shiro入门实战笔记(7)--Web集成

[本系列文章是博主的学习笔记,而非经典教程,特此说明]

前面的几篇文章我们都是通过单元用例的方式来介绍shiro中基础核心的概念,接下来,我们来介绍在web开发中如何集成shiro。惯例,我们需要读者准备基础开发环境:

a.操作系统:win7 x64

b.开发工具:myeclipse 2014,jdk1.7,maven3.3.3,jsp基础,

------------------------------------------------------------------------------------------------------------------------------------------------

正文开始:

1.创建shiro05工程,工程结构如下:

shiro入门实战笔记(7)--Web集成_第1张图片

2.我们接着来引入本例中所需要的jar包,pom文件的内容如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.java.shiro</groupId>
	<artifactId>shiro05</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>shiro05 Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-core</artifactId>
			<version>1.2.4</version>
		</dependency>
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-web</artifactId>
			<version>1.2.4</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.13</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>shiro05</finalName>
	</build>
</project>
写入上面的依赖,保存,maven会帮助我们自动的下载相关的包。下载号之后,我们在工程的maven dependencies下就可以看到如下内容,如果有遗漏,请读者认真检查。


3.创建shiro.ini配置文件,位置在WEB-INF下,请注意,一定按照如下的格式书写:

[main]
authc.loginUrl=/login
roles.unauthorizedUrl=/unauthorized.jsp
perms.unauthorizedUrl=/unauthorized.jsp
[users]
shiro05=1234,admin
shiro051=1234,teacher
shiro052=1234
[roles]
admin=user:*
teacher=student:*
[urls]
/login=anon
/admin=authc
/student=roles[teacher]
/teacher=perms["user:create"]
现在,我们先逐一解释上面配置项的作用:

authc.loginUrl:身份认证没有通过时,跳转的路径

roles.unauthorizedUrl:角色认证没有通过时,跳转的路径

perms.unauthorizedUrl:权限认证没有通过时,跳转的路径

[urls]
/login=anon:访问login路径时,不需要任何权限,即游客身份
/admin=authc:访问admin路径时,需要身份认证
/student=roles[teacher]:访问student路径时,需要teacher角色才能访问
/teacher=perms["user:create"]:访问teacher路径时,需要user:create权限才能访问
shiro中提供的所有配置项如下,读者可以按照自身需求参考官方文档配置:

shiro入门实战笔记(7)--Web集成_第2张图片

4.配置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_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>ss</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<listener>
		<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
	</listener>
	<filter>
		<filter-name>iniShiroFilter</filter-name>
		<filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
		<init-param>
			<param-name>shiroConfigLocations</param-name>
			<param-value>/WEB-INF/shiro.ini</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>iniShiroFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<servlet>
		<servlet-name>loginServlet</servlet-name>
		<servlet-class>shiro05.LoginServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>loginServlet</servlet-name>
		<url-pattern>/login</url-pattern>
	</servlet-mapping>
	<servlet>
		<servlet-name>adminServlet</servlet-name>
		<servlet-class>shiro05.AdminServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>adminServlet</servlet-name>
		<url-pattern>/admin</url-pattern>
	</servlet-mapping>

</web-app>

5.创建LoginServlet.java,具体内容如下:

package shiro05;

import java.io.IOException;

/**
 *@author 作者 E-mail:
 *@version 创建时间:2016年2月11日下午4:24:21
 *类说明
 */
public class LoginServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("login doget");
		req.getRequestDispatcher("login.jsp").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("login dopost");
		String username= req.getParameter("username");
		String password=req.getParameter("password");
		Subject sub = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username,password);
		try {
			sub.login(token);
			resp.sendRedirect("success.jsp");
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			req.setAttribute("errorInfo","用户名密码错误");
			req.getRequestDispatcher("login.jsp").forward(req, resp);
		}
	}

	
}
6.创建login.jsp,具体内容如下:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'login.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    <form action="login" method="post">
    username:<input type="text" name="username"/><br>
    password:<input type="password" name="password"/><br>
    <input type="submit" value="login"/>
  </body>
</html>

7.创建success.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>
欢迎您
</body>
</html>

8.创建AdminServlet.java,具体内容如下:

package shiro05;

import java.io.IOException;

/**
 *@author 作者 E-mail:
 *@version 创建时间:2016年2月11日下午4:24:21
 *类说明
 */
public class AdminServlet extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("admin doget");
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("admin dopost");
	}
}

9.创建unauthorized.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>
认证未通过,或者,权限不足
</body>
</html>

10.单元测试流程:

a.启动服务器,尝试访问已经配置好的路径,如/login,/admin。此时,浏览器都将跳转到login.jsp页面

b.在login.jsp页面上输入已经预置好的用户名,密码。如:shiro05=1234,admin。接着,直接修改浏览地址栏后缀为admin。请查看浏览器跳转结果,及控制台结果输出。接着,直接修改浏览地址栏后缀为student。请查看浏览器跳转结果,及控制台结果输出。最后,直接修改浏览地址栏后缀为teacher。再查看浏览器跳转结果,及控制台结果输出。

c.再在login.jsp页面上分别输入已经预置好的其他两个用户名,密码。按照b步骤的流程在尝试一遍,查看每一个步骤的结果有何区别。

d.将上面的结果与配置文件设置的内容进行对参照对比,便非常容易理解用户,角色,权限在web中的使用方法。

-------------------------------------------------------------------------------------------------------------------------------------------------

至此,shiro入门实战笔记(7)--Web集成结束


参考资料:

官方文档:http://shiro.apache.org/documentation.html

其他博文:http://jinnianshilongnian.iteye.com/blog/2018936



你可能感兴趣的:(java,apache,开发,shiro,权限控制,web集成)