Shiro——Web环境下的使用

web搭建

见:SpringMVC入门案例

依赖

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-all</artifactId>
    <version>1.7.1</version>
</dependency>
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>

主配置文件

resources下shiro.ini

[users]
abc=123
[urls]
**=anon

这表示全部放行

主监听器,拦截器

监听器用于加载配置文件
拦截器用于配置SecurityManager

<listener>
    <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>
<context-param>
    <param-name>shiroEnvironmentClass</param-name>
    <param-value>org.apache.shiro.web.env.IniWebEnvironment</param-value>
</context-param>
<context-param>
    <param-name>shiroConfigLocations</param-name>
    <param-value>classpath:shiro.ini</param-value>
</context-param>
<filter>
    <filter-name>shiro</filter-name>
    <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>shiro</filter-name>
    <servlet-name>mvc</servlet-name>
</filter-mapping>

控制器

@RequestMapping("/hello")
public String hello(String name, String pass) {
	UsernamePasswordToken token = new UsernamePasswordToken(name, pass);
	Subject subject = SecurityUtils.getSubject();
	try {
		subject.login(token);
		System.out.println("你好,沃德!");
		return "/WEB-INF/index.jsp";
	} catch (AuthenticationException e) {
		e.printStackTrace();
		System.out.println("登陆失败");
		return "/WEB-INF/error.jsp";
	}
}

两个结果页面

<%@page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head></head>
<body>
你好,沃德!
</body>
</html>

<%@page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head></head>
<body>
登陆失败
</body>
</html>

运行案例

正确的密码:

Shiro——Web环境下的使用

错误的密码:

Shiro——Web环境下的使用

上一篇:数据类型与运算符


下一篇:搭建 Zookeeper 3.6.3 集群时出现的错误