Maven搭建Spring+SpringMVC+Mybatis+Shiro项目详解
一. 环境搭建:
1. 开发工具:myeclipse 2014 / IDEA;
2. maven管理版本:apache-maven-3.0+;
3. jdk 1.7.0+
4. Tomcat8.0
二:工程搭建:
1、修改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.peng</groupId>
<artifactId>ssms</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>ssms Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>4.3.6.RELEASE</spring.version>
<mysql.version>5.1.10</mysql.version>
<druid.version>1.0.12</druid.version>
<log4j.version>1.2.17</log4j.version>
<mybatis.version>3.3.0</mybatis.version>
<shiro.version>1.2.4</shiro.version>
<jstl.version>1.2</jstl.version>
</properties>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 事务 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 数据库驱动 mysql driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.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>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</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-ehcache</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</version>
</dependency>
<!-- 添加jtl支持 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- 添加Servlet支持 -->
<!-- <dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency> -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>ssms</finalName>
<!-- <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins> -->
</build>
</project>
2.引入Spring,Springmvc以及spring与mybatis集成并配置相关属性
在src/main/resources创建spring,springmvc的配置文件,这里创建了spring-mybatis.xml,spring-mvc.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 导入配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- druid 数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 扫描mybatis 配置文件-->
<bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:com/peng/entity/mapper/*.xml" />
</bean>
<!-- 扫描Mapper 配置文件-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.peng.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</beans>
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 使用spring组件扫描@controller -->
<context:component-scan base-package="com.peng.web.controller"/>
<!-- 通过annotation-driven可以替代下边的处理器映射器和适配器 --> <!-- 自动注解 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
3.引入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
4.引入日志配置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
5.web.xml 配置spring监听器,对springmvc的支持,shiro的filter 如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ssms</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- Spring监听器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-shiro.xml,classpath:spring-mybatis.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- shiro的filter -->
<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>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 添加对springmvc的支持 -->
<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:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- post乱码处理 -->
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
6.集成spring与shiro权限管理配置文件spring-shiro.xml
在src/main/resources创建spring-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 使用spring组件扫描@service -->
<context:component-scan base-package="com.peng.service"/>
<!-- 自定义域realm -->
<bean id="custom_Realm" class="com.peng.realm.CustomRealm"></bean>
<!-- 安全管理器 ref对象-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="custom_Realm"/>
</bean>
<!-- shiro filter -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- 安全管理器必须的 -->
<property name="securityManager" ref="securityManager"/>
<!-- 身份认证失败 认证提交的地址 -->
<property name="loginUrl" value="/index.jsp"/>
<!-- 权限认证失败 没有权限认证提交的地址 -->
<property name="unauthorizedUrl" value="/unauthorized.jsp"/>
<!-- Shiro连接约束配置,即过滤链的定义 -->
<property name="filterChainDefinitions">
<value>
<!-- 对静态资源设置匿名访问 -->
/login = anon
<!-- /** = authc 所有url都必须认证通过才可以访问 -->
/admin* = authc
</value>
</property>
</bean>
<!-- Shiro生命周期处理器 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean> </beans>
7.自定义域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;
} }
8.、UserMapper以及UserMapper.xml相当于Dao层
UserMapper接口
public interface UserMapper {
public User queryUserByName(String userName);
public Set<String> queryRolesByName(String userName);
}
9.UserMapper.xml配置sql语句
<?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.peng.mapper.UserMapper">
<select id="queryUserByName" resultType="com.peng.entity.User" parameterType="java.lang.String">
SELECT id,userName,password FROM user WHERE userName=#{userName}
</select>
<select id="queryRolesByName" resultType="java.lang.String" parameterType="java.lang.String">
SELECT name FROM role r,user_role ur,user u WHERE r.id = ur.roleId AND u.id = ur.userId AND u.userName=#{userName}
</select>
</mapper>
10.Service层 创建UserService
@Service("userService")
public class UserService {
@Autowired
private UserMapper userMapper; public User queryUserByName(String userName){
return userMapper.queryUserByName(userName);
}
public Set<String> queryRolesByName(String userName){
return userMapper.queryRolesByName(userName);
}
}
11.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";
}
}
}
12.前段登陆界面测试
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录页面</title>
<link rel="stylesheet" href="${ctx}/static/css/reset.css" />
<link rel="stylesheet" href="${ctx}/static/css/login.css" />
<script type="text/javascript" src="${ctx}/static/js/jquery.min.js"></script>
<script type="text/javascript" src="${ctx}/static/js/login.js"></script>
</head>
<body>
<div class="page">
<div class="loginwarrp">
<div class="logo">管理员登陆</div>
<div class="login_form">
<form id="Login" name="Login" method="post" onsubmit="" action="login">
<li class="login-item">
<span>用户名:</span>
<input type="text" id="username" name="userName" class="login_input" >
<span id="count-msg" class="error"></span>
</li>
<li class="login-item">
<span>密 码:</span>
<input type="password" id="password" name="password" class="login_input" >
<span id="password-msg" class="error"></span>
</li>
<li class="login-sub">
<input type="submit" name="Submit" value="登录" />
<input type="reset" name="Reset" value="重置" />
</li>
</form>
</div>
</div>
</div>
<script type="text/javascript">
window.onload = function() {
var config = {
vx : 4,
vy : 4,
height : 2,
width : 2,
count : 100,
color : "121, 162, 185",
stroke : "100, 200, 180",
dist : 6000,
e_dist : 20000,
max_conn : 10
}
CanvasParticle(config);
}
</script>
<script type="text/javascript" src="${ctx}/sta`
ic/js/canvas-particle.js"></script>
</body>
</html>
12.tomcat启动不报错情况下
13.成功返回
转自:
https://blog.csdn.net/userrefister/article/details/72760424
https://blog.csdn.net/qq_30781315/article/details/71194591
Maven搭建Spring+SpringMVC+Mybatis+Shiro项目详解的更多相关文章
- IDEA中maven搭建Spring+SpringMVC+mybatis项目
一.介绍 使用IDEA搭建maven web项目,整合框架Spring+SpringMVC+mybatis 项目结构图:
- SpringMVC+MyBatis+Shiro 配置文件详解
1.web.xml文件的配置 <?xml version="1.0" encoding="UTF-8"?> <web-app version= ...
- 搭建Spring + SpringMVC + Mybatis框架之二(整合Spring和Mybatis)
整合Spring和Mybatis 首先给出完整的项目目录: (1)引入项目需要的jar包 使用http://maven.apache.org作为中央仓库即可. Spring核心包,mybatis核心包 ...
- Maven 搭建spring boot多模块项目(附源码),亲测可以,感谢原创
原创地址:https://segmentfault.com/a/1190000005020589 我的DEMO码云地址,持续添加新功能: https://gitee.com/itbase/Spring ...
- Maven 搭建spring boot多模块项目
Maven 搭建spring boot多模块项目 备注:所有项目都在idea中创建 1.idea创建maven项目 1-1: 删除src,target目录,只保留pom.xml 1-2: 根目录pom ...
- Maven配置Spring+SpringMVC+MyBatis(3.2.2)Pom 以及 IntelliJ IDEA 怎样打开依赖视图
Maven配置Spring+SpringMVC+MyBatis(3.2.2)Pom 配置原则: 利用依赖,将所需的jar包加载到project中. 先依赖主要jar包 Spring + Spring ...
- 使用maven整合spring+springmvc+mybatis
使用maven整合spring+springmvc+mybatis 开发环境: 1. jdk1.8 2. eclipse4.7.0 (Oxygen) 3. mysql 5.7 在pom.xml文件中, ...
- IntelliJ IDEA 14.0.3 实战搭建Spring+SpringMVC+MyBatis组合框架
简介 Spring+SpringMVC+MyBatis框架(SSM)是比较热门的中小型企业级项目开发的框架,对于新手来说也是比较容易学习入门的.虽说容易,但在框架搭建过程中仍然遇到了许多问题,因此用实 ...
- Spring+SpringMVC+Mybatis+Shiro环境搭建之IDEA下搭建Maven项目
运行IntelliJ IDEA 2016.3.2(64)编译器新建项目 在弹出的窗体中选择maven,然后勾选要建的maven模板--这里选webApp 然后填入相应的maven项目组信息(Gro ...
随机推荐
- django dynamic model
django model 首先对于一个习惯用django model的骚年来说,你肯定对django model自定制用的很熟悉,但突然让你用django dynamic model,也许会有很多人懵 ...
- 利用Chrome的Performance工具排查页面性能问题(原叫timeline)
当页面中发生卡顿,最先考虑的是swf文件造成的卡顿,经过排查发现不是swf造成的影响,利用Chrome的Performance工具发现页面中的一些元素不断在重新布局,造成潜在的性能瓶颈. 首先在Chr ...
- ./run.sh --indir examples/demo/ --outdir examples/results/ --vis
(AlphaPose20180911) luo@luo-ThinkPad-W540:AlphaPose$ ./run.sh --indir examples/demo/ --outdir exampl ...
- https://github.com/ildoonet/tf-pose-estimation
https://github.com/ildoonet/tf-pose-estimation
- EZOJ #202
传送门 分析 我们知道选一个点的代价就是他所有出边边权的异或和 由于一条边如果两个端点均选边权会异或两次变回0,所以不必担心重复的情况 于是直接跑线性基即可 代码 #include<bits/s ...
- HDU 5293 Tree chain problem
树状数组 + dp 设$f_i$表示以$i$为根的子树中的能选取的最大和,$sum_x$表示$\sum_{f_y}$ ($y$是$x$的一个儿子),这样子我们把所有给出的链按照两点的$lca$分组, ...
- jQuery 2.1.4版本的源码分析
jQuery 2.1.4版本的源码分析 jquery中获取元素的源码分析 jQuery.each({// 获取当前元素的父级元素 parent: function(elem) { var parent ...
- WIN XP蓝屏代码大全
转自:廊坊师范学院信息技术提高班---韩正阳 http://blog.csdn.net/jiudihanbing WIN XP蓝屏代码大全WIN XP蓝屏代码大全一.蓝屏含义 1.故障检查信息 *** ...
- BZOJ 2301 Problem b(莫比乌斯反演+分块优化)
Description 对于给出的n个询问,每次求有多少个数对(x,y),满足a≤x≤b,c≤y≤d,且gcd(x,y) = k,gcd(x,y)函数为x和y的最大公约数. Input 第一行一个整数 ...
- db2 中 SQL判断物理表是否存在、修改表名
1.db2 中 SQL判断物理表是否存在 SELECT * FROM SYSIBM.SYSTABLES WHERE TID <> 0 AND Name = 'TABLE_NAME' AND ...