SPRINGMVC Mapping Processor (ii)

Source: Internet
Author: User

Example: simpleurlhandlermapping

Step one: Establish the back-end controller Usercontrller.java. Code as follows:

package com.asm;     //...省略导入的相关类     public class UserController extends SimpleFormController {         protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response,                 Object command, BindException errors) throws Exception {             System.out.println("调用逻辑层,处理表单");             ModelAndView mav = new ModelAndView("loginSuc");             return mav;         }     }   

Step Two: Add the following configuration in the Spmvc-servlet.xml:

  <bean id= "simpleurlhandlermapping" class= "                Org.springframework.web.servlet.handler.SimpleUrlHandlerMapping "> <property name=" Interceptors "> <list> <ref bean= "Worktimeinterceptor"/> list> prop erty> <property name= "Mappings" > <props> <prop key= "/op/*/l Ogin.do ">userControllerprop> props> property> bean> <bean id=" us        Ercontroller "class=" Com.asm.UserController "> <property name=" commandclass "value=" Com.asm.User "/> bean> <bean id= "Worktimeinterceptor" class= "Com.asm.LoginTimeInterceptor" > <p Roperty name= "StartTime" value= "6"/> <property name= "endTime" value= "/> bean> 

Description: (1) Through the previous example we can know that simplecontroller such a backend controller must bind a Commandclass object, where we are bound by the configuration file.

(2) Usercontroller configuration instructions You can access the Usercontroller controller as long as the access begins with OP, the middle * can be any character, and the request ends in Login.do.

(3) Simpleurlhandlermapping is a more powerful mapping processor that supports Ant-style path matching in addition to the above configuration. It can also be configured in the following form:

<property name="mappings">        <value>            /op/*/login.do=userController        

(4) Interceptor: In order to provide special functions for certain special requests, Spring provides interceptor support for the mapping processor. Its configuration file is simple: One is to include the Interceptor class in spring container management, and the second is to introduce the configured interceptor Bean in the mapping processor.

Step three: Write the Interceptor Logintimeinterceptor.java, the main code is as follows:

Package com.asm; //...         Omit the imported related class public class Logintimeinterceptor extends Handlerinterceptoradapter {private int startTime;         private int endTime;         public void setstarttime (int startTime) {this.starttime = StartTime;         } public void Setendtime (int endTime) {this.endtime = EndTime;                 } public void Aftercompletion (HttpServletRequest request, httpservletresponse response, Object handler,             Exception ex) throws Exception {System.out.println ("Execute Aftercompletion method-->03");         Super.aftercompletion (Request, response, Handler, ex);                 } public void Posthandle (HttpServletRequest request, httpservletresponse response, Object handler,             Modelandview Modelandview) throws Exception {System.out.println ("execution Posthandle method-->02");         Super.posthandle (Request, response, Handler, Modelandview); } public boolean Prehandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {S             YSTEM.OUT.PRINTLN ("Implementation of Prehandle Method-->01");             Calendar cal = Calendar.getinstance ();                int hour = Cal.get (Calendar.hour_of_day);             if (StartTime <= hour && Hour < EndTime) {return true;                 } else {response.sendredirect ("http://www.javaeye.com");             return false;     }         }     }

Description: This interceptor acts: if the user does not log on at 6-18, then redirects to the Javaeye site (1) The Interceptor must Handlerinterceptoradapter Interface (2) Prehandle method is called before the backend controller executes. The Posthandle method is called after the backend controller executes, and the Aftercompletion method is called after the entire request processing is complete. (3) Prehandle method: Returns True, the map processor execution chain will continue to execute, and when false is returned, the Dispatcherservlet processor considers that the interceptor has finished processing the request without continuing to execute other interceptors and processors in the execution chain. Its API documentation is interpreted as follows: True if the execution chain should proceed with the next interceptor or the handler itself. Else, Dispatcherservlet assumes that this interceptor have already dealt with the response itself. (4) These three methods are the same parameters, the object handler parameter can be converted into a back-end controller object, such as here can be converted to Usercontroller object.

Step four: Complete other related code writing

User.java Code

package com.asm;  public class User {      private String username;      private String password;      //省略getter/setter方法  }  

Web-inf/page/loginsuc.jsp, the main code is as follows:

<body>     登录成功!欢迎来到后台管理页面   body> index.jsp代码:    <form action="<%=request.getContextPath()%>/op/luanXie/login.do" method="post">     用户名:<input type="text" name="username"><br/>     密 码:<input type="password" name="password"><br/>     <input type="submit" value="登录">   

Step five: Visit the index.jsp page to complete the test.

Analyze the execution process: in order to clearly understand the entire processor execution process, we first add the following code in the Usercontroller.java:

protected Object formBackingObject(HttpServletRequest request) throws Exception {         System.out.println("formBackingObject方法执行-->01");         return super.formBackingObject(request);     }     protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {         System.out.println("initBinder方法执行-->02");         super.initBinder(request, binder);     }     protected void onBind(HttpServletRequest request, Object command) throws Exception {         System.out.println("onBind方法执行-->03");         super.onBind(request, command);     }     protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors)             throws Exception {         System.out.println("onBindAndValidate方法执行-->04");         super.onBindAndValidate(request, command, errors);     }    

(1) When accessing .../login.do, it is first intercepted by the front controller Dispatcherservlet, and the front controller is processed by locating the Spmvc-servlet.xml profile and handing it over to the backend controller.

(2) After the execution, we get the following printing results, we know a general implementation process by printing the result.

More information welcome ball Ball 2042849237

Execute the Prehandle method-->01

Formbackingobject Method Execution-->01

Initbinder Method Execution-->02

Onbind Method Execution-->03

Onbindandvalidate Method Execution-->04

Call the logical layer, process the form

Admin----123456

Execute the Posthandle method-->02

Execute Aftercompletion Method-->03 '

SPRINGMVC Mapping Processor (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.