Struts2多方法实现登录过滤拦截

来源:互联网 发布:农村淘宝站点查询 编辑:程序博客网 时间:2024/06/05 19:52

目录:

        1.需求概述
        2.解决方案
            2.1 filter过滤器实现登录过滤 
            2.2  action拦截器实现登录过滤 
            2.3  方法拦截器实现登录过滤 

1.需求概述

        有时候我们在做管理系统的时候,出于安全考虑我们有些页面是不能够直接供用户访问的,这个时候就需要我们添加一些过滤操作,让已经登录的用户可访问,未登录的用户不能访问。

2.解决方案

   2.1 filter过滤器实现登录过滤
        案例中我们会建立LoginAction.java和TestAction.java两个action,main.jsp和login.jsp两个页面;我们要做到的效果就是当用户不登陆直接访问TestAction和main.jsp让他跳转到登录界面,当登录成功以后我无论是访问main.jsp还是TestAction都可以直接进入main.jsp页面。
    (1)login.jsp
  1. <%@ page language="java" contentType="text/html; charset=utf8"
  2. pageEncoding="utf8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf8">
  7. <title>Insert title here</title>
  8. </head>
  9. <body>
  10. <form action="login.action" method="post">
  11. 用户名:<input type="text" id="username" name="username"><br> 密码:<input
  12. type="password" id="password" name="password"><br> <input type="submit"
  13. value="提交">
  14. </form>
  15. </body>
  16. </html>
    (2)LoginAction.java
  1. package com.elimy.admin;
  2. import javax.servlet.http.Cookie;
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5. import javax.servlet.http.HttpSession;
  6. import org.apache.struts2.ServletActionContext;
  7. import com.elimy.entity.User;
  8. import com.opensymphony.xwork2.ActionSupport;
  9. import com.opensymphony.xwork2.ModelDriven;
  10. public class LoginAction extends ActionSupport implements ModelDriven<User> {
  11. private User user= new User();
  12. /*
  13. * 管理员登录功能
  14. */
  15. public String login() {
  16. //通过ServletActionContext获取到requst和 response请求对象
  17. HttpServletRequest request = ServletActionContext.getRequest();
  18. HttpServletResponse response= ServletActionContext.getResponse();
  19. //获取到浏览器上午cookies
  20. Cookie cookies[] = request.getCookies();
  21. //遍历cookie是否有登录信息
  22. if (cookies!=null){
  23. for(int i=0;i<cookies.length;i++){
  24. Cookie cookie = cookies[i];
  25. if ("elimy".equals(cookie.getValue())){
  26. System.out.println("你已经登录过了");
  27. //直接返回跳转到管理页面
  28. return SUCCESS;
  29. }
  30. }
  31. }
  32. //判断用户名和密码是否成功,这里就不从数据库获取了
  33. if ("elimy".equals(user.getUsername())&& "8888".equals(user.getPassword())) {
  34. System.out.println("登录成功");
  35. //将登录状态写入session
  36. request.getSession().setAttribute("username", user.getUsername());
  37. //用户名存入cookie
  38. Cookie cookie1 = new Cookie("username", user.getUsername());
  39. //设置Cookie生命周期为一天
  40. cookie1.setMaxAge(60 * 60 * 24 * 1);
  41. //保存cookie
  42. response.addCookie(cookie1);
  43. System.out.println("Session="+request.getAttribute("username"));
  44. return SUCCESS;
  45. }else {
  46. //检测是否内容为空
  47. if (user.getUsername()==null&&user.getPassword()==null) {
  48. System.out.println("输入内容为空,请输入内容先");
  49. }else {
  50. System.out.println(user.getUsername());
  51. System.out.println(user.getPassword());
  52. System.out.println("登录失败");
  53. }
  54. return ERROR ;
  55. }
  56. }
  57. @Override
  58. public User getModel() {
  59. return user;
  60. }
  61. }
    (3)mian.jsp
  1. <%@ page language="java" contentType="text/html; charset=utf8"
  2. pageEncoding="utf8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf8">
  7. <title>管理页面</title>
  8. </head>
  9. <body background="<%=request.getContextPath()%>/images/back.jpg"
  10. style=" background-repeat:no-repeat;
  11. background-size:100% 100%;
  12. background-attachment: fixed;"
  13. >
  14. welcome to struts2~~main.jsp!
  15. <table>
  16. <ul>
  17. <li>用户权限管理</li>
  18. <li>注册管理</li>
  19. <li>管理</li>
  20. <li>昵称管理</li>
  21. <li>管理</li>
  22. </ul>
  23. </table>
  24. </body>
  25. </html>
    (4)TestAction.java
  1. package com.elimy.test;
  2. import javax.servlet.http.Cookie;
  3. import javax.servlet.http.HttpServletRequest;
  4. import org.apache.struts2.ServletActionContext;
  5. import com.opensymphony.xwork2.ActionSupport;
  6. public class TestAction extends ActionSupport {
  7. private static final long serialVersionUID = 1L;
  8. @Override
  9. public String execute() throws Exception {
  10. HttpServletRequest request = ServletActionContext.getRequest();
  11. Cookie[] cookies=request.getCookies();
  12. System.out.println("TestAction 已经执行到了");
  13. if (cookies!=null) {
  14. for (Cookie cookie:cookies) {
  15. System.out.println(cookie.getValue());
  16. }
  17. }
  18. System.out.println(request.getCookies());
  19. return SUCCESS;
  20. }
  21. }
    (5)web.xml
  1. <?xml version="1.0" encoding="GBK"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://java.sun.com/xml/ns/javaee" 
  4. xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  6. <!--配置登录过滤器 -->
  7. <filter>
  8. <filter-name>loginFilter</filter-name>
  9. <filter-class>com.elimy.filter.LoginFilter</filter-class>
  10. </filter>
  11. <filter-mapping>
  12. <filter-name>loginFilter</filter-name>
  13. <url-pattern>/*</url-pattern>
  14. </filter-mapping>
  15. <!--配置struts2核心过滤器 -->
  16. <filter>
  17. <filter-name>struts2</filter-name>
  18. <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  19. </filter>
  20. <filter-mapping>
  21. <filter-name>struts2</filter-name>
  22. <url-pattern>/*</url-pattern>
  23. </filter-mapping>
  24. <!--设置欢迎界面 -->
  25. <welcome-file-list>
  26. <welcome-file>login.jsp</welcome-file>
  27. </welcome-file-list>
  28. </web-app>
    (6)登录过滤器类LoginFilter.java
  1. package com.elimy.filter;
  2. import java.io.IOException;
  3. import javax.servlet.Filter;
  4. import javax.servlet.FilterChain;
  5. import javax.servlet.FilterConfig;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.ServletRequest;
  8. import javax.servlet.ServletResponse;
  9. import javax.servlet.http.Cookie;
  10. import javax.servlet.http.HttpServlet;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import javax.servlet.http.HttpSession;
  14. public class LoginFilter extends HttpServlet implements Filter{
  15. private static final long serialVersionUID = 1L;
  16. public LoginFilter() {
  17. }
  18. @Override
  19. public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
  20. throws IOException, ServletException {
  21. Boolean redirect_flag=true;
  22. HttpServletRequest request=(HttpServletRequest) arg0;
  23. HttpServletResponse response=(HttpServletResponse) arg1;
  24. //获取到session对象,登录状态信息存放在里面
  25. HttpSession session=request.getSession();
  26. //获取上下文路径
  27. String contextPath=request.getContextPath();
  28. //获取请求路径
  29. String url=request.getServletPath();
  30. System.out.println("ServletPath="+url);
  31. //设置检测一切非/login.jsp,/login.action,/images/的请求
  32. if (! url.startsWith("/login.jsp")&&!url.startsWith("/login.action")&&!url.startsWith("/images/")) {
  33. //获取session保存的登录状态
  34. System.out.println("session="+session.getAttribute("username"));
  35. Cookie cookies[] = request.getCookies();
  36. if (cookies!=null){
  37. //循环遍历cookie
  38. for(int i=0;i<cookies.length;i++){
  39. Cookie cookie = cookies[i];
  40. //判断是否已经登录过了
  41. if ("username".equals(cookie.getName())){
  42. System.out.println("你已经登录过了");
  43. redirect_flag=false;
  44. }
  45. }
  46. }
  47. //判断如果未登录则重定向到登录页面
  48. if (redirect_flag) {
  49. System.out.println("重定向到:"+contextPath+"/login.jsp");
  50. response.sendRedirect(contextPath+"/login.jsp");
  51. return;
  52. }else {
  53. System.out.println("已经登录了不拦截");
  54. }
  55. }else {
  56. System.out.println("我不拦截");
  57. }
  58. arg2.doFilter(arg0, arg1);
  59. }
  60. @Override
  61. public void init(FilterConfig arg0) throws ServletException {
  62. }
  63. }
    (7)Struts.xml
  1. <?xml version="1.0" encoding="GBK" ?>
  2. <!DOCTYPE struts PUBLIC
  3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  4. "http://struts.apache.org/dtds/struts-2.0.dtd">
  5. <struts>
  6. <!-- 配置开启开发模式 -->
  7. <constant name="struts.devMode" value="true"></constant>
  8. <!--配置后缀 -->
  9. <constant name="struts.action.extension" value="action" />
  10. <package name="default" namespace="/" extends="struts-default">
  11. <!-- 配置TestAction -->
  12. <action name="test" class="com.elimy.test.TestAction">
  13. <result name="error">/WEB-INF/index.jsp</result>
  14. <result name="success">/WEB-INF/main.jsp</result>
  15. </action>
  16. <!-- 配置LoginAction -->
  17. <action name="login" method="login" class="com.elimy.admin.LoginAction">
  18. <result name="error">login.jsp</result>
  19. <result name="success">/WEB-INF/main.jsp</result>
  20. </action>
  21. </package>
  22. </struts>
    (8)实体类User.java(实现jsp表单数据与Action映射)
  1. package com.elimy.entity;
  2. public class User {
  3. private String username;
  4. private String password;
  5. public String getUsername() {
  6. return username;
  7. }
  8. public void setUsername(String username) {
  9. this.username = username;
  10. }
  11. public String getPassword() {
  12. return password;
  13. }
  14. public void setPassword(String password) {
  15. this.password = password;
  16. }
  17. public User() {
  18. }
  19. }
     (9)测试
  1. ServletPath=/test.action
  2. session=null
  3. 重定向到:/Wechat/login.jsp
  4. ServletPath=/login.jsp
  5. 我不拦截
  6. ServletPath=/login.action
  7. 我不拦截
  8. 登录成功
  9. Session=elimy
  10. ServletPath=/images/back.jpg
  11. 我不拦截
  12. ServletPath=/test.action
  13. session=elimy
  14. 你已经登录过了
  15. 已经登录了不拦截
  16. TestAction 已经执行到了
  17. 4C4A4E2C49A2F51F677A1D7A2CF9C30F
  18. elimy
  19. [Ljavax.servlet.http.Cookie;@73d3d058
    上面是测试的控制台输出结果,测试步骤如下:
                1.首先直接访问 http://localhost:8080/Wechat/test.action  进入过滤器后判断没有session表示没有登录,所有不能直接访问,所以重定向到login.jsp
                2.输入用户名密码,控制台显示Session存在并且显示登录成功跳转到main.jsp页面
                3.最后我再次在浏览器输入 http://localhost:8080/Wechat/test.action 继续访问,这个时候会直接跳转到main.jsp,表示拦截成功
                ps:因为我设置的cookie保存时常为一天,所以伙伴们可以试试关掉浏览器然后重启访问test.action看会不会直接进入无需登录,同时可以清除一下浏览器cookie再访问看又有啥区别。

   2.2  action拦截器实现登录过滤   
         这里我们是通过struts2的拦截器拦截action去实现登录过滤的,实现的效果和前面一致,下面会贴出代码,与上面一致的就不贴出了。
   (1)实现拦截器类LoginActionIntercepter.java  
  1. package com.elimy.interceptor;
  2. import javax.servlet.http.Cookie;
  3. import javax.servlet.http.HttpServletRequest;
  4. import org.apache.struts2.StrutsStatics;
  5. import com.opensymphony.xwork2.ActionContext;
  6. import com.opensymphony.xwork2.ActionInvocation;
  7. import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
  8. public class LoginActionIntercepter extends AbstractInterceptor {
  9. private static final long serialVersionUID = 1L;
  10. public LoginActionIntercepter() {
  11. }
  12. @Override
  13. public void destroy() {
  14. System.out.println("LoginActionIntercepter->destroy()");
  15. }
  16. @Override
  17. public void init() {
  18. System.out.println("LoginActionIntercepter->init()");
  19. }
  20. /*
  21. * 实现拦截操作
  22. */
  23. @Override
  24. public String intercept(ActionInvocation arg0) throws Exception {
  25. boolean interceptor_flag=true;
  26. //获取到请求的action名
  27. String actionName=arg0.getProxy().getActionName();
  28. System.out.println("actionName="+actionName);
  29. //拦截除了login.action以外的所有action
  30. if ("login".equals(actionName)) {
  31. //通知调用后面的interceptor或者action
  32. return arg0.invoke();
  33. }
  34. //获取到actionContext
  35. ActionContext actionContext=arg0.getInvocationContext();
  36. //获取到HttpServletRequest
  37. HttpServletRequest request=(HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
  38. //获取到浏览器cookies
  39. Cookie[] cookies = request.getCookies();
  40. if (cookies!=null){
  41. for (Cookie cookie:cookies) {
  42. if ("elimy".equals(cookie.getValue())){
  43. interceptor_flag=false;
  44. }
  45. }
  46. //存在指定用户名的cookie则不拦截
  47. if (interceptor_flag) {
  48. System.out.println("亲爱的请先登录好吗?");
  49. return "login";
  50. }else {
  51. System.out.println("你已经登录过了,我不拦你");
  52. }
  53. }else {
  54. System.out.println("似乎没有cookie哟?");
  55. return "login";
  56. }
  57. //获取判断session中是否存在username的值
  58. /* String username=(String) arg0.getInvocationContext().getSession().get("username");
  59. if (username==null) {
  60. System.out.println("亲爱的请先登录好吗?");
  61. return "login";
  62. }*/
  63. return arg0.invoke();
  64. }
  65. }
      ps:该类会根据浏览器cookie中是否存在对于的用户名来判断是否拦截除login之外的action访问    
        (2)struts.xml配置
  1. <?xml version="1.0" encoding="GBK" ?>
  2. <!DOCTYPE struts PUBLIC
  3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  4. "http://struts.apache.org/dtds/struts-2.0.dtd">
  5. <struts>
  6. <!-- 配置开启开发模式 -->
  7. <constant name="struts.devMode" value="true"></constant>
  8. <!--配置后缀 -->
  9. <constant name="struts.action.extension" value="action" />
  10. <package name="default" namespace="/" extends="struts-default">
  11. <interceptors>
  12. <!-- 自定义的拦截器 -->
  13. <interceptor name="interceptorLogin" class="com.elimy.interceptor.LoginActionIntercepter"></interceptor>
  14. <!-- 将自定义的拦截器打包到一个拦截器栈 -->
  15. <interceptor-stack name="customStack">
  16. <interceptor-ref name="defaultStack"></interceptor-ref>
  17. <interceptor-ref name="interceptorLogin"></interceptor-ref>
  18. </interceptor-stack>
  19. </interceptors>
  20. <!-- 将自定义的拦截器栈应用到全局 -->
  21. <default-interceptor-ref name="customStack"></default-interceptor-ref>
  22. <!-- 设置全局的action跳转页面 -->
  23. <global-results>
  24. <result name="login">login.jsp</result>
  25. </global-results>
  26. <!-- 配置TestAction -->
  27. <action name="test" class="com.elimy.test.TestAction">
  28. <result name="error">/WEB-INF/index.jsp</result>
  29. <result name="success">/WEB-INF/main.jsp</result>
  30. </action>
  31. <!-- 配置LoginAction -->
  32. <action name="login" method="login" class="com.elimy.admin.LoginAction">
  33. <result name="error">login.jsp</result>
  34. <result name="success">/WEB-INF/main.jsp</result>
  35. </action>
  36. </package>
  37. </struts>
        (3)web.xml
  1. <?xml version="1.0" encoding="GBK"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  3. <!--配置struts2核心过滤器 -->
  4. <filter>
  5. <filter-name>struts2</filter-name>
  6. <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  7. </filter>
  8. <filter-mapping>
  9. <filter-name>struts2</filter-name>
  10. <url-pattern>/*</url-pattern>
  11. </filter-mapping>
  12. <!--设置欢迎界面 -->
  13. <welcome-file-list>
  14. <welcome-file>login.jsp</welcome-file>
  15. </welcome-file-list>
  16. </web-app>
        (4)测试
  1. actionName=test
  2. 亲爱的请先登录好吗?
  3. actionName=login
  4. 登录成功
  5. Session=elimy
  6. actionName=test
  7. 你已经登录过了,我不拦你
  8. TestAction 已经执行到了
  9. 4146440FB496BE79C6D3EEA0E3C89E17
  10. elimy
  11. actionName=test
  12. 似乎没有cookie哟?
  上面依然是控制台输出结果,执行动作顺序依次如下:
   1.直接访问 http://localhost:8080/Wechat/test.action 输出未登录提示,直接跳转到登录页面
   2.输入用户名密码登录 显示登录成功
   3.我再次访问 http://localhost:8080/Wechat/test.action  显示已经登录过了,我不拦你 表示cookie记住登录状态保存成功
   4.然后我清除浏览器cookies 访问http://localhost:8080/Wechat/test.action 显示没有cookies,并跳转到登录界面

   2.3  方法拦截器实现登录过滤 

          下面通过拦截方法来实现与上面相同的登录过滤功能,展示页面,LoginAction.java,TestAction.java等基本与上面一致,下面贴出核心的拦截器类和配置文件代码。
    (1)LoginMethodIntercepter.java
  1. package com.elimy.interceptor;
  2. import javax.servlet.http.Cookie;
  3. import javax.servlet.http.HttpServletRequest;
  4. import org.apache.struts2.StrutsStatics;
  5. import com.opensymphony.xwork2.ActionContext;
  6. import com.opensymphony.xwork2.ActionInvocation;
  7. import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
  8. public class LoginMethodInterceptor extends MethodFilterInterceptor {
  9. private static final long serialVersionUID = 1L;
  10. public LoginMethodInterceptor() {
  11. }
  12. @Override
  13. protected String doIntercept(ActionInvocation arg0) throws Exception {
  14. System.out.println("doIntercept()");
  15. //获取到ActionContext
  16. ActionContext actionContext = arg0.getInvocationContext();
  17. //获取到HttpServletRequest
  18. HttpServletRequest request =(HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
  19. //获取cookies
  20. Cookie[] cookies=request.getCookies();
  21. if (cookies!=null) {
  22. for(Cookie cookie:cookies ){
  23. if ("elimy".equals(cookie.getValue())) {
  24. return arg0.invoke();
  25. }
  26. }
  27. }else {
  28. System.out.println("没有cookies哟");
  29. return "login";
  30. }
  31. System.out.println("似乎没有登录哦");
  32. return "login";
  33. }
  34. }
    (2)struts.xml配置文件
  1. <?xml version="1.0" encoding="GBK" ?>
  2. <!DOCTYPE struts PUBLIC
  3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  4. "http://struts.apache.org/dtds/struts-2.0.dtd">
  5. <struts>
  6. <!-- 配置开启开发模式 -->
  7. <constant name="struts.devMode" value="true"></constant>
  8. <!--配置后缀 -->
  9. <constant name="struts.action.extension" value="action" />
  10. <package name="default" namespace="/" extends="struts-default">
  11. <interceptors>
  12. <!-- 方法拦截器 -->
  13. <interceptor name="methodInterception" class="com.elimy.interceptor.LoginMethodInterceptor"></interceptor>
  14. <!-- 包含方法拦截器的栈 -->
  15. <interceptor-stack name="customMethodStack">
  16. <interceptor-ref name="defaultStack"></interceptor-ref>
  17. <!-- 引入拦截器方法,并设置拦截方法 -->
  18. <interceptor-ref name="methodInterception">
  19. <!-- 设置需要拦截的方法 -->
  20. <param name="includeMethods"></param>
  21. <!-- 设置不需拦截的方法 -->
  22. <param name="excludeMethods">login</param>
  23. </interceptor-ref>
  24. </interceptor-stack>
  25. </interceptors>
  26. <!-- 将自定义的拦截器栈应用到全局 -->
  27. <default-interceptor-ref name="customMethodStack"></default-interceptor-ref>
  28. <!-- 设置全局的action跳转页面 -->
  29. <global-results>
  30. <result name="login">login.jsp</result>
  31. </global-results>
  32. <!-- 配置TestAction -->
  33. <action name="test" class="com.elimy.test.TestAction">
  34. <result name="error">/WEB-INF/index.jsp</result>
  35. <result name="success">/WEB-INF/main.jsp</result>
  36. </action>
  37. <!-- 配置LoginAction -->
  38. <action name="login" method="login" class="com.elimy.admin.LoginAction">
  39. <result name="error">login.jsp</result>
  40. <result name="success">/WEB-INF/main.jsp</result>
  41. </action>
  42. </package>
  43. </struts>
  (3) 测试结果
  1. doIntercept()
  2. 没有cookies哟
  3. 登录成功
  4. Session=elimy
  5. doIntercept()
  6. TestAction 已经执行到了
  7. 699E407E82BDBAD6D8E0D4FFCBDDB0FD
  8. elimy
  9. doIntercept()
  10. 没有cookies哟
 上面依然是控制台输出结果,执行动作顺序与前面一致

目录:

        1.需求概述
        2.解决方案
            2.1 filter过滤器实现登录过滤 
            2.2  action拦截器实现登录过滤 
            2.3  方法拦截器实现登录过滤 

1.需求概述

        有时候我们在做管理系统的时候,出于安全考虑我们有些页面是不能够直接供用户访问的,这个时候就需要我们添加一些过滤操作,让已经登录的用户可访问,未登录的用户不能访问。

2.解决方案

   2.1 filter过滤器实现登录过滤
        案例中我们会建立LoginAction.java和TestAction.java两个action,main.jsp和login.jsp两个页面;我们要做到的效果就是当用户不登陆直接访问TestAction和main.jsp让他跳转到登录界面,当登录成功以后我无论是访问main.jsp还是TestAction都可以直接进入main.jsp页面。
    (1)login.jsp
  1. <%@ page language="java" contentType="text/html; charset=utf8"
  2. pageEncoding="utf8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf8">
  7. <title>Insert title here</title>
  8. </head>
  9. <body>
  10. <form action="login.action" method="post">
  11. 用户名:<input type="text" id="username" name="username"><br> 密码:<input
  12. type="password" id="password" name="password"><br> <input type="submit"
  13. value="提交">
  14. </form>
  15. </body>
  16. </html>
    (2)LoginAction.java
  1. package com.elimy.admin;
  2. import javax.servlet.http.Cookie;
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5. import javax.servlet.http.HttpSession;
  6. import org.apache.struts2.ServletActionContext;
  7. import com.elimy.entity.User;
  8. import com.opensymphony.xwork2.ActionSupport;
  9. import com.opensymphony.xwork2.ModelDriven;
  10. public class LoginAction extends ActionSupport implements ModelDriven<User> {
  11. private User user= new User();
  12. /*
  13. * 管理员登录功能
  14. */
  15. public String login() {
  16. //通过ServletActionContext获取到requst和 response请求对象
  17. HttpServletRequest request = ServletActionContext.getRequest();
  18. HttpServletResponse response= ServletActionContext.getResponse();
  19. //获取到浏览器上午cookies
  20. Cookie cookies[] = request.getCookies();
  21. //遍历cookie是否有登录信息
  22. if (cookies!=null){
  23. for(int i=0;i<cookies.length;i++){
  24. Cookie cookie = cookies[i];
  25. if ("elimy".equals(cookie.getValue())){
  26. System.out.println("你已经登录过了");
  27. //直接返回跳转到管理页面
  28. return SUCCESS;
  29. }
  30. }
  31. }
  32. //判断用户名和密码是否成功,这里就不从数据库获取了
  33. if ("elimy".equals(user.getUsername())&& "8888".equals(user.getPassword())) {
  34. System.out.println("登录成功");
  35. //将登录状态写入session
  36. request.getSession().setAttribute("username", user.getUsername());
  37. //用户名存入cookie
  38. Cookie cookie1 = new Cookie("username", user.getUsername());
  39. //设置Cookie生命周期为一天
  40. cookie1.setMaxAge(60 * 60 * 24 * 1);
  41. //保存cookie
  42. response.addCookie(cookie1);
  43. System.out.println("Session="+request.getAttribute("username"));
  44. return SUCCESS;
  45. }else {
  46. //检测是否内容为空
  47. if (user.getUsername()==null&&user.getPassword()==null) {
  48. System.out.println("输入内容为空,请输入内容先");
  49. }else {
  50. System.out.println(user.getUsername());
  51. System.out.println(user.getPassword());
  52. System.out.println("登录失败");
  53. }
  54. return ERROR ;
  55. }
  56. }
  57. @Override
  58. public User getModel() {
  59. return user;
  60. }
  61. }
    (3)mian.jsp
  1. <%@ page language="java" contentType="text/html; charset=utf8"
  2. pageEncoding="utf8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf8">
  7. <title>管理页面</title>
  8. </head>
  9. <body background="<%=request.getContextPath()%>/images/back.jpg"
  10. style=" background-repeat:no-repeat;
  11. background-size:100% 100%;
  12. background-attachment: fixed;"
  13. >
  14. welcome to struts2~~main.jsp!
  15. <table>
  16. <ul>
  17. <li>用户权限管理</li>
  18. <li>注册管理</li>
  19. <li>管理</li>
  20. <li>昵称管理</li>
  21. <li>管理</li>
  22. </ul>
  23. </table>
  24. </body>
  25. </html>
    (4)TestAction.java
  1. package com.elimy.test;
  2. import javax.servlet.http.Cookie;
  3. import javax.servlet.http.HttpServletRequest;
  4. import org.apache.struts2.ServletActionContext;
  5. import com.opensymphony.xwork2.ActionSupport;
  6. public class TestAction extends ActionSupport {
  7. private static final long serialVersionUID = 1L;
  8. @Override
  9. public String execute() throws Exception {
  10. HttpServletRequest request = ServletActionContext.getRequest();
  11. Cookie[] cookies=request.getCookies();
  12. System.out.println("TestAction 已经执行到了");
  13. if (cookies!=null) {
  14. for (Cookie cookie:cookies) {
  15. System.out.println(cookie.getValue());
  16. }
  17. }
  18. System.out.println(request.getCookies());
  19. return SUCCESS;
  20. }
  21. }
    (5)web.xml
  1. <?xml version="1.0" encoding="GBK"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://java.sun.com/xml/ns/javaee" 
  4. xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  6. <!--配置登录过滤器 -->
  7. <filter>
  8. <filter-name>loginFilter</filter-name>
  9. <filter-class>com.elimy.filter.LoginFilter</filter-class>
  10. </filter>
  11. <filter-mapping>
  12. <filter-name>loginFilter</filter-name>
  13. <url-pattern>/*</url-pattern>
  14. </filter-mapping>
  15. <!--配置struts2核心过滤器 -->
  16. <filter>
  17. <filter-name>struts2</filter-name>
  18. <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  19. </filter>
  20. <filter-mapping>
  21. <filter-name>struts2</filter-name>
  22. <url-pattern>/*</url-pattern>
  23. </filter-mapping>
  24. <!--设置欢迎界面 -->
  25. <welcome-file-list>
  26. <welcome-file>login.jsp</welcome-file>
  27. </welcome-file-list>
  28. </web-app>
    (6)登录过滤器类LoginFilter.java
  1. package com.elimy.filter;
  2. import java.io.IOException;
  3. import javax.servlet.Filter;
  4. import javax.servlet.FilterChain;
  5. import javax.servlet.FilterConfig;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.ServletRequest;
  8. import javax.servlet.ServletResponse;
  9. import javax.servlet.http.Cookie;
  10. import javax.servlet.http.HttpServlet;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import javax.servlet.http.HttpSession;
  14. public class LoginFilter extends HttpServlet implements Filter{
  15. private static final long serialVersionUID = 1L;
  16. public LoginFilter() {
  17. }
  18. @Override
  19. public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
  20. throws IOException, ServletException {
  21. Boolean redirect_flag=true;
  22. HttpServletRequest request=(HttpServletRequest) arg0;
  23. HttpServletResponse response=(HttpServletResponse) arg1;
  24. //获取到session对象,登录状态信息存放在里面
  25. HttpSession session=request.getSession();
  26. //获取上下文路径
  27. String contextPath=request.getContextPath();
  28. //获取请求路径
  29. String url=request.getServletPath();
  30. System.out.println("ServletPath="+url);
  31. //设置检测一切非/login.jsp,/login.action,/images/的请求
  32. if (! url.startsWith("/login.jsp")&&!url.startsWith("/login.action")&&!url.startsWith("/images/")) {
  33. //获取session保存的登录状态
  34. System.out.println("session="+session.getAttribute("username"));
  35. Cookie cookies[] = request.getCookies();
  36. if (cookies!=null){
  37. //循环遍历cookie
  38. for(int i=0;i<cookies.length;i++){
  39. Cookie cookie = cookies[i];
  40. //判断是否已经登录过了
  41. if ("username".equals(cookie.getName())){
  42. System.out.println("你已经登录过了");
  43. redirect_flag=false;
  44. }
  45. }
  46. }
  47. //判断如果未登录则重定向到登录页面
  48. if (redirect_flag) {
  49. System.out.println("重定向到:"+contextPath+"/login.jsp");
  50. response.sendRedirect(contextPath+"/login.jsp");
  51. return;
  52. }else {
  53. System.out.println("已经登录了不拦截");
  54. }
  55. }else {
  56. System.out.println("我不拦截");
  57. }
  58. arg2.doFilter(arg0, arg1);
  59. }
  60. @Override
  61. public void init(FilterConfig arg0) throws ServletException {
  62. }
  63. }
    (7)Struts.xml
  1. <?xml version="1.0" encoding="GBK" ?>
  2. <!DOCTYPE struts PUBLIC
  3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  4. "http://struts.apache.org/dtds/struts-2.0.dtd">
  5. <struts>
  6. <!-- 配置开启开发模式 -->
  7. <constant name="struts.devMode" value="true"></constant>
  8. <!--配置后缀 -->
  9. <constant name="struts.action.extension" value="action" />
  10. <package name="default" namespace="/" extends="struts-default">
  11. <!-- 配置TestAction -->
  12. <action name="test" class="com.elimy.test.TestAction">
  13. <result name="error">/WEB-INF/index.jsp</result>
  14. <result name="success">/WEB-INF/main.jsp</result>
  15. </action>
  16. <!-- 配置LoginAction -->
  17. <action name="login" method="login" class="com.elimy.admin.LoginAction">
  18. <result name="error">login.jsp</result>
  19. <result name="success">/WEB-INF/main.jsp</result>
  20. </action>
  21. </package>
  22. </struts>
    (8)实体类User.java(实现jsp表单数据与Action映射)
  1. package com.elimy.entity;
  2. public class User {
  3. private String username;
  4. private String password;
  5. public String getUsername() {
  6. return username;
  7. }
  8. public void setUsername(String username) {
  9. this.username = username;
  10. }
  11. public String getPassword() {
  12. return password;
  13. }
  14. public void setPassword(String password) {
  15. this.password = password;
  16. }
  17. public User() {
  18. }
  19. }
     (9)测试
  1. ServletPath=/test.action
  2. session=null
  3. 重定向到:/Wechat/login.jsp
  4. ServletPath=/login.jsp
  5. 我不拦截
  6. ServletPath=/login.action
  7. 我不拦截
  8. 登录成功
  9. Session=elimy
  10. ServletPath=/images/back.jpg
  11. 我不拦截
  12. ServletPath=/test.action
  13. session=elimy
  14. 你已经登录过了
  15. 已经登录了不拦截
  16. TestAction 已经执行到了
  17. 4C4A4E2C49A2F51F677A1D7A2CF9C30F
  18. elimy
  19. [Ljavax.servlet.http.Cookie;@73d3d058
    上面是测试的控制台输出结果,测试步骤如下:
                1.首先直接访问 http://localhost:8080/Wechat/test.action  进入过滤器后判断没有session表示没有登录,所有不能直接访问,所以重定向到login.jsp
                2.输入用户名密码,控制台显示Session存在并且显示登录成功跳转到main.jsp页面
                3.最后我再次在浏览器输入 http://localhost:8080/Wechat/test.action 继续访问,这个时候会直接跳转到main.jsp,表示拦截成功
                ps:因为我设置的cookie保存时常为一天,所以伙伴们可以试试关掉浏览器然后重启访问test.action看会不会直接进入无需登录,同时可以清除一下浏览器cookie再访问看又有啥区别。

   2.2  action拦截器实现登录过滤   
         这里我们是通过struts2的拦截器拦截action去实现登录过滤的,实现的效果和前面一致,下面会贴出代码,与上面一致的就不贴出了。
   (1)实现拦截器类LoginActionIntercepter.java  
  1. package com.elimy.interceptor;
  2. import javax.servlet.http.Cookie;
  3. import javax.servlet.http.HttpServletRequest;
  4. import org.apache.struts2.StrutsStatics;
  5. import com.opensymphony.xwork2.ActionContext;
  6. import com.opensymphony.xwork2.ActionInvocation;
  7. import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
  8. public class LoginActionIntercepter extends AbstractInterceptor {
  9. private static final long serialVersionUID = 1L;
  10. public LoginActionIntercepter() {
  11. }
  12. @Override
  13. public void destroy() {
  14. System.out.println("LoginActionIntercepter->destroy()");
  15. }
  16. @Override
  17. public void init() {
  18. System.out.println("LoginActionIntercepter->init()");
  19. }
  20. /*
  21. * 实现拦截操作
  22. */
  23. @Override
  24. public String intercept(ActionInvocation arg0) throws Exception {
  25. boolean interceptor_flag=true;
  26. //获取到请求的action名
  27. String actionName=arg0.getProxy().getActionName();
  28. System.out.println("actionName="+actionName);
  29. //拦截除了login.action以外的所有action
  30. if ("login".equals(actionName)) {
  31. //通知调用后面的interceptor或者action
  32. return arg0.invoke();
  33. }
  34. //获取到actionContext
  35. ActionContext actionContext=arg0.getInvocationContext();
  36. //获取到HttpServletRequest
  37. HttpServletRequest request=(HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
  38. //获取到浏览器cookies
  39. Cookie[] cookies = request.getCookies();
  40. if (cookies!=null){
  41. for (Cookie cookie:cookies) {
  42. if ("elimy".equals(cookie.getValue())){
  43. interceptor_flag=false;
  44. }
  45. }
  46. //存在指定用户名的cookie则不拦截
  47. if (interceptor_flag) {
  48. System.out.println("亲爱的请先登录好吗?");
  49. return "login";
  50. }else {
  51. System.out.println("你已经登录过了,我不拦你");
  52. }
  53. }else {
  54. System.out.println("似乎没有cookie哟?");
  55. return "login";
  56. }
  57. //获取判断session中是否存在username的值
  58. /* String username=(String) arg0.getInvocationContext().getSession().get("username");
  59. if (username==null) {
  60. System.out.println("亲爱的请先登录好吗?");
  61. return "login";
  62. }*/
  63. return arg0.invoke();
  64. }
  65. }
      ps:该类会根据浏览器cookie中是否存在对于的用户名来判断是否拦截除login之外的action访问    
        (2)struts.xml配置
  1. <?xml version="1.0" encoding="GBK" ?>
  2. <!DOCTYPE struts PUBLIC
  3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  4. "http://struts.apache.org/dtds/struts-2.0.dtd">
  5. <struts>
  6. <!-- 配置开启开发模式 -->
  7. <constant name="struts.devMode" value="true"></constant>
  8. <!--配置后缀 -->
  9. <constant name="struts.action.extension" value="action" />
  10. <package name="default" namespace="/" extends="struts-default">
  11. <interceptors>
  12. <!-- 自定义的拦截器 -->
  13. <interceptor name="interceptorLogin" class="com.elimy.interceptor.LoginActionIntercepter"></interceptor>
  14. <!-- 将自定义的拦截器打包到一个拦截器栈 -->
  15. <interceptor-stack name="customStack">
  16. <interceptor-ref name="defaultStack"></interceptor-ref>
  17. <interceptor-ref name="interceptorLogin"></interceptor-ref>
  18. </interceptor-stack>
  19. </interceptors>
  20. <!-- 将自定义的拦截器栈应用到全局 -->
  21. <default-interceptor-ref name="customStack"></default-interceptor-ref>
  22. <!-- 设置全局的action跳转页面 -->
  23. <global-results>
  24. <result name="login">login.jsp</result>
  25. </global-results>
  26. <!-- 配置TestAction -->
  27. <action name="test" class="com.elimy.test.TestAction">
  28. <result name="error">/WEB-INF/index.jsp</result>
  29. <result name="success">/WEB-INF/main.jsp</result>
  30. </action>
  31. <!-- 配置LoginAction -->
  32. <action name="login" method="login" class="com.elimy.admin.LoginAction">
  33. <result name="error">login.jsp</result>
  34. <result name="success">/WEB-INF/main.jsp</result>
  35. </action>
  36. </package>
  37. </struts>
        (3)web.xml
  1. <?xml version="1.0" encoding="GBK"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  3. <!--配置struts2核心过滤器 -->
  4. <filter>
  5. <filter-name>struts2</filter-name>
  6. <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  7. </filter>
  8. <filter-mapping>
  9. <filter-name>struts2</filter-name>
  10. <url-pattern>/*</url-pattern>
  11. </filter-mapping>
  12. <!--设置欢迎界面 -->
  13. <welcome-file-list>
  14. <welcome-file>login.jsp</welcome-file>
  15. </welcome-file-list>
  16. </web-app>
        (4)测试
  1. actionName=test
  2. 亲爱的请先登录好吗?
  3. actionName=login
  4. 登录成功
  5. Session=elimy
  6. actionName=test
  7. 你已经登录过了,我不拦你
  8. TestAction 已经执行到了
  9. 4146440FB496BE79C6D3EEA0E3C89E17
  10. elimy
  11. actionName=test
  12. 似乎没有cookie哟?
  上面依然是控制台输出结果,执行动作顺序依次如下:
   1.直接访问 http://localhost:8080/Wechat/test.action 输出未登录提示,直接跳转到登录页面
   2.输入用户名密码登录 显示登录成功
   3.我再次访问 http://localhost:8080/Wechat/test.action  显示已经登录过了,我不拦你 表示cookie记住登录状态保存成功
   4.然后我清除浏览器cookies 访问http://localhost:8080/Wechat/test.action 显示没有cookies,并跳转到登录界面

   2.3  方法拦截器实现登录过滤 

          下面通过拦截方法来实现与上面相同的登录过滤功能,展示页面,LoginAction.java,TestAction.java等基本与上面一致,下面贴出核心的拦截器类和配置文件代码。
    (1)LoginMethodIntercepter.java
  1. package com.elimy.interceptor;
  2. import javax.servlet.http.Cookie;
  3. import javax.servlet.http.HttpServletRequest;
  4. import org.apache.struts2.StrutsStatics;
  5. import com.opensymphony.xwork2.ActionContext;
  6. import com.opensymphony.xwork2.ActionInvocation;
  7. import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
  8. public class LoginMethodInterceptor extends MethodFilterInterceptor {
  9. private static final long serialVersionUID = 1L;
  10. public LoginMethodInterceptor() {
  11. }
  12. @Override
  13. protected String doIntercept(ActionInvocation arg0) throws Exception {
  14. System.out.println("doIntercept()");
  15. //获取到ActionContext
  16. ActionContext actionContext = arg0.getInvocationContext();
  17. //获取到HttpServletRequest
  18. HttpServletRequest request =(HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
  19. //获取cookies
  20. Cookie[] cookies=request.getCookies();
  21. if (cookies!=null) {
  22. for(Cookie cookie:cookies ){
  23. if ("elimy".equals(cookie.getValue())) {
  24. return arg0.invoke();
  25. }
  26. }
  27. }else {
  28. System.out.println("没有cookies哟");
  29. return "login";
  30. }
  31. System.out.println("似乎没有登录哦");
  32. return "login";
  33. }
  34. }
    (2)struts.xml配置文件
  1. <?xml version="1.0" encoding="GBK" ?>
  2. <!DOCTYPE struts PUBLIC
  3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  4. "http://struts.apache.org/dtds/struts-2.0.dtd">
  5. <struts>
  6. <!-- 配置开启开发模式 -->
  7. <constant name="struts.devMode" value="true"></constant>
  8. <!--配置后缀 -->
  9. <constant name="struts.action.extension" value="action" />
  10. <package name="default" namespace="/" extends="struts-default">
  11. <interceptors>
  12. <!-- 方法拦截器 -->
  13. <interceptor name="methodInterception" class="com.elimy.interceptor.LoginMethodInterceptor"></interceptor>
  14. <!-- 包含方法拦截器的栈 -->
  15. <interceptor-stack name="customMethodStack">
  16. <interceptor-ref name="defaultStack"></interceptor-ref>
  17. <!-- 引入拦截器方法,并设置拦截方法 -->
  18. <interceptor-ref name="methodInterception">
  19. <!-- 设置需要拦截的方法 -->
  20. <param name="includeMethods"></param>
  21. <!-- 设置不需拦截的方法 -->
  22. <param name="excludeMethods">login</param>
  23. </interceptor-ref>
  24. </interceptor-stack>
  25. </interceptors>
  26. <!-- 将自定义的拦截器栈应用到全局 -->
  27. <default-interceptor-ref name="customMethodStack"></default-interceptor-ref>
  28. <!-- 设置全局的action跳转页面 -->
  29. <global-results>
  30. <result name="login">login.jsp</result>
  31. </global-results>
  32. <!-- 配置TestAction -->
  33. <action name="test" class="com.elimy.test.TestAction">
  34. <result name="error">/WEB-INF/index.jsp</result>
  35. <result name="success">/WEB-INF/main.jsp</result>
  36. </action>
  37. <!-- 配置LoginAction -->
  38. <action name="login" method="login" class="com.elimy.admin.LoginAction">
  39. <result name="error">login.jsp</result>
  40. <result name="success">/WEB-INF/main.jsp</result>
  41. </action>
  42. </package>
  43. </struts>
  (3) 测试结果
  1. doIntercept()
  2. 没有cookies哟
  3. 登录成功
  4. Session=elimy
  5. doIntercept()
  6. TestAction 已经执行到了
  7. 699E407E82BDBAD6D8E0D4FFCBDDB0FD
  8. elimy
  9. doIntercept()
  10. 没有cookies哟
 上面依然是控制台输出结果,执行动作顺序与前面一致
原创粉丝点击