Spring Filter filter, spring to intercept the not logged-on user permission limit

Source: Internet
Author: User
Tags aop
Implementation of the function: To determine whether the user is logged in, the user does not log in to prevent access to any page or action, automatically jump to the login page.
The good thing is that no one can access the JSP page directly, to access the action, which becomes a real authority control.
Then there are 3 ways to solve the landlord's problem
1, direct use of filter
2, directly using WebWork's interceptor,
3, give the action to spring management, using spring's AOP mechanism

Allowing users to access the JSP directly would have violated MVC's intent.
1 Direct use of filter
Web.xml Configuration

<filter>
<filter-name>SecurityServlet</filter-name>
<filter-class>com.*.web.servlet.SecurityServlet</filter-class>
</filter>
<filter-mapping>
<filter-name>SecurityServlet</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>SecurityServlet</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>


Securityservlet class

Package com.*.web.servlet;

Import java.io.IOException;
Import Javax.servlet.Filter;
Import Javax.servlet.FilterChain;
Import Javax.servlet.FilterConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;
Import Javax.servlet.ServletResponse;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import javax.servlet.http.HttpSession;
public class Securityservlet extends HttpServlet implements Filter {
Private static final long serialversionuid = 1L;

public void Dofilter (ServletRequest arg0, Servletresponse arg1, Filterchain arg2) throws IOException, Servletexception {
HttpServletRequest request= (httpservletrequest) arg0;
HttpServletResponse response = (httpservletresponse) arg1;
HttpSession session = Request.getsession (true);
String usercode = (string) request.getremoteuser ();//Login person
String user_role = (string) session.getattribute ("role");//Login character
String Url=request.getrequesturi ();
if (Usercode==null | | "". Equals (Usercode) | | User_role = = NULL | | "". Equals (User_role)) {
To determine that the obtained path is not empty and is not a jump when accessing the login page or performing a logon operation
if (Url!=null &&!url.equals ("") && (Url.indexof ("login") <0 && url.indexof ("login") <0)) {
Response.sendredirect (Request.getcontextpath () + "/login.jsp");
return;
}
}
Arg2.dofilter (arg0, arg1);
Return
}
public void init (Filterconfig arg0) throws Servletexception {
}

}
The filter-mapping in the configuration defines the type of request that needs to be filtered, and the above configuration filters all requests for JSP pages and action. The implementation of the filter is independent of the STRUTS2, spring Framework, and is executed before the user request is corresponding, and in the filter, the Response.sendredirect ("") can be used

Jump to the required links, such as login page, error page, etc., do not need to jump, Arg2.dofilter (arg0, arg1), you can continue to execute the user's request. Note the use of filter to avoid two consecutive jumps, or you will report java.lang.IllegalStateException errors, specific configuration methods on the Internet, unless necessary, do not recommend the use of/* (filtering All Access) configuration, such configuration, pictures, JS files, CSS file access will be filtered


2 Spring Intercept

Spring Configuration

<bean id= "Springsessioninterceptor" class= "Com.*.web.servlet.springlogininterceptor" >
</bean>
<bean id= "AutoPorxyFactoryBean1"
class= "Org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator" >
<property name= "Interceptornames" >
<list>
<value>springLoginInterceptor</value>
</list>
</property>
<property name= "Beannames" >
<list>
<value>*Controller</value>
</list>
</property>
</bean>
Springlogininterceptor Implementation Class

Package com.web.servlet;

Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import javax.servlet.http.HttpSession;

Import Org.aopalliance.intercept.MethodInterceptor;
Import org.aopalliance.intercept.MethodInvocation;
Import Org.apache.log4j.Logger;
Import org.apache.struts.action.ActionMapping;

public class Springlogininterceptor implements Methodinterceptor {
Private static final Logger log = Logger
. GetLogger (Springlogininterceptor. Class);

@Override
Public Object Invoke (Methodinvocation invocation) throws Throwable {
Log.info ("intercept begins.") ");
object[] args = invocation.getarguments ();
HttpServletRequest request = null;
HttpServletResponse response = null;
Actionmapping mapping = null;
for (int i = 0; i < args.length; i++) {
if (Args[i] instanceof httpservletrequest) request = (httpservletrequest) args[i];
if (Args[i] instanceof httpservletresponse) response = (httpservletresponse) args[i];
if (Args[i] instanceof actionmapping) mapping = (actionmapping) args[i];
}
if (Request!= null && mapping!= null) {
String Url=request.getrequesturi ();
HttpSession session = Request.getsession (true);
String usercode = (string) request.getremoteuser ();//Login person
String user_role = (string) session.getattribute ("User_role");//Logon person role

if (Usercode = null | | usercode.equals ("")) {
if (Url.indexof ("login") <0 && url.indexof ("login") <0) {

Return Mapping.findforward ("Logininterceptor");
}
return Invocation.proceed ();
}
else {
return Invocation.proceed ();
}
}
else {
return Invocation.proceed ();
}
}
}
//================================================================
In SPRING 3 MVC mode, you can also implement the following:
public class Securityfilter extends Handlerinterceptoradapter {

@Override
public boolean prehandle (HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println ("==>>begin to Filter session====");
HttpSession session = Request.getsession ();
String user = (string) session.getattribute ("User");
System.out.println ("= = =?? Current user== "+user);
String Curpath=request.getrequesturl (). toString ();
System.out.println ("===>> curpath:" +curpath);
if (Curpath.indexof ("Gps/user/index") >=0) {
return true;
}
if (Null==user | | "". Equals (user)) {
return true;
/**
* Handle sessions and security if you want.
*/
Request.getrequestdispatcher ("/index.jsp"). Forward (request, response);
}
return Super.prehandle (Request, response, handler);
}



}
In the configuration file in Name-servlet.xml Spring, note:
<bean id= "urlmapping" class= "org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" >
<property name= "Interceptors" >
<list>
<bean class= "Com.ibm.tds.filter.SecurityFilter"/>
</list>
</property>
</bean>

You can use it.

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.