创建项目:

ssm整合
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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sxt</groupId>
	<artifactId>shiro-06-ssm</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<dependencies>
		<!-- Spring、SpringMVC依赖,会自动导入spring-context包 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>4.3.21.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.3.21.RELEASE</version>
		</dependency>
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.8.9</version>
		</dependency>
		<!-- Mybatis依赖 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.4.6</version>
		</dependency>
		<!-- Mybatis-Spring -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.3.2</version>
		</dependency>
		<!-- mysql驱动包 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.47</version>
		</dependency>
		<!-- 日志 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.25</version>
		</dependency>
		<!-- C3P0 -->
		<dependency>
			<groupId>com.mchange</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.5.3</version>
		</dependency>
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<!-- shiro相关的依赖 -->
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-spring</artifactId>
			<version>1.2.3</version>
		</dependency>
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-ehcache</artifactId>
			<version>1.2.3</version>
		</dependency>
	<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-core</artifactId>
	    <version>4.3.21.RELEASE</version>
	</dependency>
	
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-expression</artifactId>
		<version>4.3.21.RELEASE</version>
		<type>jar.lastUpdated</type>
	</dependency>
	</dependencies>
	<build>
		<plugins>
			<!-- tomcat插件 -->
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<version>2.2</version>
				<configuration>
					<!-- 端口号 -->
					<port>8082</port>
					<!-- /表示访问路径 省略项目名 -->
					<path>/</path>
					<!-- 设置编码方式 -->
					<uriEncoding>utf-8</uriEncoding>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

LoginController类:

package com.sxt.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sxt.service.UserService;

@Controller
public class LoginController {

	@Resource
	private UserService userService;
	
	/**
	 * 设定登录失败跳转的资源以及获取失败的信息
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/login.do")
	public String login(Model model, HttpServletRequest request){
		Object ex = request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		if(ex!=null){
			System.out.println(ex.toString()+"----------");
		}
		if(UnknownAccountException.class.getName().equals(ex)){
			System.out.println("----账号不正确----->");
			model.addAttribute("msg", "账号不正确");
		}else if(IncorrectCredentialsException.class.getName().equals(ex)){
			System.out.println("----密码不正确----->");
			model.addAttribute("msg", "密码不正确");
		}else{
			System.out.println("----其他错误----->");
			model.addAttribute("msg", "其他错误");
		}
		return "/login.jsp";
	}
}

UserMapper类:

package com.sxt.mapper;

import java.util.List;

import com.sxt.pojo.User;

public interface UserMapper {

	public List<User> query(String username);
}

UserMapper类:

<?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">
	<select id="query" resultType="user">
		select * from users where username=#{param1}
	</select>
</mapper>

User类:

package com.sxt.pojo;

public class User {

	private Integer id;
	
	private String username;
	
	private String password;
	
	private String salt;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getSalt() {
		return salt;
	}

	public void setSalt(String salt) {
		this.salt = salt;
	}
	
}

MyRealm类:

package com.sxt.realm;

import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.sxt.pojo.User;
import com.sxt.service.UserService;

/**
 * 自定义的Realm
 */
public class MyRealm extends AuthorizingRealm {

	@Resource
	private UserService userService;

	/**
	 * 认证方法
	 * 
	 * @param token
	 *            就是我们在测试代码中 定义的UsernamePasswordToken对象 有我们保存的需要验证的账号密码信息
	 */
	/**
	 * 授权方法
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return null;
	}

	/**
	 * 认证方法
	 * 
	 * @param token
	 *            就是我们在测试代码中 定义的UsernamePasswordToken对象 有我们保存的需要验证的账号密码信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// 获取账号信息
		String principal = (String) token.getPrincipal();
		// 正常逻辑此处应该根据账号去数据库中查询,此处我们默认账号为 root 密码123456
		// 验证账号
		List<User> list = userService.login(principal);
		User user = list.get(0);
		if (user == null) {
			return null;
		}
		// 获取密码
		String pwd = user.getPassword();
		// 获取盐值
		ByteSource bs = ByteSource.Util.bytes(user.getSalt());
		// 验证密码
		AuthenticationInfo info = new SimpleAuthenticationInfo(principal, pwd, bs, "myrealm");
		return info;
	}
}

UserService类:

package com.sxt.service;

import java.util.List;

import com.sxt.pojo.User;

public interface UserService {
	public List<User> login(String userName);
}

UserServiceImpl类:

package com.sxt.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.sxt.mapper.UserMapper;
import com.sxt.pojo.User;
import com.sxt.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	
	@Resource
	private UserMapper mapper;

	@Override
	public List<User> login(String userName) {
		return mapper.query(userName);
	}

}

配置文件:
ssm整合
applicationContext-base.xml

<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-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
	
	<!-- 关联数据属性文件 -->
	<context:property-placeholder location="classpath:db.properties"/>
	<!-- 开启扫描 -->
	<context:component-scan base-package="com.sxt.service.impl"/>

	<!-- 配置数据源 -->
	<bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource" >
		<property name="driverClass" value="${driver}"></property>
		<property name="jdbcUrl" value="${url}"></property>
		<property name="user" value="${names}"></property>
		<property name="password" value="${password}"></property>
	</bean>
	<!-- 整合mybatis -->
	<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactoryBean" >
		<!-- 关联数据源 -->
		<property name="dataSource" ref="dataSource"/>
		<!-- 关联mybatis的配置文件 -->
		<property name="configLocation" value="classpath:mybatis-config.xml"/>
		<!-- 添加别名设置 -->
		<property name="typeAliasesPackage" value="com.sxt.pojo"/>
	</bean>
	<!-- 配置扫描的路径 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" >
		<property name="basePackage" value="com.sxt.mapper"/>
	</bean>
</beans>

applicationContext-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-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
 
 	<!-- 定义凭证匹配器 -->
 	<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher" id="credentialsMatcher">
 		<!-- 配置散列算法 -->
 		<property name="hashAlgorithmName" value="md5"/>
 		<!-- 配置散列次数 -->
 		<property name="hashIterations" value="1024"/>
 	</bean>
 	
 	<!-- 注册自定义Realm -->
 	<bean class="com.sxt.realm.MyRealm" id="myRealm">
 		<!-- 配置凭证匹配器 -->
 		<property name="credentialsMatcher" ref="credentialsMatcher"/>
 	</bean>
 	
 	<!-- 注册SecurityManager -->
 	<bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
 		<!-- 配置自定义Realm -->
 		<property name="realm" ref="myRealm"/>
 	</bean>
 	
 	<!-- 注册ShiroFilterFactoryBean 注意id必须和web.xml中注册的targetBeanName的值一致 -->
 	<bean class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" id="shiro">
 		<!-- 注册SecurityManager -->
 		<property name="securityManager" ref="securityManager"/>
 		<!-- 登录地址 如果用户请求的的地址是 login.do 那么会对该地址认证-->
 		<property name="loginUrl" value="/login.do"/>
 		<!-- 登录成功的跳转地址 -->
 		<property name="successUrl" value="/user.jsp"/>
 		<!-- 访问未授权的页面跳转的地址 -->
 		<property name="unauthorizedUrl" value="/error.jsp"/>
 		<!-- 设置 过滤器链 -->
 		<property name="filterChainDefinitions">
 			<value>
 				<!--加载顺序从上往下。
 					authc需要认证
 					anon可以匿名访问的资源
 				 -->
 				/login.do=authc 	
 				/login.jsp=anon
 				/**=authc
 			</value>
 		</property>
 	</bean>
</beans>

db.properties

<?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-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
 
 	<!-- 定义凭证匹配器 -->
 	<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher" id="credentialsMatcher">
 		<!-- 配置散列算法 -->
 		<property name="hashAlgorithmName" value="md5"/>
 		<!-- 配置散列次数 -->
 		<property name="hashIterations" value="1024"/>
 	</bean>
 	
 	<!-- 注册自定义Realm -->
 	<bean class="com.sxt.realm.MyRealm" id="myRealm">
 		<!-- 配置凭证匹配器 -->
 		<property name="credentialsMatcher" ref="credentialsMatcher"/>
 	</bean>
 	
 	<!-- 注册SecurityManager -->
 	<bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
 		<!-- 配置自定义Realm -->
 		<property name="realm" ref="myRealm"/>
 	</bean>
 	
 	<!-- 注册ShiroFilterFactoryBean 注意id必须和web.xml中注册的targetBeanName的值一致 -->
 	<bean class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" id="shiro">
 		<!-- 注册SecurityManager -->
 		<property name="securityManager" ref="securityManager"/>
 		<!-- 登录地址 如果用户请求的的地址是 login.do 那么会对该地址认证-->
 		<property name="loginUrl" value="/login.do"/>
 		<!-- 登录成功的跳转地址 -->
 		<property name="successUrl" value="/user.jsp"/>
 		<!-- 访问未授权的页面跳转的地址 -->
 		<property name="unauthorizedUrl" value="/error.jsp"/>
 		<!-- 设置 过滤器链 -->
 		<property name="filterChainDefinitions">
 			<value>
 				<!--加载顺序从上往下。
 					authc需要认证
 					anon可以匿名访问的资源
 				 -->
 				/login.do=authc 	
 				/login.jsp=anon
 				/**=authc
 			</value>
 		</property>
 	</bean>
</beans>

log4j.properties

log4j.rootCategory=DEBUG, stdout , R
 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[QC] %p [%t] %C.%M(%L) | %m%n
 
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=C:\\Tomcat 5.5\\logs\\qc.log
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		 <!-- 开启延迟加载 -->
		<setting name="lazyLoadingEnabled" value="true"/>
		<setting name="aggressiveLazyLoading" value="false"/>
	</settings>
</configuration>

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-4.3.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-4.3.xsd">

	<!-- 开启扫描 -->
	<context:component-scan base-package="com.sxt.controller"
		use-default-filters="false">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

	<!-- 开启SpringMVC注解的方式 -->
	<mvc:annotation-driven>
		<!-- <mvc:message-converters> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"></bean> 
			</mvc:message-converters> -->
	</mvc:annotation-driven>

</beans>

相关文章: