Spring filter Blocker

Source: Internet
Author: User

Implementation of the function: To determine whether the user is logged in, not logged on users are forbidden to access any page or action, automatically jump to the login page.
It is good practice that no one can directly access the JSP page, to access the action, which becomes a real permission control.
Then there are 3 ways to solve the landlord problem
1, use filter directly
2, directly using WebWork's interceptor,
3, give action to spring management, using spring's AOP mechanism

Giving the user direct access to the JSP is a violation of MVC's original intent.
1 using the filter directly
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
String user_role = (string) session.getattribute ("role");//Login role
String Url=request.getrequesturi ();
if (Usercode==null | | "". Equals (Usercode) | | User_role = = NULL | | "". Equals (User_role)) {
Determines whether the obtained path is not empty and does not 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 configuration above filters all requests to the JSP page and action. The implementation of the filter is independent of the STRUTS2, spring Framework, the user request is executed before the corresponding, in the filter, you can use Response.sendredirect ("") and other methods

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 When using the filter to avoid two consecutive jumps, otherwise it will be reported java.lang.IllegalStateException error, the specific configuration method on-line, unless necessary, not recommended to use/* (filter All Access) configuration, such configuration, pictures, JS files, Access to CSS files 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
String user_role = (string) session.getattribute ("User_role");//Login 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 session and security if you want.
*/
Request.getrequestdispatcher ("/index.jsp"). Forward (request, response);
}
return Super.prehandle (Request, response, handler);
}



}
Note In the name-servlet.xml spring configuration file:
<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.

Spring filter Blocker

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.