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
1、数据库表结构以及maven项目结构
Maven搭建Spring+SpringMVC+Mybatis+Shiro项目详解(附上源码)_第1张图片
Maven搭建Spring+SpringMVC+Mybatis+Shiro项目详解(附上源码)_第2张图片

2、修改pom.xml添加对应的包依赖
这儿将全部使用的Maven依赖贴出了,对应什么作用上面都有解释,如下:pom.xml


  4.0.0
  com.peng
  ssms
  war
  0.0.1-SNAPSHOT
  ssms Maven Webapp
  http://maven.apache.org

  	4.3.6.RELEASE
  	5.1.10
  	1.0.12
  	1.2.17
  	3.3.0
  	1.2.4
  	1.2
  
  
  
  
      org.springframework
      spring-context
      ${spring.version}
    
    
     
      org.springframework
      spring-tx
      ${spring.version}
    
    
      org.springframework
      spring-jdbc
      ${spring.version}
    
    
      org.springframework
      spring-web
      ${spring.version}
    
    
      org.springframework
      spring-webmvc
      ${spring.version}
    
    
    
      mysql
      mysql-connector-java
      ${mysql.version}
    
    
    
      com.alibaba
      druid
      ${druid.version}
    
    
    
      log4j
      log4j
      ${log4j.version}
    
    
    
      org.mybatis
      mybatis
      ${mybatis.version}
    
    
      org.mybatis
      mybatis-spring
      1.2.3
    
    
    
      org.apache.shiro
      shiro-core
      ${shiro.version}
    
    
      org.apache.shiro
      shiro-ehcache
      ${shiro.version}
    
    
      org.apache.shiro
      shiro-web
      ${shiro.version}
    
    
      org.apache.shiro
      shiro-spring
      ${shiro.version}
    
    
    
      javax.servlet
      jstl
      ${jstl.version}
    
    
 
    
      junit
      junit
      3.8.1
      test
    
  
  
    ssms
    
  


3、引入Spring,Springmvc以及spring与mybatis集成并配置相关属性
在src/main/resources创建spring,springmvc的配置文件,这里创建了spring-mybatis.xml,spring-mvc.xml,信息如下:



		
	
		
	
	
		
		
		
	
	
	
		
		
	
	
	
		
		
	




	
	
	
	
	
	
	
	
		
		
		
	

4、引入Mybatis并配置数据连接池等信息
在src/main/resources创建配置连接池配置信息在jdbc.properties中,如下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssms?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root

5、引入日志配置log4j打印信息到后台
在src/main/resources创建log4j.properties,如下:

#定义LOG输出级别
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=system.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式 %d [%t]%-5p [%c] - %m%n
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = d:/logs/ssms.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

6、web.xml 配置spring监听器,对springmvc的支持,shiro的filter 如下:



  ssms
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
  
  
  		contextConfigLocation
  		classpath:spring-shiro.xml,classpath:spring-mybatis.xml
  
  
  	org.springframework.web.context.ContextLoaderListener
  
  
  
  	shiroFilter
  	org.springframework.web.filter.DelegatingFilterProxy
  	
  		targetFilterLifecycle
  		true
  	
  	
  		targetBeanName
  		shiroFilter
  	
  
  
  	shiroFilter
  	/*
  
  
 
  	springmvc
  	org.springframework.web.servlet.DispatcherServlet
  	
  		contextConfigLocation
  		classpath:spring-mvc.xml
  	
  	1
  	true
  
  
  	springmvc
  	/
   
  
  
  	CharacterEncodingFilter
  	org.springframework.web.filter.CharacterEncodingFilter
  	
  		encoding
  		utf-8
  	
  
  
  	CharacterEncodingFilter
  	/*
  

7、集成spring与shiro权限管理配置文件spring-shiro.xml
在src/main/resources创建spring-shiro.xml




	
	
	
	
	
	
		
	
	
	
		
		
		
		
		
		
		
		
			
				
				/login = anon
				
				/admin* = authc
			
		
	
	
	
	
		
	
	

8、自定义域realm

package com.peng.realm;

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.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.peng.entity.User;
import com.peng.service.UserService;

public class CustomRealm extends AuthorizingRealm{
	private static final Logger logger = LoggerFactory.getLogger(CustomRealm.class);
	@Autowired
	private UserService userService;
	/**
	 * 用户授权认证
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		logger.info("======用户授权认证======");
		String userName = principalCollection.getPrimaryPrincipal().toString();
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.setRoles(userService.queryRolesByName(userName));
		return simpleAuthorizationInfo;
	}
	/**
	 * 用户登陆认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		logger.info("======用户登陆认证======");
		String userName = authenticationToken.getPrincipal().toString();
		User user = userService.queryUserByName(userName);
		if (user!=null) {
			AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), "peng");
			return authenticationInfo;
		}
		return null;
	}

}

9、UserMapper以及UserMapper.xml相当于Dao层
UserMapper接口

public interface UserMapper {
	public User queryUserByName(String userName);
	public Set queryRolesByName(String userName);
}

UserMapper.xml配置sql语句



			

	
	

10、Service层 创建UserService

@Service("userService")
public class UserService {
	@Autowired
	private UserMapper userMapper;
	
	public User queryUserByName(String userName){
		return userMapper.queryUserByName(userName);
	}
	public Set queryRolesByName(String userName){
		return userMapper.queryRolesByName(userName);
	}
}

10、Controller层 创建LoginController

@Controller
public class LoginController {
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private UserService userService;
	@RequestMapping("/login")
	public String login(User user,Model model){
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken usernamePasswordToken = new 
				UsernamePasswordToken(user.getUserName(),user.getPassword());
		try {
			subject.login(usernamePasswordToken);
			logger.info("======登陆成功=======");
			return "success";
		} catch (Exception e) {
			logger.error("======登陆异常=======");
			//model.addAttribute("msg", "用户名或者密码错误,登陆失败");
			e.printStackTrace();
			return "/i````
dex";
		}
	}
}

11、前段登陆界面测试

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>



	
	
	登录页面
	
	
    
    


12、tomcat启动不报错情况下
Maven搭建Spring+SpringMVC+Mybatis+Shiro项目详解(附上源码)_第3张图片

通过浏览器访问http://localhost:8080/ssms 如下
Maven搭建Spring+SpringMVC+Mybatis+Shiro项目详解(附上源码)_第4张图片
Maven搭建Spring+SpringMVC+Mybatis+Shiro项目详解(附上源码)_第5张图片
Maven搭建Spring+SpringMVC+Mybatis+Shiro项目详解(附上源码)_第6张图片Maven搭建Spring+SpringMVC+Mybatis+Shiro项目详解(附上源码)_第7张图片
最后注意:
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

适合初学者,功能不完整

附上源码地址:https://github.com/412940226/ssms.git 默认用户密码admin/admin

你可能感兴趣的:(spring,shiro)