虽然Apache Shiro的核心设计目标允许它用于保护任何基于JVM的应用程序(如命令行应用程序,服务器守护程序,Web应用程序等),但本指南将着重讨论最常见的用例:确保运行的Web应用程序一个Servlet容器,比如Tomcat或者Jetty。
先决条件
预计将在本地开发机器上安装以下工具,以便跟随本教程。
Java SDK 7
Maven 3
您最喜爱的IDE,如IntelliJ IDEA或Eclipse,甚至是一个简单的文本编辑器来查看文件并进行更改。
创建Web项目(使用Maven)
配置pom.xml
导入jar
<dependencies> <!-- shiro --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiro.version}</version> </dependency> </dependencies>
配置build
<build> <finalName>shiro-web-test</finalName> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> <plugins> <!-- jetty插件 --> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <!--<version>9.0.0.v20130308</version> --> <version>9.2.7.v20150116</version> <configuration> <scanIntervalSeconds>3</scanIntervalSeconds> <webApp> <contextPath>/</contextPath> </webApp> <httpConnector> <port>8080</port> </httpConnector> <reload>automatic</reload> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.18.1</version> <configuration> <skipTests>true</skipTests> <testFailureIgnore>true</testFailureIgnore> </configuration> </plugin> </plugins> </build>
添加shiro.ini文件(src/main/resources/shiro.ini)
# ======================= # Shiro INI configuration # ======================= [main] # Objects and their properties are defined here, # Such as the securityManager, Realms and anything # else needed to build the SecurityManager [users] admin = secret lonestarr = vespa, goodguy, schwartz darkhelmet = ludicrousspeed, badguy, schwartz [roles] admin = * schwartz = lightsaber:* goodguy = winnebago:drive:eagle5 [urls] /user/** = authc /login = anon
配置web.xml
<listener> <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class> </listener> <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> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> <dispatcher>INCLUDE</dispatcher> <dispatcher>ERROR</dispatcher> </filter-mapping>
该
<listener>
声明定义了一个ServletContextListener
启动SecurityManager
Web应用程序时启动Shiro环境(包括Shiro )的应用程序。默认情况下,这个侦听器会自动知道为我们的WEB-INF/shiro.ini
文件寻找Shiro配置。该
<filter>
声明定义了主人ShiroFilter
。此过滤器将过滤所有对Web应用程序的请求,以便Shiro在允许请求到达应用程序之前执行必要的身份和访问控制操作。该
<filter-mapping>
声明确保所有请求类型均由ShiroFilter
。通常filter-mapping
声明不指定<dispatcher>
元素,但Shiro需要定义所有元素,以便可以过滤可能为Web应用程序执行的所有不同请求类型。
创建登陆页面
<%@ 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> <form action="/login" method="post"> 用户名:<input name="username" type="text"/> 密码:<input name="password" type="text"/> <input type="submit" value="登陆" /> </form> </body> </html>
创建登陆servlet
package com.coder306; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.subject.Subject; public class Login extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); String password = req.getParameter("password"); IniSecurityManagerFactory iniSecurityManagerFactory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = iniSecurityManagerFactory.getInstance(); SecurityUtils.setSecurityManager(securityManager); Subject subject = SecurityUtils.getSubject(); if(!subject.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken(username,password); try { subject.login(token); resp.sendRedirect("/user/index.jsp"); }catch (UnknownAccountException uae) { resp.sendRedirect("/login.jsp"); }catch (IncorrectCredentialsException ice) { resp.sendRedirect("/login.jsp"); }catch (LockedAccountException lae) { resp.sendRedirect("/login.jsp"); } }else { resp.sendRedirect("/user/index.jsp"); } } }
web.xml配置servlet
<servlet> <servlet-class>com.coder306.Login</servlet-class> <servlet-name>login</servlet-name> </servlet> <servlet-mapping> <servlet-name>login</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping>
运行webapp
mvn jetty:run
查看原文: http://www.coder306.cn/?p=200