1,项目总结构
2,准备数据库
Permission:权限表
Role角色表
Role_permission 权限和角色的关系表
User 用户名
User_role用户和角色和关系表
用户对应角色和权限
张三 ---1---à person:query, person:add, person:update person:delete
李四 ---2---à person:query, person:add, person:update
王五 ---3---à person:query, person:export
3,修改pom.xml
<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.sxt</groupId>
<artifactId>05_shiro_ssm_layui</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>05_shiro_ssm_layui Maven Webapp</name>
<url>http://maven.apache.org</url>
<!-- 声明版本 -->
<properties>
<servlet.version>3.1.0</servlet.version>
<jsp.version>2.3.1</jsp.version>
<spring.version>4.3.24.RELEASE</spring.version>
<mybatis.version>3.5.1</mybatis.version>
<mybatis-spring.version>2.0.1</mybatis-spring.version>
<mysql.version>5.1.47</mysql.version>
<pagehelper.version>5.1.10</pagehelper.version>
<druid.version>1.1.19</druid.version>
<log4j.version>1.2.17</log4j.version>
<slf4j.version>1.7.26</slf4j.version>
<jackson.version>2.9.9</jackson.version>
<shiro.version>1.4.1</shiro.version>
</properties>
<dependencies>
<!--servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!-- javax.servlet.jsp -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<!--spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<!-- mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>${pagehelper.version}</version>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- 引入shiro的包 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</version>
</dependency>
</dependencies>
<build>
<finalName>05_shiro_ssm_layui</finalName>
<plugins>
<!-- 加入tomcat运行插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<!--解决页面提交数据乱码问题 -->
<uriEncoding>UTF-8</uriEncoding>
<!-- tomcat插件的请求端口 -->
<port>8080</port>
<!-- 项目的请求路径 -->
<path>/bjsxt</path>
</configuration>
</plugin>
<!-- 指定当前项目的jdk版本 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<!-- 指定source和target的版本 -->
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
5,创建User相关
5.1,User
public class User {
private Integer userid;
private String username;
private String userpwd;
private String sex;
private String address;
get set方法省略
}
5.2,UserMapper
public interface UserMapper {
/**
* 根据用户登陆名 查询用户对象
*/
User queryUserByUserName(@Param("username")String username);
}
5.3,UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sxt.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.sxt.domain.User">
<id column="userid" jdbcType="INTEGER" property="userid" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="userpwd" jdbcType="VARCHAR" property="userpwd" />
<result column="sex" jdbcType="VARCHAR" property="sex" />
<result column="address" jdbcType="VARCHAR" property="address" />
</resultMap>
<sql id="Base_Column_List">
userid, username, userpwd, sex, address
</sql>
<!-- 根据用户登陆名 查询用户对象 -->
<select id="queryUserByUserName" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where username = #{username}
</select>
</mapper>
5.4,UserService
public interface UserService {
/**
* 根据用户名查询用户
*/
public User queryUserByUserName(String username);
}
5.5,UserServiceImpl
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User queryUserByUserName(String username) {
return userMapper.queryUserByUserName(username);
}
}
5.6,UserController【测试用】
@RestController
@RequestMapping("user")
public class UserController {
@RequestMapping("query")
public Map<String,Object> query(){
Map<String,Object> map=new HashMap<>();
map.put("msg", "query");
return map;
}
@RequestMapping("add")
public Map<String,Object> add(){
Map<String,Object> map=new HashMap<>();
map.put("msg", "add");
return map;
}
@RequestMapping("update")
public Map<String,Object> update(){
Map<String,Object> map=new HashMap<>();
map.put("msg", "update");
return map;
}
@RequestMapping("delete")
public Map<String,Object> delete(){
Map<String,Object> map=new HashMap<>();
map.put("msg", "delete");
return map;
}
@RequestMapping("export")
public Map<String,Object> export(){
Map<String,Object> map=new HashMap<>();
map.put("msg", "export");
return map;
}
}
6,创建Role相关
6.1,Role
public class Role {
private Integer roleid;
private String rolename;
//get set方法省略
}
6.2,RoleMapper
public interface RoleMapper {
/**
* 根据用户ID查询用户角色
*/
List<Role> queryRolesByUserId(Integer userid);
}
6.3,RoleMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sxt.mapper.RoleMapper">
<resultMap id="BaseResultMap" type="com.sxt.domain.Role">
<id column="roleid" jdbcType="INTEGER" property="roleid" />
<result column="rolename" jdbcType="VARCHAR" property="rolename" />
</resultMap>
<!-- 根据用户ID查询用户角色 -->
<select id="queryRolesByUserId" resultMap="BaseResultMap">
select t1.* from role t1 inner join user_role t2
on(t1.roleid=t2.roleid) where t2.userid=#{value}
</select>
</mapper>
6.4,RoleService
public interface RoleService {
/**
* 根据用户ID查询角色名
*/
public List<String> queryRoleByUserId(Integer userid);
}
6.5,RoleServiceImpl
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleMapper roleMapper;
@Override
public List<String> queryRoleByUserId(Integer userid) {
List<Role> rolesList = roleMapper.queryRolesByUserId(userid);
List<String> roles=new ArrayList<String>();
for (Role role : rolesList) {
roles.add(role.getRolename());
}
return roles;
}
}
7,创建Permission相关
7.1,Permission
public class Permission {
private Integer perid;
private String pername;
private String percode;
}
7.2,PermissionMapper
public interface PermissionMapper {
/**
* 根据用户ID查询权限
*/
List<Permission> queryPermssionByUserId(Integer userid);
}
7.3,PermissionMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sxt.mapper.PermissionMapper">
<!-- 根据用户ID查询权限 -->
<select id="queryPermssionByUserId" resultMap="BaseResultMap">
select t1.* from permission t1 inner join role_permission t2 inner join
user_role t3
on(t1.perid=t2.perid and t2.roleid=t3.roleid) where t3.userid=#{value}
</select>
</mapper>
7.4,PermissionService
public interface PermissionService {
/**
* 根据用户ID查询权限
*/
public List<String> queryPermissionByUserId(Integer userid);
}
7.5,PermissionServiceImpl
@Service
public class PermissionServiceImpl implements PermissionService {
@Autowired
private PermissionMapper permissionMapper;
@Override
public List<String> queryPermissionByUserId(Integer userid) {
List<Permission> permissionList = permissionMapper.queryPermssionByUserId(userid);
List<String> permissions=new ArrayList<>();
for (Permission permission : permissionList) {
permissions.add(permission.getPercode());
}
return permissions;
}
}
8,创建ActiverUser
public class ActiverUser {
private User user;
private List<String> roles;
private List<String> permissions;
//get set方法省略
}
9,修改UserRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private PermissionService permissinService;
/**
* 认证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = token.getPrincipal().toString();
// 根据用户名查询用户对象
User user = this.userService.queryUserByUserName(username);
if (null != user) {
ActiverUser activerUser = new ActiverUser();
// 查询角色
activerUser.setRoles(this.roleService.queryRoleByUserId(user.getUserid()));
// 查询权限
activerUser.setPermissions(this.permissinService.queryPermissionByUserId(user.getUserid()));
ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUsername() + user.getAddress());
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activerUser, user.getUserpwd(),
credentialsSalt, getName());
return info;
}
return null;
}
/**
* 授权
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
ActiverUser activerUser=(ActiverUser) principals.getPrimaryPrincipal();
List<String> roles = activerUser.getRoles();
List<String> permissions = activerUser.getPermissions();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
if(null!=roles&& roles.size()>0) {
info.addRoles(roles);
}
if(null!=permissions&&permissions.size()>0) {
info.addStringPermissions(permissions);
}
return info;
}
}
10,搭建ssm环境
10.1,创建db.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/shiro?useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
10.2,创建log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
10.3,创建application-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 引入db.properties -->
<context:property-placeholder location="classpath:db.properties" system-properties-mode="FALLBACK"/>
<!-- 使用druid的数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init">
<!-- 注入连接属性 -->
<property name="driverClassName" value="${driverClassName}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${username}"></property>
<property name="password" value="${password}"></property>
<!-- 设置初始化连接池大小 -->
<property name="initialSize" value="5"></property>
<!-- 最大连接数 -->
<property name="maxActive" value="10"></property>
<!-- 设置等待时间 -->
<property name="maxWait" value="5000"></property>
<property name="filters" value="stat"></property>
</bean>
<!-- 声明sessionFactory 并注入mybatis.cfg.xml-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 注入mapper.xml -->
<property name="mapperLocations">
<array>
<value>classpath:mapper/*Mapper.xml</value>
</array>
</property>
<!-- 插件 -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor"></bean>
</array>
</property>
</bean>
<!-- 扫描mapper接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入mapper接口所在的包 注意多个包的情况的配置-->
<property name="basePackage" >
<value>
com.sxt.mapper
</value>
</property>
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
</beans>
10.4,创建application-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.sxt.service.impl"></context:component-scan>
<!-- 1,声明事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 启动注解事务 -->
<!-- <tx:annotation-driven/> -->
<!-- 2,声明事务的传播特性 也就是通知 -->
<tx:advice id="advise" transaction-manager="transactionManager">
<tx:attributes>
<!-- 以add开头的方法名需要事务 -->
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="change*" propagation="REQUIRED"/>
<tx:method name="reset*" propagation="REQUIRED"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="load*" read-only="true"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 3进行AOP织入 -->
<aop:config>
<!-- 声明切面 -->
<aop:pointcut expression="execution(* com.sxt.service.impl.*.*(..))" id="pc1"/>
<!-- 织入 -->
<aop:advisor advice-ref="advise" pointcut-ref="pc1"/>
</aop:config>
</beans>
10.5,创建applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="classpath:application-dao.xml"/>
<import resource="classpath:application-service.xml"/>
</beans>
10.6,创建springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描controller -->
<context:component-scan
base-package="com.sxt.controller"></context:component-scan>
<!-- 配置映射器和适配器 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 配置前视图解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 注入前后缀 -->
<property name="prefix" value="/WEB-INF/view/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置静态文件放行 -->
<mvc:default-servlet-handler />
</beans>
10.7,配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>05_shiro_ssm</display-name>
<!-- 编码过滤器开始 -->
<filter>
<filter-name>EncodeingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodeingFilter</filter-name>
<servlet-name>springmvc</servlet-name>
</filter-mapping>
<!-- 编码过滤器结束 -->
<!-- 监听器开始 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 监听器结束 -->
<!-- 前端控制器开始 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<!-- 前端控制器结束 -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
11,集成shiro环境
11.1,修改web.xml
<!-- shrio过滤器开始 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>shiroFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<servlet-name>springmvc</servlet-name>
</filter-mapping>
<!-- shiro过滤器结束 -->
11.2,创建application-shiro.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 声明凭证匹配器 -->
<bean id="credentialsMatcher"
class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!-- 注入算法 -->
<property name="hashAlgorithmName" value="md5"></property>
<!-- 注入散列次数 -->
<property name="hashIterations" value="2"></property>
</bean>
<!-- 声明realm -->
<bean id="userRealm" class="com.sxt.realms.UserRealm">
<!-- 注入凭证匹配器 -->
<property name="credentialsMatcher" ref="credentialsMatcher"></property>
</bean>
<!-- 创建安全管理器 -->
<bean id="securityManager"
class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!-- 注入realm -->
<property name="realm" ref="userRealm"></property>
</bean>
<!-- 配置过滤器链 -->
<!-- Shiro 的Web过滤器 id必须和web.xml里面的shiroFilter的 targetBeanName的值一样 -->
<bean id="shiroFilter"
class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全接口,这个属性是必须的 -->
<property name="securityManager" ref="securityManager" />
<!-- 要求登录时的链接(登录页面地址),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->
<property name="loginUrl" value="/index.jsp" />
<!-- 登录成功后要跳转的连接(本例中此属性用不到,因为登录成功后的处理逻辑在UserController里硬编码) -->
<!-- <property name="successUrl" value="/success.action"/> -->
<!-- 用户访问未对其授权的资源时,所显示的连接 -->
<property name="unauthorizedUrl" value="/unauthorized.jsp" />
<!-- 过虑器链定义,从上向下顺序执行,一般将/**放在最下边 -->
<property name="filterChainDefinitions">
<value>
<!-- /** = authc 所有url都必须认证通过才可以访问 -->
/index.jsp*=anon
/login/toLogin*=anon
/login/login*=anon
<!-- 如果用户访问user/logout就使用Shiro注销session -->
/login/logout = logout
<!-- /** = anon所有url都不可以匿名访问 -->
<!-- /** = authc -->
<!-- /*/* = authc -->
<!-- /** = authc所有url都不可以匿名访问 必须放到最后面 -->
/** = authc
</value>
</property>
</bean>
</beans>
11.3,修改applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="classpath:application-dao.xml"/>
<import resource="classpath:application-service.xml"/>
<import resource="classpath:application-shiro.xml"/>
</beans>
12,创建webapp/index.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>
<jsp:forward page="login/toLogin.action"></jsp:forward>
</body>
</html>
13,创建webapp/WEB-INF/view/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>用户登陆</title>
</head>
<body>
<h1 align="center">用户登陆</h1>
<h6 style="color: red;">${error }</h6>
<form action="${ctx }/login/login.action" method="post">
<table align="center" width="50%" border="1" cellpadding="5" cellspacing="5">
<tr>
<td align="right">用户名:</td>
<td>
<input type="text" name="username">
</td>
</tr>
<tr>
<td align="right">用户名:</td>
<td>
<input type="password" name="userpwd">
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交">
</td>
</tr>
</table>
</form>
</body>
</html>
14,创建webapp/WEB-INF/view/index.jspr
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags"%>
<!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>系统首页</title>
</head>
<body>
系统首页
<hr>
<shiro:hasPermission name="user:query">
<a href="${ctx }/user/query.action">查询用户</a>
<br>
</shiro:hasPermission>
<shiro:hasPermission name="user:add">
<a href="${ctx }/user/add.action">添加用户</a>
<br>
</shiro:hasPermission>
<shiro:hasPermission name="user:update">
<a href="${ctx }/user/update.action">修改用户</a>
<br>
</shiro:hasPermission>
<shiro:hasPermission name="user:delete">
<a href="${ctx }/user/delete.action">删除用户</a>
<br>
</shiro:hasPermission>
<shiro:hasPermission name="user:export">
<a href="${ctx }/user/export.action">导出用户</a>
<br>
</shiro:hasPermission>
</body>
</html>
15,创建LoginController
/**
* 登陆
* @author LJH
*/
@Controller
@RequestMapping("login")
public class LoginController {
@RequestMapping("toLogin")
public String toLogin() {
return "login";
}
@RequestMapping("login")
public String login(String username, String userpwd,HttpSession session,Model model) {
// 封装token
UsernamePasswordToken token = new UsernamePasswordToken(username, userpwd);
// 得到主体
Subject subject = SecurityUtils.getSubject();
// 调用主体的登陆方法
try {
subject.login(token);
System.out.println("登陆成功");
ActiverUser activerUser = (ActiverUser) subject.getPrincipal();
session.setAttribute("user", activerUser.getUser());
return "index";
} catch (IncorrectCredentialsException e) {
System.err.println("密码不正确");
model.addAttribute("error", "密码不正确");
} catch (UnknownAccountException e) {
System.err.println("用户名不存在");
model.addAttribute("error", "用户名不存在");
}
return "login";
}
}