Struts2 - Check Login Interceptor
Struts2使用Interceptor做用户登陆检查:
1)新增一个bean: User.java
package com.my.beans; import java.util.Date; import org.apache.struts2.json.annotations.JSON; public class User { private int userId; private String username; private String password; private int age; private Date createTime; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public User(int userId, String username, String password, int age, Date createTime) { this.userId = userId; this.username = username; this.password = password; this.age = age; this.createTime = createTime; } public User() { } }
2)新增一个:CheckLoginInterceptor.java
package com.my.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.my.beans.User; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.ActionProxy; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; @SuppressWarnings("serial") public class CheckLoginInterceptor extends AbstractInterceptor { @Override public String intercept(ActionInvocation invocation) throws Exception { // invocation invoke result String result = null; // get invocation proxy ActionProxy ap = invocation.getProxy(); if (ap.getNamespace().equals("/") && ap.getActionName().equals("login") && (ap.getMethod().equals("execute") || ap.getMethod().equals("signin"))) { result = invocation.invoke(); } else { // check user already login HttpSession session = ServletActionContext.getRequest().getSession(); Object userObject = session.getAttribute("USER"); User user = (User) userObject; if (null != user) { result = invocation.invoke(); } else { HttpServletResponse response = ServletActionContext.getResponse(); HttpServletRequest request = ServletActionContext.getRequest(); // get query string String strQueryString = (String) request.getQueryString() != null ? "?" + request.getQueryString() : ""; // redirect URL response.sendRedirect(request.getContextPath() + "/login?path=" + java.net.URLEncoder.encode(request.getRequestURI() + strQueryString, "UTF-8")); } } // return action return result; } }
3) 新建一个LoginController.java
package com.my.controller; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.my.beans.User; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; @SuppressWarnings("serial") public class LoginController extends ActionSupport { private String path; private User user; public synchronized User getUser() { return user; } public synchronized void setUser(User user) { this.user = user; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } @Override public String execute() throws Exception { return SUCCESS; } public String signin() throws IOException { if (user != null) { // check user name and password if (user.getUsername().equals("admin") && user.getPassword().equals("admin")) { HttpSession session = ServletActionContext.getRequest().getSession(); session.setAttribute("USER", user); HttpServletResponse response = ServletActionContext.getResponse(); response.sendRedirect(getPath()); } } return SUCCESS; } }
4)新增一个: login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <s:form action="login!signin"> User name:<s:textfield name="user.username"></s:textfield><br/> password:<s:password name="user.password"></s:password><br/> <s:hidden name="path"></s:hidden> <s:submit value="Login"></s:submit> </s:form> </body> </html>
5)加入struts.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> <!-- 把它设置为开发模式,发布时要设置为false --> <constant name="struts.devMode" value="true" /> <!-- 设置在class被修改时是否热加载,发布时要设置为false --> <constant name="struts.convention.classes.reload" value="true"/> <!-- 自动动态方法的调用,使用这个设置后可以这样调用:action!method --> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <!-- 指定jsp文件所在的目录地址 --> <constant name="struts.convention.result.path" value="/WEB-INF/content/" /> <!-- 用于配置包名后缀。默认为action、actions、struts--> <!-- <constant name="struts.convention.package.locators" value="controller" /> --> <constant name="struts.convention.action.packages" value="com.my.controller"></constant> <!-- 用于配置类名后缀,默认为Action,设置后,Struts2只会去找这种后缀名的类做映射 --> <constant name="struts.convention.action.suffix" value="Controller"/> <!-- 设置即使没有@Action注释,依然创建Action映射。默认值是false。因为Convention-Plugin是约定优于配置的风格, 可以不通过注解根据预先的定义就能访问相应Action中的方法 --> <constant name="struts.convention.action.mapAllMatches" value="true"/> <!-- 自定义jsp文件命名的分隔符 --> <constant name="struts.convention.action.name.separator" value="-" /> <!-- 国际化资源文件名称 --> <constant name="struts.custom.i18n.resources" value="i18n" /> <!-- 是否自动加载国际化资源文件 --> <constant name="struts.i18n.reload" value="true" /> <!-- 浏览器是否缓存静态内容 --> <constant name="struts.serve.static.browserCache" value="false" /> <!-- 上传文件大小限制设置 --> <constant name="struts.multipart.maxSize" value="-1" /> <!-- 主题,将值设置为simple,即不使用UI模板。这将不会生成额外的html标签 --> <constant name="struts.ui.theme" value="simple" /> <!-- 编码格式 --> <constant name="struts.i18n.encoding" value="UTF-8" /> <!-- 设置默认package --> <constant name="struts.convention.default.parent.package" value="default"></constant> <package name="default" namespace="/" extends="json-default"> <interceptors> <interceptor name="cacheInterceptor" class="com.my.interceptor.CacheInterceptor" /> <interceptor name="loginInterceptor" class="com.my.interceptor.CheckLoginInterceptor" /> <interceptor-stack name="cacheStack"> <interceptor-ref name="defaultStack"></interceptor-ref> <interceptor-ref name="paramsPrepareParamsStack"></interceptor-ref> <interceptor-ref name="cacheInterceptor"></interceptor-ref> <interceptor-ref name="loginInterceptor"></interceptor-ref> </interceptor-stack> </interceptors> <default-interceptor-ref name="cacheStack"></default-interceptor-ref> <default-action-ref name="index" /> <global-results> <!-- <result name="error">/error.jsp</result> --> <result name="json" type="json"> <!-- 是否包括父类的属性输出,默认true. --> <!-- <param name="ignoreHierarchy">false</param> --> <!-- 是否输出null值的属性,默认false --> <!-- <param name="excludeNullProperties">true</param> --> </result> </global-results> <global-exception-mappings> <exception-mapping exception="java.lang.Exception" result="error"/> </global-exception-mappings> </package> </struts>
关键点在于:
<interceptor-ref name="loginInterceptor"></interceptor-ref>
使用此方法可以对所有的action进行监控。
如果使用web.xml的filter做监控的话,那将会对所有的资源都会监控,比如jsp、css、js等。使用Interceptor只对action做监控即可。