1. 程式人生 > >Shiro與基本web環境整合登陸驗證實例

Shiro與基本web環境整合登陸驗證實例

erro pri void sta map -name -- role uid

1. 用maven導入Shiro依賴包

 <dependency>  
    <groupId>org.apache.shiro</groupId>  
    <artifactId>shiro-web</artifactId>  
    <version>1.2.2</version>  
</dependency> 
 <dependency>  
        <groupId>commons-logging</groupId>  
        <
artifactId>commons-logging</artifactId> <version>1.1.3</version> </dependency>

2.配置web.xml

   <!-- 初始化shiro web environment -->
    <listener>
          <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class
> </listener> <!-- 設置shiro攔截器--> <filter> <filter-name>ShiroFilter</filter-name> <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class> </filter> <filter-mapping> <filter-name>ShiroFilter</
filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

3.配置初始化shiro的配置文件 shiro.ini放在類文件根目錄

[main]
authc.loginUrl=/login
authc.successUrl=/index
[users]
zhang=123,role1,role2  
wang=123,role1  
[urls]
/login=authc
/logout=logout
/* = authc

4.創建一個servlet並映射至登陸路徑/login

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public LoginServlet() {
        super();
    }
	/**GET請求顯示登錄界面同時顯示錯誤信息
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//顯示登錄界面
		request.getRequestDispatcher("/login.jsp").forward(request, response);	
	}

	/**FormAuthenticationFilter將會攔截POST請求進行登錄操作,我們不需要再做登錄操作。
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("登錄失敗才會進入doPost方法。因為攔截器攔截了POST請求進行登錄,登錄成功則直接跳轉至訪問頁面。登錄失敗後才進入Post方法");
		System.out.println("登錄失敗才再登錄界面,並添加錯誤信息");
		
		//FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME值為shiroLoginFailure,保存了登錄錯誤信息,值為異常的類全名
		String errorFullClassName = (String)request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		String cerrorKey="error";//客戶端顯示的錯誤信息
		if(UnknownAccountException.class.getName().equals(errorFullClassName)){
			//未知賬戶
			request.setAttribute(cerrorKey, "用戶名密碼錯誤");
		}else if(IncorrectCredentialsException.class.getName().equals(errorFullClassName)){
			//密碼錯誤
			request.setAttribute(cerrorKey, "用戶名密碼錯誤");
		}else{
			//其他錯誤如賬戶鎖定等等
			request.setAttribute(cerrorKey, "其他錯誤");
		}
		//顯示登錄界面
		doGet(request, response);
	}

}

  

  <servlet>
      <servlet-name>LoginServlet</servlet-name>
      <servlet-class>baseshiroweb.LoginServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>LoginServlet</servlet-name>
      <url-pattern>/login</url-pattern>
  </servlet-mapping>

5.創建一個登陸界面login.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=UTF-8">
<title>Insert title here</title>
</head>
<body>
登陸界面<br/>
<form action="/baseshiroweb/login" method="post">

   Username: <input type="text" name="username"/> <br/>
   Password: <input type="password" name="password"/><br/>
   <input type="checkbox" name="rememberMe" value="true"/>Remember Me?<br/>
   <input type="submit" value="提交"/>
</form>
${error}
</body>
</html>

6.創建一個登陸成功後的信息顯示servlet並添加退出

public class MyServlet extends HttpServlet{

	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.getWriter().println("<html>");
		resp.getWriter().println("hello shiro web"+"<br/>");
		Subject subject = SecurityUtils.getSubject();
		resp.getWriter().println("principal:"+subject.getPrincipal()+"<br/>");
		resp.getWriter().println("isAuthenticated"+subject.isAuthenticated()+"<br/>");
		resp.getWriter().println("<a href=‘/baseshiroweb/logout‘>logout</a>");
		resp.getWriter().println("</html>");
	}
}
  <servlet>
      <servlet-name>myservlet</servlet-name>
      <servlet-class>baseshiroweb.MyServlet</servlet-class>
  </servlet>
  
    <servlet-mapping>
      <servlet-name>myservlet</servlet-name>
      <url-pattern>/index</url-pattern>
  </servlet-mapping>

 此時訪問http://localhost:8080/baseshiroweb/index

執行流程:

1.將會請求/index路徑 

2.匹配Shiro配置文件裏的[urls]內的/*路徑的authc攔截器,跳轉至登陸登陸界面/login

3.在/login進行登錄操作,成功則跳轉至/index,失敗則返回/login界面並顯示錯誤信息

4./index成功登錄後,點擊超鏈接logout訪問/logout進行退出操作。/logout路徑匹配logout攔截器。

完整的web.xml為

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 
  <display-name>Archetype Created Web Application</display-name>
   <!-- 初始化shiro web environment -->
    <listener>
          <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
  </listener>
  
<!-- 設置shiro攔截器-->
   <filter>
      <filter-name>ShiroFilter</filter-name>
      <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
  </filter>
  
  <filter-mapping>
      <filter-name>ShiroFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <servlet>
      <servlet-name>myservlet</servlet-name>
      <servlet-class>baseshiroweb.MyServlet</servlet-class>
  </servlet>
  
    <servlet-mapping>
      <servlet-name>myservlet</servlet-name>
      <url-pattern>/index</url-pattern>
  </servlet-mapping>
  
  <servlet>
      <servlet-name>LoginServlet</servlet-name>
      <servlet-class>baseshiroweb.LoginServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>LoginServlet</servlet-name>
      <url-pattern>/login</url-pattern>
  </servlet-mapping>

</web-app>

Shiro與基本web環境整合登陸驗證實例