Shiro与基本web环境整合登陆验证实例

Posted 曙光城邦

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Shiro与基本web环境整合登陆验证实例相关的知识,希望对你有一定的参考价值。

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环境整合登陆验证实例的主要内容,如果未能解决你的问题,请参考以下文章

(转)shiro权限框架详解06-shiro与web项目整合(下)

全栈编程系列SpringBoot整合Shiro(含KickoutSessionControlFilter并发在线人数控制以及不生效问题配置启动异常No SecurityManager...)(代码片段

Shiro框架与SpringMVC之间的冲突

springboot+shiro整合教程

shiro的使用与JWT整合

单体物联平台系统(Springboot整合shiro实现多realm多用户表多权限表登陆)