Overview
Spring 2.5 Introduces note-driven functionality for spring MVC after Spring 2.0 's major upgrade to spring MVC. Now you don't have to have the controller inherit any interfaces, you don't need to define the mapping of the request and controller in the XML configuration file, just using annotations can make a POJO with most of the functions of the controller--spring the ease of use of the MVC framework Further enhancements. In framework flexibility, ease-of-use, and extensibility, spring MVC has gone beyond the other MVC frameworks, and with spring singing Mengjin, it is anticipated that spring MVC's appeal to the MVC market will become increasingly irresistible.
This article introduces the new sping MVC annotations feature in Spring 2.5, which describes how to replace the traditional XML-based Spring MVC configuration with the annotation configuration.
Back to top of page
A simple note-based Controller
Readers with too-low versions of Spring MVC know that when creating a Controller, we need to implement the Org.springframework.web.servlet.mvc.Controller interface directly or indirectly. In general, we define our controllers by inheriting Simpleformcontroller or Multiactioncontroller. After defining the controller, an important event is to define the mapping of the request and the controller through handlermapping in the Spring MVC configuration file in order to correlate the two.
Take a look at how annotation-based controllers are defined to do this, and the following are the Bbtforumcontroller that use annotations:
Listing 1. Bbtforumcontroller.java
package com.baobaotao.web;
Import Com.baobaotao.service.BbtForumService;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Controller;
Import Org.springframework.web.bind.annotation.ModelAttribute;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RequestMethod;
Import java.util.Collection;
@Controller//<--① @RequestMapping ("/forum.do") public class Bbtforumcontroller {@Autowired
Private Bbtforumservice Bbtforumservice;
@RequestMapping//<--②public String Listallboard () {Bbtforumservice.getallboard ();
System.out.println ("Call Listallboard method.");
return "Listboard"; }
}
|
From the above code, we can see that Bbtforumcontroller and the general class is no different, it does not implement any special interface, and thus is an authentic POJO. The magic wand that makes this POJO unique is the annotation of Spring MVC.
Two annotations were used at the ①, namely @Controller and @RequestMapping. In the article "using the Spring 2.5 note-driven IoC", I have pointed out that @Controller, @Service, and @Repository and @Component annotations are equivalent: To make a class the Bea of a Spring container N. Because the Controller of Spring MVC must be a Bean beforehand, @Controller annotations are indispensable.
It is @RequestMapping this annotation that really lets Bbtforumcontroller have the Spring MVC Controller function. @RequestMapping can be labeled at the class definition, associating a Controller with a specific request, and can be labeled at the method signature to further divert the request. At ①, we let Bbtforumcontroller associate the "/forum.do" request, and ②, we specifically specify the Listallboard () method to process the request. So the @RequestMapping labeled at the class declaration is equivalent to having POJO implement the Controller interface, and the @RequestMapping at the method definition is equivalent to having the POJO extend the Spring predefined controller (such as Simp Leformcontroller, etc.).
In order for annotation-based spring MVC to really work, you need to do something in the Xxx-servlet.xml configuration file that spring MVC corresponds to. Before you go, take a look at the configuration of Web. XML:
Listing 2. Web. XML: Enabling the Spring container and Spring MVC framework
<?xml version= "1.0" encoding= "UTF-8"?> <web-app xmlns= "Http://java.sun.com/xml/ns/javaee" XM Lns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http:/ /java.sun.com/xml/ns/javaee/web-app_2_5.xsd "version=" 2.5 "> <display-name>spring Annotation MVC Sample< /display-name> <!--Spring Service Tier profile--<context-param> <param-name>contextconfigloc Ation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context- param> <!--Spring container start listener--<listener> <listener-class>org.springframework. Web.context.ContextLoaderListener </listener-class> </listener> <!--a servlet for Spring MVC, It will load the Web-inf/annomvc-servlet.xml configuration file to start the Spring MVC module--<servlet> <SERVLET-NAME>ANNOMVC&L T;/servlet-name> ≪servlet-class>org.springframework.web.servlet.dispatcherservlet </servlet-class> <load-on-s tartup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>annomvc&
lt;/servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app> |
A spring MVC module named ANNOMVC is defined in Web. XML, and according to the spring MVC contract, the specific configuration of the Spring MVC module needs to be defined in the Web-inf/annomvc-servlet.xml configuration file. The configuration content of Annomvc-servlet.xml is as follows:
Listing 3. Annomvc-servlet.xml
<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "http://www.springframework.org/schema/
Beans "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xmlns:p=" http://www.springframework.org/schema/p " xmlns:context= "Http://www.springframework.org/schema/context" xsi:schemalocation= "http// Www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www
. Springframework.org/schema/context Http://www.springframework.org/schema/context/spring-context-2.5.xsd "> <!--①: Scan all classes in a Web package to complete bean creation and automatic dependency injection-<context:component-scan base-package= "Com.baobaotao.web"/&G
T
<!--②: Start the annotation feature of spring MVC, complete the mapping of requests and annotations Pojo-<bean class= "org.springframework.web.servlet.mvc.annotation. Annotationmethodhandleradapter "/> <!--③: Parsing the name of the model view, that is, adding the Model view name before and after <bean class=" ORG.SPRINGFR Amework.web.servlet.view.InternalResourceViewResolver "p:prefix="/web-inf/jsp/"p:suffix=". jsp "/> </beans>
|
Because all of Spring's functions evolve on the basis of the bean, the Controller must be turned into a bean beforehand, which is done by labeling the @Controller in the class and enabling the component scanning mechanism in Annomvc-servlet.xml, as ① Shown
At ②, a annotationmethodhandleradapter is configured to process the beans based on the Spring MVC annotations in the bean, making them into controllers and mapping specific URL requests.
And the work at ③ is to define the parsing rules for the name of the model view, where we use the special namespace of Spring 2.5, the P-namespace, which transforms the contents of the <property> element configuration into a <bean> property configuration, to some extent Configuration of the <bean>.
Starting Tomcat, sending a http://localhost/forum.do URL request, Bbtforumcontroller's Listallboard () method responds to this request and turns to web-inf/jsp/ The listboard.jsp view page.
Back to top of page
Have a Controller handle multiple URL requests
In the lower version of Spring MVC, we can let a Controller handle multiple URL requests by inheriting Multiactioncontroller. This feature is much easier to implement with @RequestMapping annotations. Take a look at the following code:
Listing 3. Each request processing parameter corresponds to a URL
Package com.baobaotao.web;
Import Com.baobaotao.service.BbtForumService;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;
@Controller public class Bbtforumcontroller {@Autowired private bbtforumservice bbtforumservice;
@RequestMapping ("/listallboard.do")//<--①public String Listallboard () {Bbtforumservice.getallboard ();
System.out.println ("Call Listallboard method.");
return "Listboard"; } @RequestMapping ("/listboardtopic.do")//<--②public String listboardtopic (int topicid) {bbtforums
Ervice.getboardtopics (TOPICID);
System.out.println ("Call Listboardtopic method.");
return "Listtopic"; }
} |
Here, we annotate @RequestMapping annotations for the Listallboard () and Listboardtopic () methods at ① and ② respectively, specifying the URL requests processed by the two methods, which is equivalent to Bbtforumcontroller Transformed into a multiactioncontroller. Such/listallboard.do URL requests are handled by Listallboard (), while/listboardtopic.do?topicid=1 URL requests are handled by the Listboardtopic () method.
For controllers that handle multiple URL requests, we tend to specify the name of the controller processing method (such as Method=listallboard) through a URL parameter rather than specifying the handler of the controller directly from a different URL Method. It is easy to implement this common requirement with @RequestMapping annotations. Look at the following code:
Listing 4. A Controller corresponds to a URL, which determines the request processing method by the request parameter
Package com.baobaotao.web;
Import Com.baobaotao.service.BbtForumService;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;
@Controller @RequestMapping ("/bbtforum.do")//<--① specifies that the controller corresponds to a URL request public class Bbtforumcontroller {@Autowired
Private Bbtforumservice Bbtforumservice; <--② if the URL request includes "Method=listallboard" parameters, this method handles @RequestMapping (params = "method=listallboard") public St
Ring Listallboard () {Bbtforumservice.getallboard ();
System.out.println ("Call Listallboard method.");
return "Listboard";
}//<--③ If the URL request includes "method=listboardtopic" parameters, this method handles @RequestMapping (params = "method=listboardtopic")
Public String listboardtopic (int topicid) {bbtforumservice.getboardtopics (topicid);
System.out.println ("Call Listboardtopic method."); Return"Listtopic";
}
} |
The @RequestMapping labeled at the class definition let Bbtforumcontroller handle all URL requests that contain/bbtforum.do, while the request processing method in Bbtforumcontroller has a split rule for URL requests in ② and The ③ defines the triage rule according to the URL's method request parameter. So using @RequestMapping annotations at the class definition and at the method definition makes it easy to specify how the Controller is handled by the URL parameter.
In addition to the params attribute in @RequestMapping annotations, there is also a common property, method, which allows the Controller method to handle requests for a specific HTTP request, such as having one method handle an HTTP GET request, and another handling the HTTP The POST request is as follows:
Listing 4. Let the request processing method handle a specific HTTP request method
Package com.baobaotao.web;
Import Com.baobaotao.service.BbtForumService;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping ("/bbtforum.do") public
class Bbtforumcontroller {
@RequestMapping (params = "Method=createtopic", method = requestmethod.post) public
String Createtopic () {
System.out.println ("Call Createtopic method. ");
return "Createtopic";
}
}
|
This will only be handled by the Createtopic () method when the/bbtforum.do?method=createtopic request is submitted as an HTTP POST.
Back to top of page
How to bind a URL parameter to a processing method entry parameter
Binding by contract
When a Controller's method is annotated with @RequestMapping annotation, it can process a specific URL request. We can not help but ask: How to bind the URL parameter to the request processing method. Before you answer this question, take a look at the following code:
Listing 5. Bind by parameter name match
The @RequestMapping (params = "method=listboardtopic")
//<--①topicid how the incoming parameter binds the URL request parameter. Public
String listboardtopic (int topicid) {
bbtforumservice.getboardtopics (topicid);
System.out.println ("Call Listboardtopic method.");
return "Listtopic";
}
|
When we send a URL request for http://localhost//bbtForum.do?method=listBoardTopic&topicId=10, Spring not only lets Listboardtopic () The TopicID method handles this request and also binds the request parameter to the TOPICID entry of the Listboardtopic () method after the type conversion. The return type of the Listboardtopic () method is String, which will be parsed into the name of the logical view. That is to say, Spring has a set of potential rules for how to assign automatic values to processing methods and how to convert the return value of the processing method into Modelandview, and it is not possible to develop the annotation-based request processing method without being familiar with this rule, so understanding this potential rule is undoubtedly an understanding The Spring MVC Framework is based on the core issue of annotation functionality.
Let's start with the most common: the type of the request processing method entry can be a Java base data type or a string type, when the method parameter is bound to the URL request parameter by the parameter name matching principle, and also automatically completes the String type URL The conversion of the request parameter to the request processing method parameter type. Here are a few examples: listboardtopic (int topicid): and topicid URL request parameter bindings; listboardtopic (int topicid,string boardname): respectively and TopicID, Boardname URL request parameter binding;
In particular, if the entry is a basic data type (such as int, long, float, etc.), the URL request parameter must have a corresponding parameter, otherwise the typemismatchexception exception will be thrown, indicating that null cannot be converted to the base data type.
In addition, the parameter of the request processing method can be a JavaBean, as the following User object can be used as an entry parameter:
Listing 6. User.java: a JavaBean
Package com.baobaotao.web;
public class User {
private int userId;
Private String userName;
Omit Get/setter method Public
String toString () {
return this.username + "," +this.userid;
}
}
|
Here is the entry for the User as the Listboardtopic () Request Processing method:
Listing 7: Using JavaBean as the parameter of the request processing method