0% found this document useful (0 votes)
4 views56 pages

1.2 Writing an Annotation Based Controller Class -@Controller @RequestMapping

The document provides a detailed guide on creating servlets using Spring MVC annotations in Eclipse, highlighting the use of @Controller and @RequestMapping annotations for defining controller classes and mapping URLs to methods. It explains how to simplify configuration by using component scanning and discusses handling dynamic URL patterns with path variables. Additionally, it covers the use of maps to retrieve multiple path variables efficiently within controller methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views56 pages

1.2 Writing an Annotation Based Controller Class -@Controller @RequestMapping

The document provides a detailed guide on creating servlets using Spring MVC annotations in Eclipse, highlighting the use of @Controller and @RequestMapping annotations for defining controller classes and mapping URLs to methods. It explains how to simplify configuration by using component scanning and discusses handling dynamic URL patterns with path variables. Additionally, it covers the use of maps to retrieve multiple path variables efficiently within controller methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 56

www.techmentor.co.

in
Creating Servlets in Eclipse 2

05/05/25
Creating Servlets in Eclipse 3

05/05/25
Simple Spring MVC Web App

Actually Spring MVC has one more way of writing


a controller class in our application
by using Spring MVC provided Annotations.
Now we will attempt to write the same controller
class which will gracefully use the ANNOTATIONS
Let us first see --------------- the same controller
class using annotation.
Creating Servlets in Eclipse 4

05/05/25
This is the annotation based HelloController class

@Controller

public class HelloController {

@RequestMapping("/welcome")

public ModelAndView helloWorld() {

ModelAndView model = new


ModelAndView("HelloPage");

model.addObject("msg","hello world");

return model;
Creating Servlets in Eclipse 5

} }
05/05/25
annotation based HelloController class
According to Spring MVC --------------
If the developer has mentioned @Controller
annotation on top of a java class --------
Then that class will be considered as a Spring
Controller.
Here there is no need to extend controller class from
any specific base class -----------
Like ---------- HelloController extends
AbstractController{
Creating Servlets in Eclipse 6

05/05/25
annotation based HelloController class

Another vital change we can introduce regarding


our annotation based controller class.
We do not need to put its entry -------- in the second
<bean> element of spring-dispatcher-servlet.xml
configuration file.

<bean name="/welcome.html"
class="com.techMentor.hellocontroller.HelloController
" />
Creating Servlets in Eclipse 7

05/05/25
annotation based HelloController class
Instead of the earlier <bean> entry ---------- we need
to put following entry in that configuration file.
<context : component-scan base-package =
"com.techMentor.hellocontroller" />

Here we are simply telling Spring Framework -------

to automatically detect all java classes having


@Controller annotation which are placed in this
package.
Creating Servlets in Eclipse 8

05/05/25
annotation based HelloController class
And also we are asking framework to consider all
of them are part of this .xml file.
If we do not mention this statement --------
We need to do the entry of every single controller
class in the .xml file
As we did in previous program for one controller class.

So here the component-scan statement plays


very vital role.
Creating Servlets in Eclipse 9

05/05/25
annotation based HelloController class

By doing this ---------- our code will be little


cleaner and concise.

Also one more change we can expect in this


annotation based code --------

We do not need to provide the first <bean>


component associated with HandlerMapping.

Creating Servlets in Eclipse 10

05/05/25
annotation based HelloController class

Now coming back to HelloController class again –


We can find @RequestMapping("/welcome")
This is very vital annotation.
When request reaches to web.xml file from a
client – browser -----------
Here request is mapped to DispatcherServlet i.e.
Front Controller.
Creating Servlets in Eclipse 11

05/05/25
annotation based HelloController class

This Front Controller reads configuration XML file


for further processing of request.

After seeing the component-scan statement here

The front controller understands that you have


used annotation based controllers in the
project in the said package.
Creating Servlets in Eclipse 12

05/05/25
annotation based HelloController class

So now it loads all those controller classes in


memory.

Now it has to decide -------


Which controller method ------- it would invoke for further
processing the request ???

And how it does is -------------

it looks at the @RequestMapping annotation value of each


method present in each controller class.
Creating Servlets in Eclipse 13

05/05/25
annotation based HelloController class

And further it compares this value with incoming


request URL pattern
public class HelloController {

@RequestMapping("/welcome")

public ModelAndView helloWorld() { …………………. }

Creating Servlets in Eclipse 14

05/05/25
annotation based HelloController class

And which ever @RequestMapping annotation


value matches with incoming request URL pattern
-------------
It simply makes a call to that method.
In this case ------------ If a user has requested for a
web page using this URL - /welcome ---
Then Front Controller would make a call to the method
associated with annotated method.
Creating Servlets in Eclipse 15

05/05/25
annotation based HelloController class

Thus the match between URL Request Pattern


and the value specified in @RequestMapping
annotation --------

will dictate the invocation of the appropriate


required method.
Here the presence of @RequestMapping annotation
is justified.
Creating Servlets in Eclipse 16

05/05/25
annotation based HelloController class
public class HelloController {
@RequestMapping("/welcome")
public ModelAndView helloWorld() {
ModelAndView model = new ModelAndView("HelloPage");
model.addObject("msg","hello world"); return model;
}

This method simply prepares ModelAndView Object


which is having the data which is to be rendered as a
response web page

And the view name which front controller would use


to prepare the response is “HelloPage”
Creating Servlets in Eclipse 17

05/05/25
annotation based HelloController class

This object is ultimately returned back to Front


Controller.

The Front Controller now would find out the exact path
of the view which is present in the project

using ViewResolver class and <Property> values ------


prefix and suffix.

Creating Servlets in Eclipse 18

05/05/25
annotation based HelloController class

This way the HelloPage.JSP is provided by Front


Controller to client – browser.

Note that ------- this response is built using


annotation based Controller class.

Creating Servlets in Eclipse 19

05/05/25
Multi - Action Controller class

Creating Servlets in Eclipse 20

05/05/25
Multi - Action Controller class

Earlier we have created a controller class using


Spring MVC Annotations.

Then we have traced out the invocation of


required method at appropriate URL Pattern.

During this process we have made use of 2


annotations
@Controller and @RequestMapping.
Creating Servlets in Eclipse 21

05/05/25
Multi - Action Controller class

While writing the controller class ----------


We have clearly discussed the purpose of putting
@RequestMapping Annotation
i.e. This annotation on top of a method which is
residing in a controller class
In short ------ If we want the specified method to be
invoked by the front controller when a client enters an
URL on browser
Then its Request Mapping Pattern has to match with
Creating Servlets in Eclipse 22

incoming request URL Pattern


05/05/25
Then the Front Controller would invoke this method for processing the
request only after finding the match bet request and annotated pattern

Creating Servlets in Eclipse 23

If the incoming request URL Pattern is like this ---------------


05/05/25
Multi - Action Controller class

The method which we write here in controller


class -------------
for the purpose of handling an incoming request

Is called as ---------- Request Handler method.

Now it reasonably obvious to ask that ---------


Can we have such multiple methods ???

Which can be mapped to different URL Patterns ???


Creating Servlets in Eclipse 24

Let us add one more request handler method in controller class


05/05/25
Here we have added one more method with name hiworld()

Creating Servlets in Eclipse 25

Just observe Request Mapping Pattern at annotation


05/05/25
Multi - Action Controller class

Like this we can write as many request handler


methods in one controller class.

In this case -------- client need to type correct URL


Pattern which should be specific to the
annotation value.

Creating Servlets in Eclipse 26

05/05/25
So in this case ----- if a client is going
to type above URL ---------

The Front Controller would make a call


to this method for further processing of
request.

And if ----- if a client is going to type the


below URL ---------

The Front Controller would make a call


to this method for further processing of
request.

Creating Servlets in Eclipse 27

05/05/25
Multi - Action Controller class

SO we can conclude that the incoming request


pattern would get match up with
@RequestMapping annotation value

Which we are specifying at the top of Request


Handling Method

With this Front Controller gives call to


corresponding method.
Creating Servlets in Eclipse 28

05/05/25
Multi - Action Controller class

Up until now ------- we were placing the


@requestMapping Annotation on the top of
method
So that it would be treated as Method Level
Annotation.

However ------- Spring also supports an


annotation which is treated as Class Level
Annotation
Creating Servlets in Eclipse 29

05/05/25
Class Level Annotation

Now ---------- None of our earlier URL patterns will match because the
class level annotation will override the method level annotation
Creating Servlets in Eclipse 30

05/05/25
Class Level Annotation in Spring MVC

Here --------- the Method Level Annotations are


relative to the Class Level Annotations.

Means -------- if we want make a call to


helloworld() method ------------- then URL request
should be like as follows

Creating Servlets in Eclipse 31

05/05/25
Multi - Action Controller class

SO if we are using Class Level Annotations as well


-------------

The pattern specified in Class Level Annotation


should precede the pattern in individual
Method Level Annotation.

Creating Servlets in Eclipse 32

05/05/25
Creating Servlets in Eclipse 33

05/05/25
Creating Servlets in Eclipse 34

05/05/25
Creating Servlets in Eclipse 35

05/05/25
Use of one more Annotation

Now let us make a small change in the pattern at


method level annotation.
@RequestMapping("/welcome /countryName/userName “)

I have added countryName and userName in


the pattern.

Now what will be the response of the browser ?


Creating Servlets in Eclipse 36

05/05/25
Use of one more Annotation

Even for this change ---------- our application


behaves properly with following Browser URL
http://localhost:8181/FifthSpringMVCProject/welcome/countryName/userName

Now we will have more specific change in URL


Pattern at browser.
SO that we enter value of username instead of
hardcoded “username” string.
Creating Servlets in Eclipse 37

05/05/25
Use of one more Annotation

So the URL
http://localhost:8181/FifthSpringMVCProject/welcome/countryName/userName

Is now used as
http://localhost:8181/FifthSpringMVCProject/welcome/countryName/sachin

Now will the application will invoke the intended


method ???

Off course not !!! And this is but obvious !!!


Creating Servlets in Eclipse 38

05/05/25
Use of one more Annotation

Now ----------- what if I want to make it with


this URL only by treating “sachin” as a value
of the string in URL
Instead of hardcoded value in URL

How would I do that ??

Answer is using curly braces over “userName”


String
Creating Servlets in Eclipse 39

05/05/25
Use of one more Annotation

If I put curly braces on the “userName” string


Then the end user is allowed to substitute the value of
userName with any other value.

So now after this change -------- when I request using


this URL ------------ the Front Controller should happily
make a request to this method.

Creating Servlets in Eclipse 40

05/05/25
Use of one more Annotation

What if in this method ---------- I would want


to retrieve the value of {userName} coming
from incoming request.

This can be done using @pathvariable


annotation.

Creating Servlets in Eclipse 41

05/05/25
Use of one more Annotation
This annotation can be placed inside the code as
follows….
public ModelAndView
helloWorld(@PathVariable(“userName”) String name {

Here with this annotation ------- I am asking Spring


Framework ------- When the front Controller would invoke
this method --------- then please bind the username value
which is coming from incoming request URL with this
Creating Servlets in Eclipse 42

name variable
05/05/25
Use of one more Annotation

And further ----------- in the method I should


be able to use this name variable which is
having userName value.

Here the @Pathariable Annotation binds


userName value coming from incoming
request with name variable.
Creating Servlets in Eclipse 43

05/05/25
Use of one more Annotation

Further we can send this userName value


back to client with response message.

When we check these things on browser


-------- We will definitely find that the
application is responding as per
expectations.
Creating Servlets in Eclipse 44

05/05/25
http://localhost:8181/FifthSpringMVCProject/welcome/countryName/sachin

Creating Servlets in Eclipse 45

05/05/25
Use of one more Annotation

What if I do the same thing with


countryName Here ??????
As we did with userName

Now the user will provide the value of


countryName aslo in URL instead of hardcoded
string.

And further our method would retrieve both


Creating Servlets in Eclipse 46

userName and countryName.


05/05/25
Use of one more Annotation

So now include coutryNmae also in curly


braces.

Then put one more @PathVariable


annotation for countryName.

And then include the country variable in the


response message.
Creating Servlets in Eclipse 47
We are done !!!
05/05/25
Creating Servlets in Eclipse 48

05/05/25
Use of one more Annotation

Now one more variant regarding


@PathVariable annotation.

What if we are tied of putting many


@PathVariable annotations ------------ in
method arguments as we did earlier -------

Creating Servlets in Eclipse 49

05/05/25
Use of one more Annotation

In this case Spring says ------------ If you put


the PathVariable Annotation on a map ----

Then Spring will put all these path variables


----------- which we have put in the curly
braces ------------

In the specified map ------------ as a name


value pair
Creating Servlets in Eclipse 50

05/05/25
Creating Servlets in Eclipse 51

05/05/25
Use of one more Annotation

So what it means is ---------

In the method body ------------ we can simply


retrieve a particular path variable ----------

by providing its name as a key to the Map

So here in the Map ----------- nothing has


changed from earlier.
Creating Servlets in Eclipse 52

05/05/25
Use of one more Annotation

Earlier I was retrieving the value od


countryName and userName by providing
many path variable annotations in the
method argument.

Now ------- I am retrieving all those values


using one path variable annotation on a
pathvars Map
Creating Servlets in Eclipse 53

05/05/25
Creating Servlets in Eclipse 54

05/05/25
Use of one more Annotation

And here ------------ I am retrieving the values


of countryName and userName ---------

by providing ------------ the name to the Map


as a Key.

Creating Servlets in Eclipse 55

05/05/25
Use of one more Annotation

One important aspect of Map with


@PathVariable Annotation

We need place MVC Annotation Driven tag in


the configuration file like this

<mvc:annotation-driven/> ------ just below


the component-scan statement
Creating Servlets in Eclipse 56

05/05/25

You might also like