Struts2 login Interceptor (if not logged in, return to the login page)

Source: Internet
Author: User

1. interceptor

Interceptor is one of struts2's most powerful features. It allows you to process the action or result before or after execution. At the same time, the interceptor allows you to modularize common code and use it as a reusable class. Many features of struts2 are implemented by the interceptor. For example, the Params interceptor parses the parameters in the HTTP request and sets them to the action attribute. The servlet-config interceptor directly transmits the httpservletrequest object in the HTTP request to the action.

Struts2 has many built-in interceptors. They provide many core features and optional advanced features of struts2. These built-in interceptors are configured in the struts-default.xml. Only when the interceptor is configured can the interceptor work and run normally. In the struts-default.xml, the interceptor's configuration snippets are:

<Package name = "struts-Default" abstract = "true"> ① <interceptors> <interceptor name = "alias" class = "com. opensymphony. xwork2.interceptor. aliasinterceptor "/> ② <interceptor name =" autowiring "class =" com. opensymphony. xwork2.spring. interceptor. actionautowiringinterceptor "/> //... Other interceptor configurations <Interceptor-stack name = "defaultstack"> ③ <Interceptor-ref name = "exception"/> <Interceptor-ref name = "alias"/> <Interceptor-ref name = "servletconfig"/> <Interceptor-ref name = "i18n"/> //... Reference of other interceptors </Interceptor-stack> </interceptors> <default-interceptor-ref name = "defaultstack"/> ④ </package>

① Package sets the abstract attribute to true, which indicates that the package is an abstract package. The difference between Abstract package and non-Abstract package is that action cannot be configured in abstract package.

② The name attribute specifies the interceptor name, and the class attribute specifies the fully qualified name of the interceptor.

③ Multiple interceptors can form an interceptor stack. The name attribute is the name of the interceptor stack.

④ Specify the default Interceptor (stack) of the current package ). The default interceptor stack currently specified is defaultstack, which is a basic interceptor stack run by struts2. Generally, you do not need to configure it yourself, because in most cases, the custom package inherits from the Struts-default package.

2. Configure the login interceptor

2.1 write an intercept class first

package com.kaishengit.intercepter;import java.util.Map;import com.kaishengit.entity.Employee;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;public class LoginValidate extends AbstractInterceptor{private static final long serialVersionUID = 1L;@Overridepublic String intercept(ActionInvocation invocation) throws Exception {String namespace = invocation.getProxy().getNamespace();String actionName = invocation.getProxy().getActionName();if(("/".equals(namespace) && "toLogin".equals(actionName)) || ("/".equals(namespace) && "login".equals(actionName))){return invocation.invoke();} else {Map<String, Object> session = ActionContext.getContext().getSession();Employee e = (Employee) session.get("cur_user");if(e == null) {return "login";} else {return invocation.invoke();}}}}

2.2 struts. xml configuration

<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype struts public "-// Apache Software Foundation // DTD struts configuration 2.3 // en" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <include file = "struts-project.xml"> </include> <package name = "mydefault" extends = "struts-Default" abstract = "true"> <! -- Add interceptor --> <interceptors> <! -- Add the login interceptor --> <interceptor name = "loginvalidate" class = "com. kaishengit. intercepter. loginvalidate"/> <! -- Create a new station, put the login interceptor and the default website in --> <Interceptor-stack name = "mystack"> <Interceptor-ref name = "defaultstack"/> <Interceptor-ref name = "loginvalidate "/> </Interceptor-stack> </interceptors> <! -- Modify the default interceptor --> <default-interceptor-ref name = "mystack"/> <! -- Set result to global, in this way, no interceptor is added to each package --> <global-Results> <result name = "login" type = "redirectaction"> <Param name = "actionname"> tologin </param> <Param name = "namespace">/</param> <Param name = "code"> 1002 </param> </result> </Global-Results> </package> <package name = "mypackage" extends = "mydefault" namespace = "/"> <action name = "tologin" class = "com. kaishengit. action. appaction "> <result>/WEB-INF/views/index. JSP </result> </Action> <action name = "login" class = "com. kaishengit. action. appaction "method =" login "> <result type =" redirectaction "> <Param name =" actionname "> List </param> <Param name =" namespace ">/project </param> </result> <result name = "login" type = "redirectaction"> <Param name = "actionname"> tologin </param> <Param name = "code" >$ {code} </param> </result> </Action> </package> </struts>

2.3 configuration in struts-project.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"    "http://struts.apache.org/dtds/struts-2.3.dtd"><struts><package name="projectPackage" extends="mydefault" namespace="/project"><action name="list" class="com.kaishengit.action.ProjectAction"><result>/WEB-INF/views/project/main.jsp</result></action></package></struts>

2.4 appaction. Java

package com.kaishengit.action;import java.util.Map;import org.apache.struts2.interceptor.SessionAware;import com.kaishengit.entity.Employee;import com.kaishengit.service.EmployeeService;public class AppAction implements SessionAware{private Employee employee;private Map<String, Object> session;private String code ;EmployeeService es = new EmployeeService();public String execute(){return "success";}public String login(){Employee e = es.login(employee);if(e != null) {session.put("cur_user", e);return "success";} else {code = "1001";return "login";}}//get setpublic Employee getEmployee() {return employee;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}public void setEmployee(Employee employee) {this.employee = employee;}public void setSession(Map<String, Object> session) {this.session = session;}}

2.4 projectaction. Java

package com.kaishengit.action;import java.util.List;import java.util.Map;import org.apache.struts2.interceptor.SessionAware;import com.kaishengit.entity.Employee;import com.kaishengit.entity.Project;import com.kaishengit.service.ProjectService;public class ProjectAction implements SessionAware{private Map<String, Object> session;private List<Project> list;ProjectService ps = new ProjectService();public String execute(){Employee e = (Employee) session.get("cur_user");list = ps.findById(e.getId());return "success";}//get setpublic void setSession(Map<String, Object> session) {this.session = session;}public List<Project> getList() {return list;}public void setList(List<Project> list) {this.list = list;}}

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.