Maven下spring springmvc mybatis shiro 整合
最近新换了一台机器,这次主要框架使用Spring+SpringMVC+Mybatis+Shiro。项目持久层使用Mybatis3.3.0,控制层使用SpringMVC4.3.6,使用Spring4.3.6管理控制器,使用Shiro1.2.4权限管理器,数据库连接池使用druid数据源,
该项数据库暂使用MySQL5.6。环境是win10 64位 jdk1.8 tomcat8.5 Maven 3.5
2、修改pom.xml添加对应的包依赖
这儿将全部使用的Maven依赖贴出了,对应什么作用上面都有解释,如下:pom.xml
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 <groupId>com.peng</groupId> 5 <artifactId>ssms</artifactId> 6 <packaging>war</packaging> 7 <version>0.0.1-SNAPSHOT</version> 8 <name>ssms Maven Webapp</name> 9 <url>http://maven.apache.org</url> 10 <properties> 11 <spring.version>4.3.6.RELEASE</spring.version> 12 <mysql.version>5.1.10</mysql.version> 13 <druid.version>1.0.12</druid.version> 14 <log4j.version>1.2.17</log4j.version> 15 <mybatis.version>3.3.0</mybatis.version> 16 <shiro.version>1.2.4</shiro.version> 17 <jstl.version>1.2</jstl.version> 18 </properties> 19 <dependencies> 20 <!-- spring --> 21 <dependency> 22 <groupId>org.springframework</groupId> 23 <artifactId>spring-context</artifactId> 24 <version>${spring.version}</version> 25 </dependency> 26 <!-- 事务 --> 27 <dependency> 28 <groupId>org.springframework</groupId> 29 <artifactId>spring-tx</artifactId> 30 <version>${spring.version}</version> 31 </dependency> 32 <dependency> 33 <groupId>org.springframework</groupId> 34 <artifactId>spring-jdbc</artifactId> 35 <version>${spring.version}</version> 36 </dependency> 37 <dependency> 38 <groupId>org.springframework</groupId> 39 <artifactId>spring-web</artifactId> 40 <version>${spring.version}</version> 41 </dependency> 42 <dependency> 43 <groupId>org.springframework</groupId> 44 <artifactId>spring-webmvc</artifactId> 45 <version>${spring.version}</version> 46 </dependency> 47 <!-- 数据库驱动 mysql driver --> 48 <dependency> 49 <groupId>mysql</groupId> 50 <artifactId>mysql-connector-java</artifactId> 51 <version>${mysql.version}</version> 52 </dependency> 53 <!-- druid --> 54 <dependency> 55 <groupId>com.alibaba</groupId> 56 <artifactId>druid</artifactId> 57 <version>${druid.version}</version> 58 </dependency> 59 <!-- 日志 --> 60 <dependency> 61 <groupId>log4j</groupId> 62 <artifactId>log4j</artifactId> 63 <version>${log4j.version}</version> 64 </dependency> 65 <!-- mybatis --> 66 <dependency> 67 <groupId>org.mybatis</groupId> 68 <artifactId>mybatis</artifactId> 69 <version>${mybatis.version}</version> 70 </dependency> 71 <dependency> 72 <groupId>org.mybatis</groupId> 73 <artifactId>mybatis-spring</artifactId> 74 <version>1.2.3</version> 75 </dependency> 76 <!-- shiro --> 77 <dependency> 78 <groupId>org.apache.shiro</groupId> 79 <artifactId>shiro-core</artifactId> 80 <version>${shiro.version}</version> 81 </dependency> 82 <dependency> 83 <groupId>org.apache.shiro</groupId> 84 <artifactId>shiro-ehcache</artifactId> 85 <version>${shiro.version}</version> 86 </dependency> 87 <dependency> 88 <groupId>org.apache.shiro</groupId> 89 <artifactId>shiro-web</artifactId> 90 <version>${shiro.version}</version> 91 </dependency> 92 <dependency> 93 <groupId>org.apache.shiro</groupId> 94 <artifactId>shiro-spring</artifactId> 95 <version>${shiro.version}</version> 96 </dependency> 97 <!-- 添加jtl支持 --> 98 <dependency> 99 <groupId>javax.servlet</groupId> 100 <artifactId>jstl</artifactId> 101 <version>${jstl.version}</version> 102 </dependency> 103 <!-- 添加Servlet支持 --> 104 <!-- <dependency> 105 <groupId>javax.servlet</groupId> 106 <artifactId>javax.servlet-api</artifactId> 107 <version>3.1.0</version> 108 </dependency> 109 <dependency> 110 <groupId>javax.servlet.jsp</groupId> 111 <artifactId>javax.servlet.jsp-api</artifactId> 112 <version>2.3.1</version> 113 </dependency> --> 114 <dependency> 115 <groupId>junit</groupId> 116 <artifactId>junit</artifactId> 117 <version>3.8.1</version> 118 <scope>test</scope> 119 </dependency> 120 </dependencies> 121 <build> 122 <finalName>ssms</finalName> 123 <!-- <plugins> 124 <plugin> 125 <groupId>org.apache.maven.plugins</groupId> 126 <artifactId>maven-compiler-plugin</artifactId> 127 <version>3.3.0</version> 128 <configuration> 129 <source>1.8</source> 130 <target>1.8</target> 131 </configuration> 132 </plugin> 133 </plugins> --> 134 </build> 135 </project>
3、引入Spring,Springmvc以及spring与mybatis集成并配置相关属性
在src/main/resources创建spring,springmvc的配置文件,这里创建了spring-mybatis.xml,spring-mvc.xml,信息如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context-4.3.xsd"> 9 10 <!-- 导入配置文件 --> 11 <context:property-placeholder location="classpath:jdbc.properties"/> 12 <!-- druid 数据源 --> 13 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> 14 <property name="url" value="${jdbc.url}"></property> 15 <property name="username" value="${jdbc.username}"></property> 16 <property name="password" value="${jdbc.password}"></property> 17 </bean> 18 <!-- 扫描mybatis 配置文件--> 19 <bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 20 <property name="dataSource" ref="dataSource" /> 21 <property name="mapperLocations" value="classpath:com/peng/entity/mapper/*.xml" /> 22 </bean> 23 <!-- 扫描Mapper 配置文件--> 24 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 25 <property name="basePackage" value="com.peng.mapper" /> 26 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> 27 </bean> 28 </beans>
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context-4.3.xsd"> 9 10 <!-- 使用spring组件扫描@controller --> 11 <context:component-scan base-package="com.peng.web.controller"/> 12 <!-- 通过annotation-driven可以替代下边的处理器映射器和适配器 --> 13 14 <!-- 自动注解 --> 15 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean> 16 <!-- 视图解析器 --> 17 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 18 <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> 19 <property name="prefix" value="/WEB-INF/jsp/" /> 20 <property name="suffix" value=".jsp" /> 21 </bean> 22 </beans>
4、引入Mybatis并配置数据连接池等信息
在src/main/resources创建配置连接池配置信息在jdbc.properties中,如下:
1 jdbc.driver=com.mysql.jdbc.Driver 2 jdbc.url=jdbc:mysql://localhost:3306/ssms?useUnicode=true&characterEncoding=UTF-8 3 jdbc.username=root 4 jdbc.password=root
5、引入日志配置log4j打印信息到后台
在src/main/resources创建log4j.properties,如下:
1 #定义LOG输出级别 2 log4j.rootLogger=INFO,Console,File 3 #定义日志输出目的地为控制台 4 log4j.appender.Console=org.apache.log4j.ConsoleAppender 5 log4j.appender.Console.Target=system.out 6 #可以灵活地指定日志输出格式,下面一行是指定具体的格式 %d [%t]%-5p [%c] - %m%n 7 log4j.appender.Console.layout = org.apache.log4j.PatternLayout 8 log4j.appender.Console.layout.ConversionPattern=[%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n 9 10 #文件大小到达指定尺寸的时候产生一个新的文件 11 log4j.appender.File = org.apache.log4j.RollingFileAppender 12 #指定输出目录 13 log4j.appender.File.File = d:/logs/ssms.log 14 #定义文件最大大小 15 log4j.appender.File.MaxFileSize = 10MB 16 # 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志 17 log4j.appender.File.Threshold = ALL 18 log4j.appender.File.layout = org.apache.log4j.PatternLayout 19 log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
6、web.xml 配置spring监听器,对springmvc的支持,shiro的filter 如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 5 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> 6 <display-name>ssms</display-name> 7 <welcome-file-list> 8 <welcome-file>index.html</welcome-file> 9 <welcome-file>index.htm</welcome-file> 10 <welcome-file>index.jsp</welcome-file> 11 <welcome-file>default.html</welcome-file> 12 <welcome-file>default.htm</welcome-file> 13 <welcome-file>default.jsp</welcome-file> 14 </welcome-file-list> 15 <!-- Spring监听器 --> 16 <context-param> 17 <param-name>contextConfigLocation</param-name> 18 <param-value>classpath:spring-shiro.xml,classpath:spring-mybatis.xml</param-value> 19 </context-param> 20 <listener> 21 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 22 </listener> 23 <!-- shiro的filter --> 24 <filter> 25 <filter-name>shiroFilter</filter-name> 26 <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 27 <init-param> 28 <param-name>targetFilterLifecycle</param-name> 29 <param-value>true</param-value> 30 </init-param> 31 <init-param> 32 <param-name>targetBeanName</param-name> 33 <param-value>shiroFilter</param-value> 34 </init-param> 35 </filter> 36 <filter-mapping> 37 <filter-name>shiroFilter</filter-name> 38 <url-pattern>/*</url-pattern> 39 </filter-mapping> 40 <!-- 添加对springmvc的支持 --> 41 <servlet> 42 <servlet-name>springmvc</servlet-name> 43 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 44 <init-param> 45 <param-name>contextConfigLocation</param-name> 46 <param-value>classpath:spring-mvc.xml</param-value> 47 </init-param> 48 <load-on-startup>1</load-on-startup> 49 <async-supported>true</async-supported> 50 </servlet> 51 <servlet-mapping> 52 <servlet-name>springmvc</servlet-name> 53 <url-pattern>/</url-pattern> 54 </servlet-mapping> 55 <!-- post乱码处理 --> 56 <filter> 57 <filter-name>CharacterEncodingFilter</filter-name> 58 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 59 <init-param> 60 <param-name>encoding</param-name> 61 <param-value>utf-8</param-value> 62 </init-param> 63 </filter> 64 <filter-mapping> 65 <filter-name>CharacterEncodingFilter</filter-name> 66 <url-pattern>/*</url-pattern> 67 </filter-mapping> 68 </web-app>
7、集成spring与shiro权限管理配置文件spring-shiro.xml
在src/main/resources创建spring-shiro.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context-4.3.xsd"> 9 10 <!-- 使用spring组件扫描@service --> 11 <context:component-scan base-package="com.peng.service"/> 12 <!-- 自定义域realm --> 13 <bean id="custom_Realm" class="com.peng.realm.CustomRealm"></bean> 14 <!-- 安全管理器 ref对象--> 15 <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> 16 <property name="realm" ref="custom_Realm"/> 17 </bean> 18 <!-- shiro filter --> 19 <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> 20 <!-- 安全管理器必须的 --> 21 <property name="securityManager" ref="securityManager"/> 22 <!-- 身份认证失败 认证提交的地址 --> 23 <property name="loginUrl" value="/index.jsp"/> 24 <!-- 权限认证失败 没有权限认证提交的地址 --> 25 <property name="unauthorizedUrl" value="/unauthorized.jsp"/> 26 <!-- Shiro连接约束配置,即过滤链的定义 --> 27 <property name="filterChainDefinitions"> 28 <value> 29 <!-- 对静态资源设置匿名访问 --> 30 /login = anon 31 <!-- /** = authc 所有url都必须认证通过才可以访问 --> 32 /admin* = authc 33 </value> 34 </property> 35 </bean> 36 <!-- Shiro生命周期处理器 --> 37 <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean> 38 <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> 39 <property name="securityManager" ref="securityManager"/> 40 </bean> 41 42 </beans>
8、自定义域realm
1 package com.peng.realm; 2 3 import org.apache.shiro.authc.AuthenticationException; 4 import org.apache.shiro.authc.AuthenticationInfo; 5 import org.apache.shiro.authc.AuthenticationToken; 6 import org.apache.shiro.authc.SimpleAuthenticationInfo; 7 import org.apache.shiro.authz.AuthorizationInfo; 8 import org.apache.shiro.authz.SimpleAuthorizationInfo; 9 import org.apache.shiro.realm.AuthorizingRealm; 10 import org.apache.shiro.subject.PrincipalCollection; 11 import org.slf4j.Logger; 12 import org.slf4j.LoggerFactory; 13 import org.springframework.beans.factory.annotation.Autowired; 14 15 import com.peng.entity.User; 16 import com.peng.service.UserService; 17 18 public class CustomRealm extends AuthorizingRealm{ 19 private static final Logger logger = LoggerFactory.getLogger(CustomRealm.class); 20 @Autowired 21 private UserService userService; 22 /** 23 * 用户授权认证 24 */ 25 @Override 26 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { 27 logger.info("======用户授权认证======"); 28 String userName = principalCollection.getPrimaryPrincipal().toString(); 29 SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); 30 simpleAuthorizationInfo.setRoles(userService.queryRolesByName(userName)); 31 return simpleAuthorizationInfo; 32 } 33 /** 34 * 用户登陆认证 35 */ 36 @Override 37 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { 38 logger.info("======用户登陆认证======"); 39 String userName = authenticationToken.getPrincipal().toString(); 40 User user = userService.queryUserByName(userName); 41 if (user!=null) { 42 AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), "peng"); 43 return authenticationInfo; 44 } 45 return null; 46 } 47 48 }
9、UserMapper以及UserMapper.xml相当于Dao层
UserMapper接口
1 public interface UserMapper { 2 public User queryUserByName(String userName); 3 public Set<String> queryRolesByName(String userName); 4 }
UserMapper.xml配置sql语句
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 4 5 <mapper namespace="com.peng.mapper.UserMapper"> 6 <select id="queryUserByName" resultType="com.peng.entity.User" parameterType="java.lang.String"> 7 SELECT id,userName,password FROM user WHERE userName=#{userName} 8 </select> 9 <select id="queryRolesByName" resultType="java.lang.String" parameterType="java.lang.String"> 10 SELECT name FROM role r,user_role ur,user u WHERE r.id = ur.roleId AND u.id = ur.userId AND u.userName=#{userName} 11 </select> 12 </mapper>
10、Service层 创建UserService
1 @Service("userService") 2 public class UserService { 3 @Autowired 4 private UserMapper userMapper; 5 6 public User queryUserByName(String userName){ 7 return userMapper.queryUserByName(userName); 8 } 9 public Set<String> queryRolesByName(String userName){ 10 return userMapper.queryRolesByName(userName); 11 } 12 }
10、Controller层 创建LoginController
1 @Controller 2 public class LoginController { 3 private static final Logger logger = LoggerFactory.getLogger(LoginController.class); 4 @Autowired 5 private UserService userService; 6 @RequestMapping("/login") 7 public String login(User user,Model model){ 8 Subject subject = SecurityUtils.getSubject(); 9 UsernamePasswordToken usernamePasswordToken = new 10 UsernamePasswordToken(user.getUserName(),user.getPassword()); 11 try { 12 subject.login(usernamePasswordToken); 13 logger.info("======登陆成功======="); 14 return "success"; 15 } catch (Exception e) { 16 logger.error("======登陆异常======="); 17 //model.addAttribute("msg", "用户名或者密码错误,登陆失败"); 18 e.printStackTrace(); 19 return "/i```` 20 dex"; 21 } 22 } 23 }
11、前段登陆界面测试
1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 2 <c:set var="ctx" value="${pageContext.request.contextPath}" /> 3 <%@ page language="java" contentType="text/html; charset=utf-8" 4 pageEncoding="utf-8"%> 5 <!DOCTYPE html> 6 <html> 7 <head> 8 <meta charset="utf-8" /> 9 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 10 <title>登录页面</title> 11 <link rel="stylesheet" href="${ctx}/static/css/reset.css" /> 12 <link rel="stylesheet" href="${ctx}/static/css/login.css" /> 13 <script type="text/javascript" src="${ctx}/static/js/jquery.min.js"></script> 14 <script type="text/javascript" src="${ctx}/static/js/login.js"></script> 15 </head> 16 <body> 17 <div class="page"> 18 <div class="loginwarrp"> 19 <div class="logo">管理员登陆</div> 20 <div class="login_form"> 21 <form id="Login" name="Login" method="post" onsubmit="" action="login"> 22 <li class="login-item"> 23 <span>用户名:</span> 24 <input type="text" id="username" name="userName" class="login_input" > 25 <span id="count-msg" class="error"></span> 26 </li> 27 <li class="login-item"> 28 <span>密 码:</span> 29 <input type="password" id="password" name="password" class="login_input" > 30 <span id="password-msg" class="error"></span> 31 </li> 32 <li class="login-sub"> 33 <input type="submit" name="Submit" value="登录" /> 34 <input type="reset" name="Reset" value="重置" /> 35 </li> 36 </form> 37 </div> 38 </div> 39 </div> 40 <script type="text/javascript"> 41 window.onload = function() { 42 var config = { 43 vx : 4, 44 vy : 4, 45 height : 2, 46 width : 2, 47 count : 100, 48 color : "121, 162, 185", 49 stroke : "100, 200, 180", 50 dist : 6000, 51 e_dist : 20000, 52 max_conn : 10 53 } 54 CanvasParticle(config); 55 } 56 </script> 57 <script type="text/javascript" src="${ctx}/sta` 58 ic/js/canvas-particle.js"></script> 59 </body> 60 </html>
12、tomcat启动不报错情况下
通过浏览器访问http://localhost:8080/ssms 如下
**最后注意:
1、Java Build Path 选“Libraries”,将JRE System Library改为安装的javase-1.8
2、Java Compile 中的JDK Compliance 中Compiler Compliance level 改为 1.8
3、Project Facets 中 将Dynamic Web Module 改为3.0及以上
,Java中的版本改为 1.8**