Spring MVC advanced technologies include, but are not limited to, Web. XML configuration, exception handling, and cross-redirect request delivery data
1. Web. xml file Configuration
<! DOCTYPE web-app Public"-//sun Microsystems, INC.//DTD Web application 2.3//en" "Http://java.sun.com/dtd/web-app_2_3.dtd" ><web-app > <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener> <servlet> <servlet-name>appServlet</servlet-name> <ser vlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param- value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping > <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </se Rvlet-mapping></web-app>
Contextloaderlistener is the root container, and Dispatcherservlet is a child container. The Bean managed in the parent container can be referenced by the container, and vice versa. They all initialize their own context from their respective XML files.
Contextloaderlistener if the contextconfiglocation parameter is not specified, the configuration file that is loaded by default is/web-inf/applicationcontext.xml
Dispatcherservlet if the contextconfiglocation parameter is not specified, the name specified by the <servlet-name> element is/web-inf/ Folder looking for configuration files Appservlet-servlet.xml
2. Handling Exceptions
Spring provides a variety of ways to convert exceptions to responses
- A specific spring exception is automatically mapped to the specified HTTP status code
- You can add @responsestatus annotations to an exception to map an exception to an HTTP status code
- @exceptionhandler annotations can be added to the method to handle exceptions
1) A specific SPring exception is automatically mapped to the specified HTTP status code
If an exception is thrown in the controller, the exception is not in the list, and no HTTP status code is specified, the default is a status code of 500
2) Exceptions can be added @responsestatus annotations to map exceptions to an HTTP status code
@Controller
public class Hellocontroller {@RequestMapping ("/home ") public String Home () {System.out.println ( execute home throw new MyException (); // return "Home"; // Returns a String that is the logical view name }}
Package com.cn.Exception; Import Org.springframework.http.HttpStatus; Import Org.springframework.web.bind.annotation.ResponseStatus; Public class extends runtimeexception{}
Browser Access Http://localhost:8080/home
Modifying custom exceptions
Package com.cn.Exception; Import Org.springframework.http.HttpStatus; Import = httpstatus.not_found, reason = "Cause of Exception thrown")publicclassextends runtimeexception{}
Browser Access Http://localhost:8080/home
3) @exceptionhandler annotations can be added to the method to handle exceptions
- The method handles the exception in the same way that the request is handled, @ExceptionHandler the annotation's return value to a string representing the logical view name
Package com.cn.Exception; Public class extends runtimeexception{}
@Controller Public classHellocontroller {@RequestMapping ("Home") PublicString Home () {System.out.println ("Perform Home"); Throw NewMyException2 ();//return "Home";//returns a string that is the logical view name} @ExceptionHandler (MyException2.class) PublicString handlemexception () {System.out.println ("Handling Exception Logic"); return"Fail"; }}
Access Http://localhost:8080/home, background output
Browser page
@ExceptionHandler Annotated method can handle exceptions thrown by all processor methods in the same controller (annotations specify exceptions), and annotations are defined as follows
@Target ({elementtype.method}) @Retention (retentionpolicy.runtime) @Documented public @Interface exceptionhandler { Classextendsdefault {};}
- Spring also supports adding notifications to the controller, so the notification will work for all of the processor methods thrown by all controllers, as follows
The classes marked with @Controlleradvice are instantiated by component scans and given to container management. One of the most practical scenarios is to collect all the methods of the @Exceptionhandler annotation into a class so that all controller exceptions can be handled uniformly in one place. The following HandleException class definition indicates that the processor in the controller throws an exception to the MyException2 class, which is handled by the Handlemexception method and eventually jumps fail.jsp the page
PackageCom.cn.advice;ImportCom.cn.Exception.MyException2;ImportOrg.springframework.web.bind.annotation.ControllerAdvice;ImportOrg.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice Public classhandleexception {@ExceptionHandler (MyException2.class) PublicString handlemexception () {System.out.println ("Handling Exception Logic"); return"Fail"; }}
3. Pass data across redirect requests
If the forward forwarding request, then the processor method after the business process is completed, the model data specified by the method is copied into the request, as part of the request, forwarded to the next processor, the next processor can get the last processed model data from the request;
If redirect is re-submitted, the original request ends and a GET request is re-initiated. As a result, the model data in the original request disappears, and when the request arrives at the next processor, no model data is needed, and the model data must be processed by itself.
There are two scenarios for transferring data for redirection:
- Using URL templates to pass data in the form of path variables and/or query parameters
- Passing data using the Flash properties
1) Use URL templates to pass data in the form of path variables and/or query parameters
@Controller Public classHellocontroller {@RequestMapping ("/home2") PublicString home2 (model model) {Model.addattribute ("id", "12324131343256"); Model.addattribute ("Name", "Pick"); return"Redirect:home3/{id}";//A string containing redirect, indicating redirection to another processor;//if a string containing forward is moved to another processor} @RequestMapping ("/home3/{id}") Publicstring Home3 (@PathVariable string ID, model model) {SYSTEM.OUT.PRINTLN ("Id= of delivery" +ID); Model.addattribute (NewUser ()); return"Home"; }}
The browser accesses the localhost:8080/home2, grabbing the URL of the packet to be accessed. As can be seen below, when the processor is redirected, the data in the model is populated in the path variable, and the key not in the path variable is assigned to the URL in the form of a query parameter, which makes up the new URL access.
2) passing data using the Flash attribute
redirection, in 1), transmits data in a way that simply transmits simple data and cannot be passed on to objects. How can objects be passed to the next processor? Data that is to be passed to the next processor can be placed in a user session, then removed from the session by the next processor, and the data in the session is deleted. However, Spring provides the ability to send data as a Flash property without the need for us to manage the data, and the flash properties will carry the data consistently until the next request disappears.
Spring provides redirectattributes is a sub-interface of the model interface, in addition to providing all the features of the model, there are several methods to set the Flash properties.
@Controller Public classHellocontroller {@RequestMapping ("/home2") PublicString home2 (redirectattributes model) {Model.addattribute ("id", "12324131343256"); Model.addflashattribute ("User",NewUser ("Liming", "123456") ///Set flash properties, or Model.addflashattribute (new User ("Liming", "123456"))
The key is self-inferred by a worthwhile type return"Redirect:home3/{id}";} @RequestMapping ("/home3/{id}") Publicstring Home3 (@PathVariable string ID, redirectattributes model) {SYSTEM.OUT.PRINTLN ("Id= of delivery" +ID); if(Model.containsattribute ("User") {System.out.println ("Passed object:" + model.getflashattributes (). Get ("User")); } return"Home"; }
}