springmvc
1. Response data and results view
1.1 return value classification
1.1.1 return string
- The return string of the Controller method can specify the name of the logical view and the address of the physical view according to the view parser.
<a href="user/testString" >testString</a>
/** * Return String * @param model * @return */ @RequestMapping("/testString") public String testString(Model model){ System.out.println("testString Method is executed..."); // Simulate querying the User object from the database User user = new User(); user.setUsername("to one's heart's content"); user.setPassword("123"); user.setAge(30); // model object model.addAttribute("user",user); return "success"; }
1.1.2 the return value is void
- If the method return value of the controller is written as void, the program will execute the exception of 404, and the default search JSP page is not found.
- By default, it will jump to @ requestmapping (value = "/ testvoid") testvoid JSP page.
- You can use request forwarding or redirection to jump to the specified page
/** * It's void * A request forwards a request without writing the name of the item */ @RequestMapping("/testVoid") public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("testVoid Method is executed..."); // Write a program for request forwarding request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response); // redirect response.sendRedirect(request.getContextPath()+"/index.jsp"); // Set Chinese garbled code response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); // Respond directly response.getWriter().print("Hello"); }
- WEB-INF can be forwarded, but it cannot be redirected directly
1.1.3 the return value is ModelAndView object
- ModelAndView object is an object provided by Spring, which can be used to adjust the specific JSP view
- The specific codes are as follows
/** * Return ModelAndView object * You can pass in the name of the view (that is, the page to jump) and the object. * @return * @throws Exception */ @RequestMapping("/testModelAndView") public ModelAndView testModelAndView(){ // Create ModelAndView object ModelAndView mv = new ModelAndView(); System.out.println("testModelAndView Method is executed..."); // Simulate querying the User object from the database User user = new User(); user.setUsername("Xiaofeng"); user.setPassword("456"); user.setAge(30); // Storing the user object in the mv object will also store the user object in the request object mv.addObject("user",user); // Which page to jump to mv.setViewName("success"); return mv; }
1.2 forwarding and redirection provided by spring MVC framework
1.2.1 forward request forwarding
- The controller method returns the String type. You can also write it as if you want to forward the request
/** * Forward the request using the forward keyword * "forward:The forwarded JSP path "does not take the view parser, so you need to write a complete path * @return * @throws Exception */ @RequestMapping("/testForward") public String testForwardOrRedirect(){ System.out.println("testForward Method is executed..."); // Forwarding of requests return "forward:/WEB-INF/pages/success.jsp"; }
1.2.2 redirect
- The controller method returns the String type. You can also write it as if you want to redirect
/** * Redirect using keywords * @return */ @RequestMapping("/testRedirect") public String testForwardOrRedirect(){ System.out.println("testRedirect Method is executed..."); // redirect return "redirect:/index.jsp"; }
1.3 ResponseBody response json data
- DispatcherServlet will intercept all resources, leading to a problem that static resources (img, css, js) will also be intercepted and cannot be used. The solution is to configure static resources without interception. In spring MVC Add the following configuration to the XML configuration file
- mvc:resources tag configuration does not filter
- The location element represents all files under the package in the webapp directory
- The mapping element represents all request paths starting with / static, such as / static/a or / static/a/b
- mvc:resources tag configuration does not filter
<!-- Set static resources not to filter --> <mvc:resources location="/css/" mapping="/css/**"/> <!-- style --> <mvc:resources location="/images/" mapping="/images/**"/> <!-- picture --> <mvc:resources location="/js/" mapping="/js/**"/> <!-- javascript -->
- Use @ RequestBody to get request body data
- Use the @ RequestBody annotation to convert the json string into a JavaBean object
// Page loading, binding click event $(function(){ $("#btn").click(function(){ // alert("hello btn"); // Send ajax request $.ajax({ // Write json format and set properties and values url:"user/testAjax", contentType:"application/json;charset=UTF-8", data:'{"username":"hehe","password":"123","age":30}', dataType:"json", type:"post", success:function(data){ // The json data responded by the data server is parsed alert(data); alert(data.username); alert(data.password); alert(data.age); } }); }); });
/** * Simulate asynchronous request response */ @RequestMapping("/testAjax") public @ResponseBody User testAjax(@RequestBody User user){ System.out.println("testAjax Method is executed..."); // The client sends the request of ajax, and the json string is passed. The back end encapsulates the json string into the user object System.out.println(user); // Respond and simulate query database user.setUsername("haha"); user.setAge(40); // Respond return user; }
- Use the @ ResponseBody annotation to convert JavaBean objects into json strings to respond directly
- The request method needs to return the object of the JavaBean
/** * Simulate asynchronous request response */ @RequestMapping("/testAjax") public @ResponseBody User testAjax(@RequestBody User user){ System.out.println("testAjax Method is executed..."); // The client sends the request of ajax, and the json string is passed. The back end encapsulates the json string into the user object System.out.println(user); // Respond and simulate query database user.setUsername("haha"); user.setAge(40); // Respond return user; }
- In the process of converting json strings and JavaBean objects to each other, jackson's jar package needs to be used
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.0</version> </dependency>
2. File upload
2.1 review of file upload
- Import the jar package uploaded by the file
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
- Write JSP page for file upload
<h3>File upload</h3> <form action="user/fileupload" method="post" enctype="multipart/form-data"> Select File:<input type="file" name="upload"/><br/> <input type="submit" value="Upload file"/> </form>
- Write the Controller for file upload
/** * File upload * @throws Exception */ @RequestMapping(value="/fileupload") public String fileupload(HttpServletRequest request) throws Exception { // Get the file directory to upload first String path = request.getSession().getServletContext().getRealPath("/uploads"); // Create a File object and upload the File to this path later File file = new File(path); // Judge whether the path exists. If it does not exist, create the path if(!file.exists()) { file.mkdirs(); } // Create disk file item factory DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload fileUpload = new ServletFileUpload(factory); // Parse request object List<FileItem> list = fileUpload.parseRequest(request); // ergodic for (FileItem fileItem : list) { // Judge whether the file item is a common field or an uploaded file if(fileItem.isFormField()) { } else { // Upload file item // Gets the name of the uploaded file String filename = fileItem.getName(); // Upload file fileItem.write(new File(file, filename)); // Delete temporary file fileItem.delete(); } } return "success"; }
2.2 spring MVC traditional file upload
- The spring MVC framework provides a MultipartFile object, which represents the uploaded file. The variable name must be the same as the file label of the form
The name attribute has the same name. - The code is as follows
/** * SpringMVC File upload by * * @param request * @return * @throws Exception */ @RequestMapping(value="/fileupload2") public String fileupload2(HttpServletRequest request,MultipartFile upload) throws Exception { System.out.println("SpringMVC File upload by..."); // Get the file directory to upload first String path = request.getSession().getServletContext().getRealPath("/uploads"); // Create a File object and upload the File to this path File file = new File(path); // Judge whether the path exists. If it does not exist, create the path if(!file.exists()) { file.mkdirs(); } // Gets the name of the uploaded file String filename = upload.getOriginalFilename(); String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase(); // Make the name of the file unique filename = uuid+"_"+filename; // Upload file upload.transferTo(new File(file,filename)); return "success"; }
- Profile parser object
- 10*1024*1024
<!-- Configuration file parser object, requirements id Name must be multipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760"/> </bean>
2.3 spring MVC cross server file upload
- Build a picture server
- Configure the server according to the document. Now there are 2 servers
- Import the items in the data and use them as a picture server
- Realize spring MVC cross server file upload
- Import the jar package required for development
- Write JSP page for file upload
- Write controller
<dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-core</artifactId> <version>1.18.1</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.18.1</version> </dependency>
<h3>Cross server file upload</h3> <form action="user/fileupload3" method="post" enctype="multipart/form-data"> Select File:<input type="file" name="upload"/><br/> <input type="submit" value="Upload file"/> </form>
/** * SpringMVC Cross server file upload * * @param request * @return * @throws Exception */ @RequestMapping(value="/fileupload3") public String fileupload3(MultipartFile upload) throws Exception { System.out.println("SpringMVC Cross server file upload..."); // Define the request path of the picture server String path = "http://localhost:9090/day02_springmvc5_02image/uploads/"; // Gets the name of the uploaded file String filename = upload.getOriginalFilename(); String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase(); // Make the name of the file unique filename = uuid+"_"+filename; // Upload file to image server // Create client object Client client = Client.create(); // Connect to the picture server WebResource webResource = client.resource(path+filename); // Upload file webResource.put(upload.getBytes()); return "success"; }
3. Exception handler
3.1 exception handling ideas
- Controller calls service and service calls dao. Exceptions are thrown upward. Finally, DispatcherServlet finds the exception handler to handle exceptions.
3.2 exception handling of spring MVC
- Custom exception class
package xyz.slienceme.exception; public class SysException extends Exception{ private static final long serialVersionUID = 4055945147128016300L; // Exception prompt information private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public SysException(String message) { this.message = message; } }
- Custom exception handler
package xyz.slienceme.exception; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; /** * Exception handler * @author rt */ public class SysExceptionResolver implements HandlerExceptionResolver{ /** * Method of jumping to specific error page */ public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ex.printStackTrace(); SysException e = null; // Get exception object if(ex instanceof SysException) { e = (SysException) ex; }else { e = new SysException("Please contact the administrator"); } ModelAndView mv = new ModelAndView(); // Save error message mv.addObject("message", e.getMessage()); // Jump to Jsp page mv.setViewName("error"); return mv; } }
- Configure exception handler
<!-- Configure exception handler --> <bean id="sysExceptionResolver" class="xyz.slienceme.exception.SysExceptionResolver"/>
4. Interceptor
4.1 overview of interceptors
- Interceptors in spring MVC framework are used to preprocess and post process processors.
- The interceptor chain can be defined. The connector chain is to form a chain of interceptors in a certain order. When accessing the intercepted methods, the interceptors in the interceptor chain will execute in the defined order.
- The functions of interceptors and filters are similar and different
- Filters are part of the Servlet specification, and any framework can use filter technology.
- Interceptors are unique to the spring MVC framework.
- The filter is configured with / *, which can intercept any resource.
- The interceptor will only intercept the methods in the controller.
- Interceptor is also an implementation of AOP
- To customize the interceptor, you need to implement the HandlerInterceptor interface.
4.2 steps for customizing interceptors
- Create a class, implement the HandlerInterceptor interface, and override the required methods
package xyz.slienceme.demo1; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; /** * Custom interceptor 1 * @author rt */ public class MyInterceptor1 implements HandlerInterceptor{ /** * controller Method to intercept before method execution * return true Release * return false intercept * You can use forwarding or redirection to jump directly to the specified page. */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("The interceptor executed..."); return true; } }
- In spring MVC Configuring interceptor classes in XML
<!-- Configuring Interceptors --> <mvc:interceptors> <mvc:interceptor> <!-- What methods are used to intercept --> <mvc:mapping path="/user/*"/> <!-- Which methods are not intercepted <mvc:exclude-mapping path=""/> --> <!-- Register interceptor object --> <bean class="xyz.slienceme.demo1.MyInterceptor1"/> </mvc:interceptor> </mvc:interceptors>
4.3 methods in handlerinterceptor interface
- The preHandle method is the method intercepted before the controller method executes
- You can use request or response to jump to the specified page
- return true to execute the next interceptor. If there is no interceptor, execute the method in the controller.
- return false. The method in the controller will not be executed.
- postHandle is the method executed after the controller method is executed and before the JSP view is executed.
- You can use request or response to jump to the specified page
- If a page to jump to is specified, the page to which the controller method jumps will not be displayed.
- The postHandle method is executed after the JSP is executed
- request or response can no longer jump to the page
4.4 configure multiple interceptors
- Write another interceptor class
- Configure 2 interceptors
<!-- Configuring Interceptors --> <mvc:interceptors> <mvc:interceptor> <!-- What methods are used to intercept --> <mvc:mapping path="/user/*"/> <!-- Which methods are not intercepted <mvc:exclude-mapping path=""/> --> <!-- Register interceptor object --> <bean class="xyz.slienceme.demo1.MyInterceptor1"/> </mvc:interceptor> <mvc:interceptor> <!-- What methods are used to intercept --> <mvc:mapping path="/**"/> <!-- Register interceptor object --> <bean class="xyz.slienceme.demo1.MyInterceptor2"/> </mvc:interceptor> </mvc:interceptors>
Note: (previous front note portal)
1. HTML beginner
2. CSS beginner
3. JavaScript beginner
4. JQuery beginner
5. Resume school
6. CSS resumption
7. Resumption of basic education
8. Advanced resumption
9. BootStrap simple understanding