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
<%@ page language="java" contentType="text/html; charset=utf8"
pageEncoding="utf8"%>
<!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=utf8">
<title>Insert title here</title>
</head>
<body>
<form action="login.action" method="post">
用户名:<input type="text" id="username" name="username"><br> 密码:<input
type="password" id="password" name="password"><br> <input type="submit"
value="提交">
</form>
</body>
</html>
(2)LoginAction.java
package com.elimy.admin;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.elimy.entity.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class LoginAction extends ActionSupport implements ModelDriven<User> {
private User user= new User();
/*
* 管理员登录功能
*/
public String login() {
//通过ServletActionContext获取到requst和 response请求对象
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response= ServletActionContext.getResponse();
//获取到浏览器上午cookies
Cookie cookies[] = request.getCookies();
//遍历cookie是否有登录信息
if (cookies!=null){
for(int i=0;i<cookies.length;i++){
Cookie cookie = cookies[i];
if ("elimy".equals(cookie.getValue())){
System.out.println("你已经登录过了");
//直接返回跳转到管理页面
return SUCCESS;
}
}
}
//判断用户名和密码是否成功,这里就不从数据库获取了
if ("elimy".equals(user.getUsername())&& "8888".equals(user.getPassword())) {
System.out.println("登录成功");
//将登录状态写入session
request.getSession().setAttribute("username", user.getUsername());
//用户名存入cookie
Cookie cookie1 = new Cookie("username", user.getUsername());
//设置Cookie生命周期为一天
cookie1.setMaxAge(60 * 60 * 24 * 1);
//保存cookie
response.addCookie(cookie1);
System.out.println("Session="+request.getAttribute("username"));
return SUCCESS;
}else {
//检测是否内容为空
if (user.getUsername()==null&&user.getPassword()==null) {
System.out.println("输入内容为空,请输入内容先");
}else {
System.out.println(user.getUsername());
System.out.println(user.getPassword());
System.out.println("登录失败");
}
return ERROR ;
}
}
@Override
public User getModel() {
return user;
}
}
(3)mian.jsp
<%@ page language="java" contentType="text/html; charset=utf8"
pageEncoding="utf8"%>
<!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=utf8">
<title>管理页面</title>
</head>
<body background="<%=request.getContextPath()%>/images/back.jpg"
style=" background-repeat:no-repeat;
background-size:100% 100%;
background-attachment: fixed;"
>
welcome to struts2~~main.jsp!
<table>
<ul>
<li>用户权限管理</li>
<li>注册管理</li>
<li>管理</li>
<li>昵称管理</li>
<li>管理</li>
</ul>
</table>
</body>
</html>
(4)TestAction.java
package com.elimy.test;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport {
private static final long serialVersionUID = 1L;
@Override
public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
Cookie[] cookies=request.getCookies();
System.out.println("TestAction 已经执行到了");
if (cookies!=null) {
for (Cookie cookie:cookies) {
System.out.println(cookie.getValue());
}
}
System.out.println(request.getCookies());
- return SUCCESS;
}
}
(5)web.xml
<?xml version="1.0" encoding="GBK"?>
<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">
<!--配置登录过滤器 -->
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>com.elimy.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置struts2核心过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--设置欢迎界面 -->
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
(6)登录过滤器类LoginFilter.java
package com.elimy.filter;
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.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginFilter extends HttpServlet implements Filter{
private static final long serialVersionUID = 1L;
public LoginFilter() {
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
Boolean redirect_flag=true;
HttpServletRequest request=(HttpServletRequest) arg0;
HttpServletResponse response=(HttpServletResponse) arg1;
//获取到session对象,登录状态信息存放在里面
HttpSession session=request.getSession();
//获取上下文路径
String contextPath=request.getContextPath();
//获取请求路径
String url=request.getServletPath();
System.out.println("ServletPath="+url);
//设置检测一切非/login.jsp,/login.action,/images/的请求
if (! url.startsWith("/login.jsp")&&!url.startsWith("/login.action")&&!url.startsWith("/images/")) {
//获取session保存的登录状态
System.out.println("session="+session.getAttribute("username"));
Cookie cookies[] = request.getCookies();
if (cookies!=null){
//循环遍历cookie
for(int i=0;i<cookies.length;i++){
Cookie cookie = cookies[i];
//判断是否已经登录过了
if ("username".equals(cookie.getName())){
System.out.println("你已经登录过了");
redirect_flag=false;
}
}
}
//判断如果未登录则重定向到登录页面
if (redirect_flag) {
System.out.println("重定向到:"+contextPath+"/login.jsp");
response.sendRedirect(contextPath+"/login.jsp");
return;
}else {
System.out.println("已经登录了不拦截");
}
}else {
System.out.println("我不拦截");
}
arg2.doFilter(arg0, arg1);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
(7)Struts.xml
<?xml version="1.0" encoding="GBK" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 配置开启开发模式 -->
<constant name="struts.devMode" value="true"></constant>
<!--配置后缀 -->
<constant name="struts.action.extension" value="action" />
<package name="default" namespace="/" extends="struts-default">
<!-- 配置TestAction -->
<action name="test" class="com.elimy.test.TestAction">
<result name="error">/WEB-INF/index.jsp</result>
<result name="success">/WEB-INF/main.jsp</result>
</action>
<!-- 配置LoginAction -->
<action name="login" method="login" class="com.elimy.admin.LoginAction">
<result name="error">login.jsp</result>
<result name="success">/WEB-INF/main.jsp</result>
</action>
</package>
</struts>
(8)实体类User.java(实现jsp表单数据与Action映射)
package com.elimy.entity;
public class User {
private String username;
private String password;
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 User() {
}
}
(9)测试
ServletPath=/test.action
session=null
重定向到:/Wechat/login.jsp
ServletPath=/login.jsp
我不拦截
ServletPath=/login.action
我不拦截
登录成功
Session=elimy
ServletPath=/images/back.jpg
我不拦截
ServletPath=/test.action
session=elimy
你已经登录过了
已经登录了不拦截
TestAction 已经执行到了
4C4A4E2C49A2F51F677A1D7A2CF9C30F
elimy
[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
package com.elimy.interceptor;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.StrutsStatics;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class LoginActionIntercepter extends AbstractInterceptor {
private static final long serialVersionUID = 1L;
public LoginActionIntercepter() {
}
@Override
public void destroy() {
System.out.println("LoginActionIntercepter->destroy()");
}
@Override
public void init() {
System.out.println("LoginActionIntercepter->init()");
}
/*
* 实现拦截操作
*/
@Override
public String intercept(ActionInvocation arg0) throws Exception {
boolean interceptor_flag=true;
//获取到请求的action名
String actionName=arg0.getProxy().getActionName();
System.out.println("actionName="+actionName);
//拦截除了login.action以外的所有action
if ("login".equals(actionName)) {
//通知调用后面的interceptor或者action
return arg0.invoke();
}
//获取到actionContext
ActionContext actionContext=arg0.getInvocationContext();
//获取到HttpServletRequest
HttpServletRequest request=(HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
//获取到浏览器cookies
Cookie[] cookies = request.getCookies();
if (cookies!=null){
for (Cookie cookie:cookies) {
if ("elimy".equals(cookie.getValue())){
interceptor_flag=false;
}
}
//存在指定用户名的cookie则不拦截
if (interceptor_flag) {
System.out.println("亲爱的请先登录好吗?");
return "login";
}else {
System.out.println("你已经登录过了,我不拦你");
}
}else {
System.out.println("似乎没有cookie哟?");
return "login";
}
//获取判断session中是否存在username的值
/* String username=(String) arg0.getInvocationContext().getSession().get("username");
if (username==null) {
System.out.println("亲爱的请先登录好吗?");
return "login";
}*/
return arg0.invoke();
}
}
ps:该类会根据浏览器cookie中是否存在对于的用户名来判断是否拦截除login之外的action访问
(2)struts.xml配置
<?xml version="1.0" encoding="GBK" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 配置开启开发模式 -->
<constant name="struts.devMode" value="true"></constant>
<!--配置后缀 -->
<constant name="struts.action.extension" value="action" />
<package name="default" namespace="/" extends="struts-default">
<interceptors>
<!-- 自定义的拦截器 -->
<interceptor name="interceptorLogin" class="com.elimy.interceptor.LoginActionIntercepter"></interceptor>
<!-- 将自定义的拦截器打包到一个拦截器栈 -->
<interceptor-stack name="customStack">
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="interceptorLogin"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 将自定义的拦截器栈应用到全局 -->
<default-interceptor-ref name="customStack"></default-interceptor-ref>
<!-- 设置全局的action跳转页面 -->
<global-results>
<result name="login">login.jsp</result>
</global-results>
<!-- 配置TestAction -->
<action name="test" class="com.elimy.test.TestAction">
<result name="error">/WEB-INF/index.jsp</result>
<result name="success">/WEB-INF/main.jsp</result>
</action>
<!-- 配置LoginAction -->
<action name="login" method="login" class="com.elimy.admin.LoginAction">
<result name="error">login.jsp</result>
<result name="success">/WEB-INF/main.jsp</result>
</action>
</package>
</struts>
(3)web.xml
<?xml version="1.0" encoding="GBK"?>
<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">
<!--配置struts2核心过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--设置欢迎界面 -->
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
(4)测试
actionName=test
亲爱的请先登录好吗?
actionName=login
登录成功
Session=elimy
actionName=test
你已经登录过了,我不拦你
TestAction 已经执行到了
4146440FB496BE79C6D3EEA0E3C89E17
elimy
actionName=test
似乎没有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
package com.elimy.interceptor;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.StrutsStatics;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
public class LoginMethodInterceptor extends MethodFilterInterceptor {
private static final long serialVersionUID = 1L;
public LoginMethodInterceptor() {
}
@Override
protected String doIntercept(ActionInvocation arg0) throws Exception {
System.out.println("doIntercept()");
//获取到ActionContext
ActionContext actionContext = arg0.getInvocationContext();
//获取到HttpServletRequest
HttpServletRequest request =(HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
//获取cookies
Cookie[] cookies=request.getCookies();
if (cookies!=null) {
for(Cookie cookie:cookies ){
if ("elimy".equals(cookie.getValue())) {
return arg0.invoke();
}
}
}else {
System.out.println("没有cookies哟");
return "login";
}
System.out.println("似乎没有登录哦");
return "login";
}
}
(2)struts.xml配置文件
<?xml version="1.0" encoding="GBK" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 配置开启开发模式 -->
<constant name="struts.devMode" value="true"></constant>
<!--配置后缀 -->
<constant name="struts.action.extension" value="action" />
<package name="default" namespace="/" extends="struts-default">
<interceptors>
<!-- 方法拦截器 -->
<interceptor name="methodInterception" class="com.elimy.interceptor.LoginMethodInterceptor"></interceptor>
<!-- 包含方法拦截器的栈 -->
<interceptor-stack name="customMethodStack">
<interceptor-ref name="defaultStack"></interceptor-ref>
<!-- 引入拦截器方法,并设置拦截方法 -->
<interceptor-ref name="methodInterception">
<!-- 设置需要拦截的方法 -->
<param name="includeMethods"></param>
<!-- 设置不需拦截的方法 -->
<param name="excludeMethods">login</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 将自定义的拦截器栈应用到全局 -->
<default-interceptor-ref name="customMethodStack"></default-interceptor-ref>
<!-- 设置全局的action跳转页面 -->
<global-results>
<result name="login">login.jsp</result>
</global-results>
<!-- 配置TestAction -->
<action name="test" class="com.elimy.test.TestAction">
<result name="error">/WEB-INF/index.jsp</result>
<result name="success">/WEB-INF/main.jsp</result>
</action>
<!-- 配置LoginAction -->
<action name="login" method="login" class="com.elimy.admin.LoginAction">
<result name="error">login.jsp</result>
<result name="success">/WEB-INF/main.jsp</result>
</action>
</package>
</struts>
(3) 测试结果
doIntercept()
没有cookies哟
登录成功
Session=elimy
doIntercept()
TestAction 已经执行到了
699E407E82BDBAD6D8E0D4FFCBDDB0FD
elimy
doIntercept()
没有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
<%@ page language="java" contentType="text/html; charset=utf8"
pageEncoding="utf8"%>
<!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=utf8">
<title>Insert title here</title>
</head>
<body>
<form action="login.action" method="post">
用户名:<input type="text" id="username" name="username"><br> 密码:<input
type="password" id="password" name="password"><br> <input type="submit"
value="提交">
</form>
</body>
</html>
(2)LoginAction.java
package com.elimy.admin;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.elimy.entity.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class LoginAction extends ActionSupport implements ModelDriven<User> {
private User user= new User();
/*
* 管理员登录功能
*/
public String login() {
//通过ServletActionContext获取到requst和 response请求对象
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response= ServletActionContext.getResponse();
//获取到浏览器上午cookies
Cookie cookies[] = request.getCookies();
//遍历cookie是否有登录信息
if (cookies!=null){
for(int i=0;i<cookies.length;i++){
Cookie cookie = cookies[i];
if ("elimy".equals(cookie.getValue())){
System.out.println("你已经登录过了");
//直接返回跳转到管理页面
return SUCCESS;
}
}
}
//判断用户名和密码是否成功,这里就不从数据库获取了
if ("elimy".equals(user.getUsername())&& "8888".equals(user.getPassword())) {
System.out.println("登录成功");
//将登录状态写入session
request.getSession().setAttribute("username", user.getUsername());
//用户名存入cookie
Cookie cookie1 = new Cookie("username", user.getUsername());
//设置Cookie生命周期为一天
cookie1.setMaxAge(60 * 60 * 24 * 1);
//保存cookie
response.addCookie(cookie1);
System.out.println("Session="+request.getAttribute("username"));
return SUCCESS;
}else {
//检测是否内容为空
if (user.getUsername()==null&&user.getPassword()==null) {
System.out.println("输入内容为空,请输入内容先");
}else {
System.out.println(user.getUsername());
System.out.println(user.getPassword());
System.out.println("登录失败");
}
return ERROR ;
}
}
@Override
public User getModel() {
return user;
}
}
(3)mian.jsp
<%@ page language="java" contentType="text/html; charset=utf8"
pageEncoding="utf8"%>
<!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=utf8">
<title>管理页面</title>
</head>
<body background="<%=request.getContextPath()%>/images/back.jpg"
style=" background-repeat:no-repeat;
background-size:100% 100%;
background-attachment: fixed;"
>
welcome to struts2~~main.jsp!
<table>
<ul>
<li>用户权限管理</li>
<li>注册管理</li>
<li>管理</li>
<li>昵称管理</li>
<li>管理</li>
</ul>
</table>
</body>
</html>
(4)TestAction.java
package com.elimy.test;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport {
private static final long serialVersionUID = 1L;
@Override
public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
Cookie[] cookies=request.getCookies();
System.out.println("TestAction 已经执行到了");
if (cookies!=null) {
for (Cookie cookie:cookies) {
System.out.println(cookie.getValue());
}
}
System.out.println(request.getCookies());
- return SUCCESS;
}
}
(5)web.xml
<?xml version="1.0" encoding="GBK"?>
<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">
<!--配置登录过滤器 -->
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>com.elimy.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置struts2核心过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--设置欢迎界面 -->
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
(6)登录过滤器类LoginFilter.java
package com.elimy.filter;
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.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginFilter extends HttpServlet implements Filter{
private static final long serialVersionUID = 1L;
public LoginFilter() {
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
Boolean redirect_flag=true;
HttpServletRequest request=(HttpServletRequest) arg0;
HttpServletResponse response=(HttpServletResponse) arg1;
//获取到session对象,登录状态信息存放在里面
HttpSession session=request.getSession();
//获取上下文路径
String contextPath=request.getContextPath();
//获取请求路径
String url=request.getServletPath();
System.out.println("ServletPath="+url);
//设置检测一切非/login.jsp,/login.action,/images/的请求
if (! url.startsWith("/login.jsp")&&!url.startsWith("/login.action")&&!url.startsWith("/images/")) {
//获取session保存的登录状态
System.out.println("session="+session.getAttribute("username"));
Cookie cookies[] = request.getCookies();
if (cookies!=null){
//循环遍历cookie
for(int i=0;i<cookies.length;i++){
Cookie cookie = cookies[i];
//判断是否已经登录过了
if ("username".equals(cookie.getName())){
System.out.println("你已经登录过了");
redirect_flag=false;
}
}
}
//判断如果未登录则重定向到登录页面
if (redirect_flag) {
System.out.println("重定向到:"+contextPath+"/login.jsp");
response.sendRedirect(contextPath+"/login.jsp");
return;
}else {
System.out.println("已经登录了不拦截");
}
}else {
System.out.println("我不拦截");
}
arg2.doFilter(arg0, arg1);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
(7)Struts.xml
<?xml version="1.0" encoding="GBK" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 配置开启开发模式 -->
<constant name="struts.devMode" value="true"></constant>
<!--配置后缀 -->
<constant name="struts.action.extension" value="action" />
<package name="default" namespace="/" extends="struts-default">
<!-- 配置TestAction -->
<action name="test" class="com.elimy.test.TestAction">
<result name="error">/WEB-INF/index.jsp</result>
<result name="success">/WEB-INF/main.jsp</result>
</action>
<!-- 配置LoginAction -->
<action name="login" method="login" class="com.elimy.admin.LoginAction">
<result name="error">login.jsp</result>
<result name="success">/WEB-INF/main.jsp</result>
</action>
</package>
</struts>
(8)实体类User.java(实现jsp表单数据与Action映射)
package com.elimy.entity;
public class User {
private String username;
private String password;
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 User() {
}
}
(9)测试
ServletPath=/test.action
session=null
重定向到:/Wechat/login.jsp
ServletPath=/login.jsp
我不拦截
ServletPath=/login.action
我不拦截
登录成功
Session=elimy
ServletPath=/images/back.jpg
我不拦截
ServletPath=/test.action
session=elimy
你已经登录过了
已经登录了不拦截
TestAction 已经执行到了
4C4A4E2C49A2F51F677A1D7A2CF9C30F
elimy
[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
package com.elimy.interceptor;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.StrutsStatics;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class LoginActionIntercepter extends AbstractInterceptor {
private static final long serialVersionUID = 1L;
public LoginActionIntercepter() {
}
@Override
public void destroy() {
System.out.println("LoginActionIntercepter->destroy()");
}
@Override
public void init() {
System.out.println("LoginActionIntercepter->init()");
}
/*
* 实现拦截操作
*/
@Override
public String intercept(ActionInvocation arg0) throws Exception {
boolean interceptor_flag=true;
//获取到请求的action名
String actionName=arg0.getProxy().getActionName();
System.out.println("actionName="+actionName);
//拦截除了login.action以外的所有action
if ("login".equals(actionName)) {
//通知调用后面的interceptor或者action
return arg0.invoke();
}
//获取到actionContext
ActionContext actionContext=arg0.getInvocationContext();
//获取到HttpServletRequest
HttpServletRequest request=(HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
//获取到浏览器cookies
Cookie[] cookies = request.getCookies();
if (cookies!=null){
for (Cookie cookie:cookies) {
if ("elimy".equals(cookie.getValue())){
interceptor_flag=false;
}
}
//存在指定用户名的cookie则不拦截
if (interceptor_flag) {
System.out.println("亲爱的请先登录好吗?");
return "login";
}else {
System.out.println("你已经登录过了,我不拦你");
}
}else {
System.out.println("似乎没有cookie哟?");
return "login";
}
//获取判断session中是否存在username的值
/* String username=(String) arg0.getInvocationContext().getSession().get("username");
if (username==null) {
System.out.println("亲爱的请先登录好吗?");
return "login";
}*/
return arg0.invoke();
}
}
ps:该类会根据浏览器cookie中是否存在对于的用户名来判断是否拦截除login之外的action访问
(2)struts.xml配置
<?xml version="1.0" encoding="GBK" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 配置开启开发模式 -->
<constant name="struts.devMode" value="true"></constant>
<!--配置后缀 -->
<constant name="struts.action.extension" value="action" />
<package name="default" namespace="/" extends="struts-default">
<interceptors>
<!-- 自定义的拦截器 -->
<interceptor name="interceptorLogin" class="com.elimy.interceptor.LoginActionIntercepter"></interceptor>
<!-- 将自定义的拦截器打包到一个拦截器栈 -->
<interceptor-stack name="customStack">
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="interceptorLogin"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 将自定义的拦截器栈应用到全局 -->
<default-interceptor-ref name="customStack"></default-interceptor-ref>
<!-- 设置全局的action跳转页面 -->
<global-results>
<result name="login">login.jsp</result>
</global-results>
<!-- 配置TestAction -->
<action name="test" class="com.elimy.test.TestAction">
<result name="error">/WEB-INF/index.jsp</result>
<result name="success">/WEB-INF/main.jsp</result>
</action>
<!-- 配置LoginAction -->
<action name="login" method="login" class="com.elimy.admin.LoginAction">
<result name="error">login.jsp</result>
<result name="success">/WEB-INF/main.jsp</result>
</action>
</package>
</struts>
(3)web.xml
<?xml version="1.0" encoding="GBK"?>
<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">
<!--配置struts2核心过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--设置欢迎界面 -->
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
(4)测试
actionName=test
亲爱的请先登录好吗?
actionName=login
登录成功
Session=elimy
actionName=test
你已经登录过了,我不拦你
TestAction 已经执行到了
4146440FB496BE79C6D3EEA0E3C89E17
elimy
actionName=test
似乎没有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
package com.elimy.interceptor;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.StrutsStatics;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
public class LoginMethodInterceptor extends MethodFilterInterceptor {
private static final long serialVersionUID = 1L;
public LoginMethodInterceptor() {
}
@Override
protected String doIntercept(ActionInvocation arg0) throws Exception {
System.out.println("doIntercept()");
//获取到ActionContext
ActionContext actionContext = arg0.getInvocationContext();
//获取到HttpServletRequest
HttpServletRequest request =(HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
//获取cookies
Cookie[] cookies=request.getCookies();
if (cookies!=null) {
for(Cookie cookie:cookies ){
if ("elimy".equals(cookie.getValue())) {
return arg0.invoke();
}
}
}else {
System.out.println("没有cookies哟");
return "login";
}
System.out.println("似乎没有登录哦");
return "login";
}
}
(2)struts.xml配置文件
<?xml version="1.0" encoding="GBK" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 配置开启开发模式 -->
<constant name="struts.devMode" value="true"></constant>
<!--配置后缀 -->
<constant name="struts.action.extension" value="action" />
<package name="default" namespace="/" extends="struts-default">
<interceptors>
<!-- 方法拦截器 -->
<interceptor name="methodInterception" class="com.elimy.interceptor.LoginMethodInterceptor"></interceptor>
<!-- 包含方法拦截器的栈 -->
<interceptor-stack name="customMethodStack">
<interceptor-ref name="defaultStack"></interceptor-ref>
<!-- 引入拦截器方法,并设置拦截方法 -->
<interceptor-ref name="methodInterception">
<!-- 设置需要拦截的方法 -->
<param name="includeMethods"></param>
<!-- 设置不需拦截的方法 -->
<param name="excludeMethods">login</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 将自定义的拦截器栈应用到全局 -->
<default-interceptor-ref name="customMethodStack"></default-interceptor-ref>
<!-- 设置全局的action跳转页面 -->
<global-results>
<result name="login">login.jsp</result>
</global-results>
<!-- 配置TestAction -->
<action name="test" class="com.elimy.test.TestAction">
<result name="error">/WEB-INF/index.jsp</result>
<result name="success">/WEB-INF/main.jsp</result>
</action>
<!-- 配置LoginAction -->
<action name="login" method="login" class="com.elimy.admin.LoginAction">
<result name="error">login.jsp</result>
<result name="success">/WEB-INF/main.jsp</result>
</action>
</package>
</struts>
(3) 测试结果
doIntercept()
没有cookies哟
登录成功
Session=elimy
doIntercept()
TestAction 已经执行到了
699E407E82BDBAD6D8E0D4FFCBDDB0FD
elimy
doIntercept()
没有cookies哟
上面依然是控制台输出结果,执行动作顺序与前面一致
阅读全文
0 0
- Struts2多方法实现登录过滤拦截
- Struts2多方法实现登录过滤拦截
- struts2拦截器实现session会话过滤
- 【Struts2】:拦截器实现方法过滤
- 实现Struts2中对未登录的jsp页面进行拦截功能(采用的是Struts2中过滤器进行过滤拦截)
- java之Struts2实现用户登录过滤
- struts2拦截器实现登录控制
- Struts2 拦截器 实现登录权限
- struts2拦截器实现登录限制
- Struts2自定义拦截器,实现登录检查。
- J2EE学习笔记——Struts2多方法实现
- Struts2拦截器 实现未登录拦截和权限控制
- Struts2拦截器 实现未登录拦截和权限控制
- Struts2 拦截器Interceptor实现防止恶意登录(登录限制)
- Struts2 Action多方法调用
- Struts2 Action多方法调用
- Struts2多方法的Action
- STRUTS2 登录拦截器
- babel学习笔记
- 深度学习综述
- 嵌入式Linux下PWM功能调试
- $.ajax()——超时设置,增加 loading 提升体验
- mysql 父类查询所有子类以及从子类查询父类
- Struts2多方法实现登录过滤拦截
- Android关于软键盘弹出遮盖了原来界面的布局控件
- 四大组件之BroadcastReceiver(广播接收者)
- Android编译时报错Error:Connection timed out: connect. If you are behind an HTTP proxy, please......
- 工具栏使用
- js 导出 excel 文件
- 获取本地内存状态值
- Android 之 Material Design(二)—BottomNavigationView
- 2017网易春招 工作安排(dfs)