Struts2中利用filter、session实现安全访问和身份认证

1、开发环境:

Eclipse软件

JDK 1.7

Apach Tomcat 7

2、通过eclipse创建Dynamic Web Project后,导入相应的Struts2 的jar文件:




3、导入jar包后,创建如下图所示项目相应目录:

   权限说明 
(1) 根目录(WebContent)下的资源,如:index.jsp和login.jsp,允许匿名访问。 
(2) Admin目录下的admin.jsp只允许角色为”admin”的用户访问。 User目录下的user.jsp只允许角色为”user”的用户访问



4、相应的jsp代码如下:

@index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<form name="welcome" action="welcome" method="post">
		<table>
			<tr>
				<td>welcome to you !</td>
			</tr>
			<tr>
				<td><input value="login" type="submit" /></td>
			</tr>
		</table>
	</form>
</body>
</html>
@login.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form name="login" action="login" method="post">
		<table>
			<tr>
				<td>用户名</td>
				<td><input name="name" type="text" /></td>
			</tr>
			<tr>
				<td>密码</td>
				<td><input name="password" type="password" /></td>
			</tr>
			<tr>
				<td></td>
				<td><input value="submit" type="submit" /></td>
			</tr>
		</table>
	</form>
	<%=path%>
	<%=request.getRequestURI()%>
	<%=request.getServletPath()%>
</body>
</html>

@user.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<%
		String user = (String) session.getAttribute("name");
		String balance = (String) session.getAttribute("balance");
		String address = (String) session.getAttribute("address");
		String tel = (String) session.getAttribute("tel");
	%>
	<form>
		<table>
			<tr>
				<td>用户名:</td>
				<td><%=user %></td>
			</tr>
			<tr>
				<td>余额:</td>
				<td><%=balance %></td>
			</tr>
			<tr>
				<td>住址:</td>
				<td><%=address %></td>
			</tr>
			<tr>
				<td>电话:</td>
				<td><%=tel %></td>
			</tr>
		</table>
	</form>
</body>
</html>

@admin.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<%
		String user = (String) session.getAttribute("name");
		String balance = (String) session.getAttribute("balance");
		String address = (String) session.getAttribute("address");
		String tel = (String) session.getAttribute("tel");
	%>
	<form>
		<table>
			<tr>
				<td>用户名:</td>
				<td><%=user %></td>
			</tr>
			<tr>
				<td>余额:</td>
				<td><%=balance %></td>
			</tr>
			<tr>
				<td>住址:</td>
				<td><%=address %></td>
			</tr>
			<tr>
				<td>电话:</td>
				<td><%=tel %></td>
			</tr>
		</table>
	</form>
</body>
</html>
@创建用于登陆验证类Login.java:

package com.axb.cheney.filter;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;

public class Login extends ActionSupport
  implements ServletRequestAware
{
  private static final long serialVersionUID = 1L;
  private String name;
  private String password;
  private HttpServletRequest request;

  public String pass()
  {
    HttpServletRequest req = this.request;
    HttpSession session = req.getSession();
    if ((this.name.equals("user1")) && (this.password.equals("password1"))) {
      session.setAttribute("name", this.name);
      session.setAttribute("balance", "10,000");
      session.setAttribute("address", "广东省深圳市福田区购物公园");
      session.setAttribute("tel", "12665654856");
      System.out.println("login:" + this.name);
      return "user";
    }if ((this.name.equals("admin")) && (this.password.equals("password2"))) {
      session.setAttribute("name", this.name);
      session.setAttribute("balance", "9,000");
      session.setAttribute("address", "广东省珠海市香洲区北理工");
      session.setAttribute("tel", "14956569898");
      System.out.println("login:" + this.name);
      return "admin";
    }
    System.out.println("login: fail");
    return "failure";
  }

  public String getName()
  {
    return this.name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getPassword() {
    return this.password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public HttpServletRequest getRequest() {
    return this.request;
  }

  public void setServletRequest(HttpServletRequest request)
  {
    this.request = request;
  }
}
@修改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>

	<constant name="struts.enable.DynamicMethodInvocation" value="false" />
	<constant name="struts.devMode" value="true" />

	<package name="default" namespace="/" extends="struts-default">

		<default-action-ref name="index" />

		<global-results>
			<result name="error">/WEB-INF/error.jsp</result>
		</global-results>
		<action name="welcome">
			<result>/login.jsp </result>
		</action>
		<action name="login" class="com.axb.cheney.filter.Login"
			method="pass">
			<result name="failure">/login.jsp </result>
			<result name="user">/user/user.jsp </result>
			<result name="admin">/admin/admin.jsp </result>
		</action>
	</package>

</struts>


@创建用于拦截验证身份的UserAuthenticationFilter.java

package com.axb.cheney.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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class UserAuthenticationFilter
  implements Filter
{
  private static String LOGIN_PAGE = "/login.jsp";

  public void destroy()
  {
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException
  {
    HttpServletRequest req = (HttpServletRequest)request;
    HttpServletResponse res = (HttpServletResponse)response;

    String currentUrl = req.getServletPath();

    HttpSession session = req.getSession();

    System.out.println("UserAuthenticationFilter");
    if (currentUrl.equals("")) currentUrl = currentUrl + "/";
    if ((currentUrl.startsWith("/")) && (!currentUrl.startsWith("/login.jsp"))) {
      String user = (String)session.getAttribute("name");
      if (user == null) {
        res.sendRedirect(req.getContextPath() + LOGIN_PAGE);
        return;
      }
      if (!user.equals("user1")) {
        session.removeAttribute("name");
        res.sendRedirect(req.getContextPath() + LOGIN_PAGE);
        return;
      }
    }

    chain.doFilter(request, response);
  }

  public void init(FilterConfig arg0)
    throws ServletException
  {
  }
}


@创建用于拦截验证身份的AdminAuthenticationFilter.java

package com.axb.cheney.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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AdminAuthenticationFilter
  implements Filter
{
  private static String LOGIN_PAGE = "/login.jsp";

  public void destroy()
  {
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException
  {
    HttpServletRequest req = (HttpServletRequest)request;
    HttpServletResponse res = (HttpServletResponse)response;

    String currentUrl = req.getServletPath();

    HttpSession session = req.getSession();

    System.out.println("AdminAuthenticationFilter");
    if (currentUrl.equals("")) currentUrl = currentUrl + "/";
    if ((currentUrl.startsWith("/")) && (!currentUrl.startsWith("/login.jsp"))) {
      String user = (String)session.getAttribute("name");
      if (user == null) {
        res.sendRedirect(req.getContextPath() + LOGIN_PAGE);
        return;
      }
      if (!user.equals("admin")) {
        session.removeAttribute("name");
        res.sendRedirect(req.getContextPath() + LOGIN_PAGE);
        return;
      }
    }
    chain.doFilter(request, response);
  }

  public void init(FilterConfig arg0)
    throws ServletException
  {
  }
}

@最后配置web.xml文件用于过滤admin和user目录下的资源访问

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	<display-name>SAML</display-name>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

	 <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> 

	<filter>
		<filter-name>UserAuthentication</filter-name>
		<filter-class>com.axb.cheney.filter.UserAuthenticationFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>UserAuthentication</filter-name>
		<url-pattern>/user/*</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>AdminAuthentication</filter-name>
		<filter-class>com.axb.cheney.filter.AdminAuthenticationFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>AdminAuthentication</filter-name>
		<url-pattern>/admin/*</url-pattern>
	</filter-mapping>


</web-app>

5、测试结果如下:

@当第一次运行tomcat时,页面显示index.jsp主界面,如图1所示。

当点击页面<login>按钮,页面将调转到图2所示用户登陆页面。

图1


图2

@当你想通过直接访问user资源时,如图3所示,输入资源相应路径时,访问User子目录的任何资源,

都将被UserAuthenticationFilter捕获。UserAuthenticationFilter对请求进行验证,检查session中是否

有正确的登录信息,是否有相应的权限。如果通过了验证,允许访问,否则不允许访问,向客户端浏

览器返回login.jsp,让用户进行登录。


图3


图4

@当验证正确时,页面显示请求的相应内容,如图5所示

图5

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值