SPRINGMVC is a dispatcherservlet-based MVC framework that each request is first visited by Dispatcherservlet, Dispatcherservlet is responsible for forwarding each request to the corresponding Handler,handler processing and then returning the corresponding view and model, the returned view and model can not be specified, That is, you can return only the model or only the view or none of the returns. In SPRINGMVC using annotations, processor handler is based on @controller and @requestmapping annotations, @Controller declares a processor class, @RequestMapping declares the mapping of the corresponding request , which provides a very flexible way to match and handle.
Dispatcherservlet is inherited from the HttpServlet, since SPRINGMVC is based on Dispatcherservlet, then we first configure the Dispatcherservlet, So that it can manage what we want it to manage. The HttpServlet is declared in the Web. xml file.
<servlet><servlet-name>blog</servlet-name><servlet-class> org.springframework.web.servlet.dispatcherservlet</servlet-class><load-on-startup>1</ load-on-startup></servlet><servlet-mapping><servlet-name>blog</servlet-name>< Url-pattern>*.do</url-pattern></servlet-mapping>
The above declares a dispatcherservlet named blog that will handle all requests that end with ". Do". When initializing the Dispatcherservlet, SPRINGMVC defaults to the/web-inf directory looking for a call [servlet-name]- The Servlet.xml configuration file that initializes the Bean object inside the file that overwrites the Bean object declared in the spring configuration file with the same name as the Bean object. As above will look for a file called Blog-servlet.xml in the/web-inf directory, of course, you can also declare the location of the configuration file in the servlet, that is, by The initialization parameters of the servlet to set the value of the Contextconfiglocation parameter.
<servlet><servlet-name>blog</servlet-name><servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class><init-param><param-name> contextconfiglocation</param-name><param-value>/web-inf/blog-servlet.xml</param-value></ init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping>< Servlet-name>blog</servlet-name><url-pattern>*.do</url-pattern></servlet-mapping>
Dispatcherservlet will use some special beans to process request requests and generate corresponding view returns.
With regard to the return of the view, the controller is only responsible for passing back a value, and then exactly what view is returned, is controlled by the view parser, the common view parser in JSP is Internalresourceviewresovler,
It will require a prefix and a suffix
<beanclass= "Org.springframework.web.servlet.view.InternalResourceViewResolver" ><property name= "prefix" Value= "/web-inf/"/><property name= "suffix" value= ". JSP"/></bean>
In the view parser above, if the controller returns BLOG/INDEX, the view after parsing through the view parser is/web-inf/blog/index.jsp.
The SPRINGMVC to use annotations needs to be declared in the SPRINGMVC configuration file by first introducing the MVC namespace and then declaring it with <mvc:annotation-driven/>.
<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:context=" Http://www.springframework.org/schema/context "<span style=" Background-color: #00ff00; " ><span style= "color: #ff0000;" >xmlns:mvc= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/MVC" </span></span>xsi:schemalocation= "http// Www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-3.0.xsd <span style= "background-color: #00ff00; color: #ff0000;" > Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd "</span>><mvc:annotation-driven/></beans>
Mainly talking about controller.
In SPRINGMVC, the controller does not need to inherit what class, do not need to implement what interface, all use the @controller tag class are controller
@Controllerpublic class BlogController {}
With the controller, then exactly how to request a controller specific method, which is marked by @requestmapping, @RequestMapping can be marked on the class, can also be marked on the method, When @requestmapping is marked on both the method and the class, then the corresponding URL is the addition method on the class, such as the following index method, the corresponding URL should be/blog on the class plus the/index on the index method, so it should be/blog /index, so the BlogController index method is accessed when the/blog/index.do is requested. The @RequestMapping added to the class is not required, and when @requestmapping is added to the controller class, the @ on the Controller method Requestmapping is relative to the class of @requestmapping, that is, the previous request mapping is the address on the class and method address, and when the Controller class does not add @requestmapping time, The @requestmapping on the method is the absolute path.
@Controller @requestmapping ("/blog") public class BlogController {@RequestMapping ("/index") public String Index (MAP <string, object> map) {return "Blog/index";}}
In the above code, if there is no requestmapping annotation on the index method, but only on the BlogController class, and the class has only one method, the URL on the direct request class calls the method inside, that is, the direct request/ The index method is called when blog.do.
In Requestmapping, you can also specify a property method whose primary value is Requestmethod.get and Requestmethod.post, this property can be used to strictly control a method can only be tagged request path corresponding to the request method to access, such as the value of the specified method is get, it means that only through the Get method can be accessed by default is accessible.
The URL mappings in requestmapping also support wildcard characters *, such as:
@Controller @requestmapping ("/blog") public class BlogController {@RequestMapping ("/*/index") public String Index (MAP <string, object> map) {return "Blog/index";}}
There is also a property params in @requestmapping that allows you to specify that a parameter must be included in the request parameter
, or must not contain a parameter, or what the value of a parameter must be, to narrow the specified mapping range.
@Controller @requestmapping ("/blog") public class BlogController {@RequestMapping (value= "/index", params= "param1= Value1 ") Public String Index (map<string, object> Map) {return" Blog/index ";}}
In the example above, the corresponding index method can be accessed only if the request is/blog/index.do and the value of the request parameter param1 is value1.
If the value of the params is "param1", it means that the request parameter can be as long as it contains param1, as to what its value is, and if the value of the params is "!param1",
Indicates that the request parameter must not contain param1. You can also use the header to narrow the mapping @RequestMapping, such as:
@Controller @requestmapping ("/blog") public class BlogController {@RequestMapping (value= "/index", headers= " Content-type=text/html ") Public String Index (map<string, object> Map) {return" Blog/index ";}}
The annotations commonly used in SPRINGMVC are also @pathvariable, @RequestParam, @PathVariable marked on the parameters of the method,
Using the parameters It flags can be used to pass the value of the request path, see the following example
@RequestMapping (value= "/comment/{blogid}", method=requestmethod.post) public void comment (Comment comment,@ pathvariable int BlogId, HttpSession session, HttpServletResponse response) throws IOException {}
In this example, blogID is marked as a request path variable by @pathvariable, and if the request is/blog/comment/1.do, the value of blogID is 1,
@PathVariable at the time of the assignment, if the next variable is not specified as above, which is the corresponding URL, the default is to take the same variable name from the URL followed by the next variable.
As in the example above, @pathvariable int blogId does not indicate which of the variables in the URL to get, the default is to assign the value of the blogId variable in the URL to the BlogId in the method parameter,
If the name of the method parameter is not the same as the variable name in the access path defined in requestmapping, or if I want to use pathvariable to explicitly specify which of the following method arguments corresponds to which variable in the URL,
You can do this in pathvariable, given a value= "blogId" (only one argument can be omitted) value explicitly specifies that the ID variable in the method parameter is the BLOGID variable in the corresponding request path definition.
@RequestMapping (value= "/comment/{blogid}", method=requestmethod.post) public void comment (Comment comment,@ Pathvariable ("blogId") int ID, HttpSession session, HttpServletResponse response) throws IOException {}
The same @requestparam is used to pass values to the parameter, but it is the value from the parameter of the request from the beginning, which is equivalent to the Request.getparameter ("parameter name") method. Its value rule is the same as @pathvariable,
When not specified, the default is to take a parameter value from the request with the same name as the variable name followed, using @requestparam ("parameter name") when you want to explicitly take a parameter from the request, as follows:
@RequestMapping ("/show") public void Showparam (@RequestParam int id, @RequestParam ("name") String username) {// When this method is used for URL request access, the value of the parameter ID is assigned to the parameter variable ID from request, and the value of the parameter name from request is assigned to the parameter variable username}
In the controller's method, if you need web elements httpservletrequest,httpservletresponse and HttpSession, you just need to give the method a corresponding parameter, Then the SPRINGMVC will automatically pass the value when it is accessed, but it is important to note that the session will be called when the session is accessed for the first time, because the session has not yet been generated.
Next, we discuss the return value of the method, mainly in the following cases:
- Returns a Modelandview, where model is a map, which holds a pair of pair of key-value pairs, which can be used directly on the page, view is a string that represents the name of a particular view
- Return a string, this time if you need to pass a value to the page, you can give the method a map parameter, the map is equivalent to a model, the model is stored in a key value pair can be accessed on the page
- Returns a View object
- Return a model is a map, this time will resolve the default generated view name, the default view name is the method name, here was wrong, thank the Netizen correction.
- The default view name is parsed by the Requesttoviewnametranslator, as the name implies, translating the request into ViewName, when no requesttoviewnametranslator is specified, Spring will use its own default implementation of the default configuration of Defaultrequesttoviewnametranslator, which takes the URI of the current request, removing the first and last Slash "/", and the corresponding suffix. So when you request "HTTP://LOCALHOST/APP/ABC", the corresponding default viewname is the request uri--"/ABC" to remove the first and last slash and suffix after the result, namely "ABC", Request "http://localhost/ APP/ABC/EFG, the default view name is "ABC/EFG", "http://localhost/app/abc/efg/hi.html" and "Abc/efg/hi". If you need to change the way the default view name is resolved, you can configure a bean in the Springmvc configuration file named Viewnametranslator, which is of type Requesttoviewnametranslator. If the bean is defaultrequesttoviewnametranslator, you can specify a prefix for the view name through the prefix property, specifying the suffix by suffix, Specify whether you want to remove the front slash from the Stripleadingslash, and see the implementation of the Defaultrequesttoviewnametranslator for more properties you can specify. Of course you can also define your own Requesttoviewnametranslator implementation class to implement the Getviewname of the Requesttoviewnametranslator interface (httpservletrequest Request) method to implement your own logic to get the default view name.
- Nothing is returned, this time you can write the return directly to HttpServletResponse in the method body, otherwise it will be determined by Requesttoviewnametranslator.
- Any other type of object. At this point, the method return type object is returned to the view as a property of the return model model, which can be specified by a given @modelattribute annotation on the method, otherwise the return class name will be used by default as the property name.
The following is a simple example
@RequestMapping ("/{owner}/index") public String Userindex (map<string, object> Map, @PathVariable string owner, HttpServletRequest request) throws parserexception {list<defcategory> categories = Categoryservice.find (owner); int offset = Util.getoffset (request); pager<blog> Pager = blogservice.find (owner, 0, offset, maxResults); int totalrecords = Pager.gettotalrecords (); list<blog> blogs = pager.getdata (); Util.shortblog (blogs); list<message> messages = Messageservice.find (owner, 0, 5). GetData (); Util.shortmessage (Messages), Map.put ("messages", messages), Map.put ("Totalrecords", totalrecords); List<blogstore> stores = Storeservice.find (owner, 0, 5). GetData (); Map.put ("MaxResults", maxResults); Map.put (" Blogs ", blogs), Map.put (" Totalrecords ", totalrecords); Map.put (" Owner ", Userservice.find (owner)); Map.put (" Defcategories ", categories); Map.put (" Stores ", stores); return" Blog/userindex ";}
To pass a value to a page
After the request is forwarded to the business logic layer in the controller, it is necessary to show the result of the business logic layer, and in the process of presentation, we need to pass the processing result to the presentation layer.
So how does the processing result pass? It's already been said that the controller's return result can be a modelandview that contains the model and view, or it can be just a view, and of course nothing is returned.
It is also possible to return only one model. We know that model is used to encapsulate the data to show the view, then, in the SPRINGMVC, if we want to pass the backstage information to the foreground to show, what should we do?
? There are two main ways of doing this:
1. Return the Modelandview that contains the model, or return directly to one of the models (this is the time to consider the default view), and the return result of this type contains the model, and the corresponding attribute column in the model object
Can be used directly inside the view.
2. If you are returning directly to a view, this time SPRINGMVC provides a mechanism similar to getting the HttpRequest object in the Controller method, this time we only need to give the Controller method a map parameter,
The map is then added to the method body and a key-value pair that needs to be passed to the view, so that the corresponding key-value pairs can be accessed directly in the view.
SPRINGMVC Study Summary (iv)--A brief introduction to SPRINGMVC based on annotations