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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章