Web development often encountered when browsing Web pages, users need to login to access some important pages, when you visit some "illegal" page, that is, if you have not logged into the system, you need to log in, as long as you successfully login to access the content of the message, to achieve the function required
Inheriting interceptors Handlerinterceptoradapter, there are three important methods in this class, Gray elder brother method can not focus first, the main code implementation is the green part, the code is as follows:
/**
* @author Tony
* @date 2014-12-17
*/
/**
* login blocker, only after login to access
*/
Public class Logininterceptor extends handlerinterceptoradapter{
@Override
Public void Aftercompletion (HttpServletRequest request,
httpservletresponse Response, Object handler, Exception ex)
throws Exception {
super.aftercompletion (Request, response, Handler, ex);
}
@Override
Public void Posthandle (HttpServletRequest request,
httpservletresponse Response, Object handler,
Modelandview Modelandview) throws Exception {
Super.posthandle (Request, response, Handler, Modelandview);
}
// The URL of the promise passed
private static final string[] Ignore_uri = {"/login.from", "/tologin.from"};
@Override
Public Boolean Prehandle (HttpServletRequest request,
httpservletresponse response, Object handler) throws Exception {
request.setcharacterencoding ("Utf-8");
response.setcharacterencoding ("UTF-8");
Response.setcontenttype ("Text/html;charset=utf-8");
String url = Request.getrequesturi (). toString ();
System.out.println (URL);
Boolean flag = false;
For (String S:ignore_uri) {
if (Url.contains (s)) {// if the request is a landing page, leave
flag = true;
Break ;
}}
if (!flag) {
User user = (user) request.getsession (). getattribute ("user");
System.out.println (user);
if (user = = null) {// check login, otherwise jump back to landing page
PrintWriter out = Response.getwriter ();
StringBuilder builder = new StringBuilder ();
builder.append ("<script type=\" text/javascript\ "charset=\" utf-8\ ">");
builder.append ("alert (\" you are not logged in, please log in first . \ ");");
builder.append ("window.top.location.href=\");
builder.append ("/studentsystem/login/tologin.from\";</script> ");
Out.print (builder.tostring ());
Out.close ();
return false;
}}
return true;
}}
Of course, after the login check is implemented, the custom interceptor needs to be registered in the master configuration file.
Spring_mvc.xml Register the Interceptor Code as follows:
<!--Configure the landing blocker --
<mvc:interceptors>
<mvc:interceptor>
<!--path= "/**"//** means all folders and subfolders --
<mvc:mapping path= "/**"/>
<bean id= "Logininterceptor" class= "Edu.nwsuaf.xc.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
This is achieved under the SPRINGMVC.
Login Check springmvc interceptor blocker for login access