Controller method returns a value
Return ModelAndView
The method defined in ModelAndView controller and returns the object, the object may be added to model data, the specified view.
Return void
Request and response may be defined on the Controller parameter method, using the request or response in response to the specified result:
1, request forwarding page, as follows:
request.getRequestDispatcher("页面路径").forward(request, response) request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request, response);
2, can be redirected by the response page:
response.sendRedirect("url") response.sendRedirect("/springmvc-web2/itemEdit.action");
3, can be specified response through a response result, for example in response json data was as follows:
response.getWriter().print("{\"abc\":123}");
/ ** * returns void test * * @param request * @param Response * @throws Exception * / @RequestMapping ( "queryItem") public void queryItem (the HttpServletRequest request, the HttpServletResponse Response) throws Exception { // use request forwarding. 1 / / request.getRequestDispatcher ( "/ the WEB-INF / JSP / success.jsp") Forward (Request,. // response); // 2 using a redirect response to the edit page // response.sendRedirect ( "/ springmvc-web2 /itemEdit.action "); // use response displayed directly. 3 response.getWriter () Print (." {\ "ABC \": 123} "); }
Returns a string
method returns the string controller to specify the logical name of the view, the view resolved to a physical address view resolver.
// name specifies the logical view, the view through the parser is a physical path jsp: /WEB-INF/jsp/itemList.jsp return "the itemList";
Redirect Redirect
Contrller method returns a string that can be redirected to the url, the following products modified product submitted redirected to the edit page.
/ ** * Update goods * * @param Item * @return * / @ RequestMapping ( "updateItem") public String updateItemById (Item Item) { // update the product ; this.itemService.updateItemById (item) // After successfully modified goods redirected to the edit page of goods after // redirect the browser address bar is changed to redirect address, // redirect equivalent to the implementation of the new request and response, so the request parameters will be lost before // If you want to specify request parameters need to be added after the redirect url itemId = 1 this request parameter? return "the redirect: /itemEdit.action itemId =?" + the item.getId (); }
forward forwarding
Continue another Controller Controller method after method execution. Modified steering following products submitted to the product modified pages, product id parameter modifications to the product can be modified method.
/ ** * Update goods * * @param Item * @return * / @ RequestMapping ( "updateItem") public String updateItemById (Item Item) { // update the product ; this.itemService.updateItemById (item) // After successfully modified goods redirected to the edit page of goods after // redirect the browser address bar is changed to redirect address, // redirect equivalent to the implementation of the new request and response, so the request parameters will be lost before // If you want to specify request parameters need to be added after the redirect url itemId = 1 such a request parameter? // return "redirect: /itemEdit.action itemId =?" + the item.getId (); // modified product is successful, proceed to another methods // use forward manner. Browser address bar or the original request address, the forwarding // forwards did not perform a new request and response, so the request parameters are present before return "Forward: /itemEdit.action"; } // results forwarded to editItem.action , request can bring the past return "Forward: /itemEdit.action ";
Interceptor
Spring Web MVC processor interceptors like filter Filter Servlet Development, processor for preprocessing and postprocessing.
Interceptor definitions
HandlerInterceptor implement the interface, as follows:
{class HandlerInterceptor1 HandlerInterceptor from the implements public // This method is called to return the rear view and the controller performs // here obtained during execution of the abnormality information controller // herein may be recorded operation log @Override public void afterCompletion (the HttpServletRequest the arg0, the HttpServletResponse arg1, arg2 Object , Exception arg3) throws Exception { System.out.println ( "HandlerInterceptor1 afterCompletion ...."); } // controller after performing this method is called but did not return a front view // herein may be processed before being returned to the user model data processing, such as where the common information is added to the page display @Override public void The postHandle (the HttpServletRequest the arg0, the HttpServletResponse arg1, arg2 Object, ModelAndView arg3) throws Exception { System.out.println ( "HandlerInterceptor1 .... postHandle"); } // call the Controller Before performing this method returns true to continue // returns false suspend the execution // Here you can join login verification, permission interception @ override public Boolean The preHandle (the HttpServletRequest the arg0, the HttpServletResponse arg1, arg2 Object) throws Exception { System.out.println ( "HandlerInterceptor1 .... The preHandle"); // set to true, the test using the return to true; } }
Interceptor Configuration
As defined above blocker and a copy HandlerInterceptor2, pay attention to the new interceptor modify the code: System.out.println ( "HandlerInterceptor2 .... preHandle");
Configuring the interceptor in springmvc.xml
<! - Configuration interceptor -> <MVC: interceptors> : <MVC Interceptor> <! - all requests entering the interceptor -> <MVC: Mapping path = "/ **" /> ! <- - specific configuration interceptor -> <the bean class = "cn.itcast.ssm.interceptor.HandlerInterceptor1" /> </ MVC: interceptor> <MVC: interceptor> ! <- all requests entering the interceptor - > <MVC: Mapping path = "/ **" /> ! <- specific configuration interceptor -> <the bean class = "cn.itcast.ssm.interceptor.HandlerInterceptor2" /> </ MVC: interceptor> < / mvc: interceptors>
Normal flow test
Browser to access the address: http: //127.0.0.1: 8080 / springmvc-web2 / itemList.action
Run Process
Print Console:
HandlerInterceptor1..preHandle.. HandlerInterceptor2..preHandle.. HandlerInterceptor2..postHandle.. HandlerInterceptor1..postHandle.. HandlerInterceptor2..afterCompletion.. HandlerInterceptor1..afterCompletion..
Interrupt the flow test
Browser to access the address: http: //127.0.0.1: 8080 / springmvc-web2 / itemList.action
Running processes: HandlerInterceptor1 preHandler the method returns false, HandlerInterceptor2 returns true, the operation process is as follows:
HandlerInterceptor1..preHandle ..
Method preHandler seen a blocker return false from the log after the first interceptor performed only preHandler method, the other two methods do not perform all the method of the second interceptor is not performed and not performed Controller .
The method preHandler HandlerInterceptor1 return true, HandlerInterceptor2 returns false, operation process is as follows:
HandlerInterceptor1..preHandle .. HandlerInterceptor2..preHandle .. HandlerInterceptor1..afterCompletion ..
Method preHandler second interceptor seen from the log after a first return false postHandler interceptor is not performed, the second interceptor postHandler and afterCompletion not performed, and the controller is not implemented.
to sum up
- preHandle order of definition interceptors call
- postHandler interceptors defined by reverse call
- afterCompletion interceptors defined by reverse call
- postHandler in the interceptor chain all interceptors successful call back
- afterCompletion only just returned preHandle true calling
Interceptor Application
Process flow
- There is a sign in page, you need to write a login page Access Controller
- Login page there is a movement to submit the form. Need to be addressed in the Controller.
a) determine whether the correct user name and password (printed on the console)
b) If it is correct, write user information to the session (write user name username)
c) Go to Product List
Interceptor
a) intercepting a user request, determining whether the login user (login request not intercept)
b) If the user has logged in. Discharged
c) If the user is not logged in, jump to the login page.
1. Log in to write jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="${pageContext.request.contextPath }/user/login.action"> <label>用户名:</label> <br> <input type="text" name="username"> <br> <label>密码:</label> <br> <input type="password" name="password"> <br> <input type="submit"> </form> </body> </html>
2, user login Controller
@Controller @RequestMapping("user") public class UserController { /** * 跳转到登录页面 * * @return */ @RequestMapping("toLogin") public String toLogin() { return "login"; } /** * 用户登录 * * @param username * @param password * @param session * @return */ @RequestMapping("login") public String login(String username, String password, HttpSession session) { // 校验用户登录 System.out.println(username); System.out.println(password); // the user name into the session session.setAttribute ( "username", username); return "the redirect: /item/itemList.action"; } }
3, the preparation Blocker
@Override public Boolean The preHandle (the HttpServletRequest request, the HttpServletResponse Response, Object arg2) throws Exception { // Get the session request from the HttpSession session Request.getSession = (); // Get username from the session Object username = session.getAttribute ( "username "); // determines whether the username is null IF (username = null) {! // if not empty then released return to true; } the else { // if blank jump to the login page response.sendRedirect (request.getContextPath () + "/user/toLogin.action"); } return to false; }
4, the configuration interceptors
Only interception of goods url, so you need to modify ItemController, so that all requests must start with item, as shown below:
Configuring interceptors in springmvc.xml
: <MVC Interceptor> <! - interceptor interceptor article is arranged -> <MVC: Mapping path = "/ Item / **" /> <-! interceptor specific configuration -> <= the bean class " cn.itcast.ssm.interceptor.LoginHandlerInterceptor "/> </ MVC: Interceptor>
Transfer: https://www.cnblogs.com/ginb/p/7350964.html