This article introduces examples of forwarding redirection and interceptor in Springmvc. It is shared with you, as follows:
Variable parameters When designing methods, use数据类型... to declare parameter types, for example: public static void function(int... numbers)
When implementing the method body, the variable parameters are processed as an array
public class Test{ public static void main(String[] args){ System.out.println(Test.sum(1,2,3)); System.out.println(Test.sum(1,2,3,4,54)); } public static int sum(int... numbers){ int sum=0; for(int i=0;i<numbers.length;i++){ sum+=numbers[i]; } return sum; }}Note: In each method, only 1 variable parameter is allowed at most, and if there is a variable parameter, it must be the last parameter.
Forwarding and redirecting
In the method of handling requests within the controller, the default method of returning a string is forwarding. The forwarded value is the name of the view component, such as return "login", which will essentially obtain the page that is finally displayed based on the view resolver (ViewResolver). The syntax of the return redirect: path represents redirect. The content on the right side of redirect: is the path. This path usually uses a relative path, and is referenced based on the path in the address bar of the current client as the standard. For example, the current address is: http://localhost:8080/Project/user/reg.do, and then return "redirect:login.do" , and then redirect to http://localhost:8080/Project/user/login.do ,If you return "redirect:/main/index.do" or return "redirect:../main/index.do", you will redirect to http://localhost:8080/Project/main/index.do
forward:
The default method, but you can also use return "forward:login"
The returned view must be a view, which will be forwarded to the specified view after passing through the view parser.
redirect:
Redirect: return "redirect:login.do"
Returns a path to the Controller method, not a view. This will not pass through the view parser, but will jump directly.
Example
@RequestMapping(value="/handle_reg.do", method=RequestMethod.POST) public String handleReg(User user,ModelMap map){ try { userService.reg(user); System.out.println("Registered successfully!"); return "redirect:login.do"; //Redirect to the control method of login.do, login.do corresponds to forward to login.jsp } catch (UsernameConflictException e) { System.out.println(e.getMessage()); map.put("errorMessage", e.getMessage()); return "error"; } } @RequestMapping(value="login.do") public String handleLogin(){ return "login"; }Interceptor
Basic concepts
Using interceptor
Custom interceptor class
Create an intercept class (DemoInterceptor) to implement the HandlerInterceptor interface
public class DemoInterceptorimplements HandlerInterceptor{ /** * Called before the processor executes * @param request HttpServletRequest object, which can obtain request parameters, etc. * @param response HttpServletResponse object* @param Handler Interceptor Controller object* @return If false is returned, the processing flow will be interrupted and subsequent interceptors and controllers will not be processed. If true is returned, subsequent interceptors and processors will be executed */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("PreHandler execution of DemoInterceptor"); return true; } /** * Called after the processor is executed, and call before jumping to the specified view* @param request HttpServletRequest object* @param response HttpServletResponse object* @param response HttpServletResponse object* @param Handler Interceptor Controller object* @param modelAndView ModelAndView object, which stores the processing results and view information*/ public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { /** * 1. You can design your own logic, for example, in some cases, return false, return true * 2. Return true means that the subsequent processor and interceptor are executed, return false will interrupt the processing flow*/ System.out.println("handler:"+handler); System.out.println("PostHandler execution of DemoInterceptor"); //Set the view name, then after the execution is completed, it will jump to the index.jsp page//modelAndView.setViewName("index"); } /** * Call * After the request processing is completed, public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("DemoInterceptor's afterCompletion execution"); }}Configure in springmvc configuration file
Configuration
Must be configured in the above order, otherwise an error will be reported
<!-- Configure the interceptor, where multiple interceptors can be configured --><mvc:interceptors> <mvc:interceptor> <!-- Configure the interceptor path, and intercept all processor method mappings under /user, for example: http://localhost:8080/Springmvc/user/login.do, this request will be intercepted --> <mvc:mappingpath="/user/*"/> <!-- Configure the controller method that is not intercepted by the interceptor, this is an optional configuration, such as http://localhost:8080/Springmvc/user/index.do, this will not be intercepted --> <mvc:exclude-mappingpath="/user/index.do"/> <mvc:exclude-mappingpath="/user/login.do"/> <!-- Configure the bean of the interceptor, specifying the full class name--> <beanclass="cn.tedu.spring.interceptor.DemoInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>
The implementation method
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler)
public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView)
public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)
Demo login check
Custom Interceptor (LoginInterceptor)
The specific process is written very clearly in the prehandler method
public class LoginInterceptorimplements HandlerInterceptor{ /* * Called before the processor is executed (non-Javadoc) * 1. Get session * 2. Read the uid value in the session * If null, it means that there is no login, then directly redirect to the login interface and return false at the same time. There is no need to execute the subsequent process* If not null, it means that it has been logged in, then directly return true and continue to execute the subsequent interceptor or processor*/ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session=request.getSession(); //Get session Object uid=session.getAttribute("uid"); //Read the object in session//If uid exists, then you can log in and complete if (uid!=null) { return true; //Return true, if the login is successful, you need to execute the subsequent process} response.sendRedirect(request.getContextPath()+"/user/login.do"); //Redirect to the login interface return false; //Return false, the subsequent process does not need to be executed, and it is directly interrupted} public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }}Configure interceptor in springmvc
Since here it just jumps to the user center and needs to verify the login, it just matches user_center.do
<!-- Configure interceptors, where multiple interceptors can be configured --> <mvc:interceptors> <mvc:interceptor> <mvc:mappingpath="/user/user_center.do"/> <beanclass="cn.tedu.spring.interceptor.LoginInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>
Execution order of multiple interceptors
Execute according to the order configured in the springmvc configuration file, that is, the order of interceptors configured under <mvc:interceptors>. If an interceptor is performed on the same path, then the first-configured first-interceptor
The difference between interceptor and filter (main difference)
Summarize
Interceptors can be used when multiple requests require the same or extremely similar tasks.
Develop an interceptor well, then you need to configure it in the configuration file of springmvc
In <mvc:interceptors>, if several <mvc:interceptors> are configured, multiple interceptors will form an interceptor chain. If multiple interceptors are configured, they will intercept the same path, and then they will be executed in the order of the configured nodes.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.