SSM框架搭建图文教程(推荐)
好久就想着好好搭建一个ssm框架,自己以后用也方便吧,但是最近的事真的是很多,很多事情都没有去干,有时候自己会怀疑一下人生自己该不该去做程序员,我是一个没毕业的学生,找工作真的是四处碰壁,感觉自己好难混,一个暑假换了3个公司。我其实就想找一个公司能干自己想干的技术,能学到自己想学到的东西,可是我发现太难了,几乎没有这样的公司。所以说在你不是很牛逼的时候,人得适应公司,而不是公司适应你。第一个公司的一个老程序员和我去公司必须能吃上饭,能吃上饭再想其他的东西,而我是个90后,我明白我的性格,一遇到难题就想逃避,可是逃避是最不好的道路,也是不能走的道路。希望刚毕业的同学能找到一个适合自己的工作。
一、我用的是idea
二、首先创建一个maven项目,结构如下:
三、开始写配置文件
pom文件
<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.xxx.demo</groupId>
<artifactId>ssm</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>ssm Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- spring版本号 -->
<spring.version>4.2.6.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.8</mybatis.version>
<!-- mysql驱动版本号 -->
<mysql-driver.version>5.1.29</mysql-driver.version>
<!-- log4j日志包版本号 -->
<slf4j.version>1.7.18</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencies>
<!-- 添加jstl依赖 -->
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!-- 添加junit4依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<!-- 指定范围,在测试时才会加载 -->
<scope>test</scope>
</dependency>
<!-- 添加spring核心依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</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-oxm</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-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</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>1.2.2</version>
</dependency>
<!-- 添加mysql驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-driver.version}</version>
</dependency>
<!-- 添加数据库连接池依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.3</version>
</dependency>
<!-- 添加fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>
<!-- 添加日志相关jar包 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<!-- 映入JSON -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
</dependencies>
<build>
<finalName>ssm</finalName>
</build>
</project>
db.properties
db.Driver=com.mysql.jdbc.Driver
db.Url=jdbc:mysql://localhost:3306/myuser?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
db.username=root
db.password=xxxxxxxxxxxxx
#定义初始连接数
db.initialSize=1
#定义最大连接数
db.maxActive=20
#定义最大空闲
db.maxIdle=20
#定义最小空闲
db.minIdle=1
#定义最长等待时间
db.maxWait=60000
#使用非公平锁
db.useUnfairLock=true
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
db.timeBetweenEvictionRunsMillis=60000
#配置一个连接在池中最小生存的时间,单位是毫秒
db.minEvictableIdleTimeMillis=300000
db.validationQuery=SELECT 'x'
#申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
db.testWhileIdle=true
#申请连接时执行validationQuery检测连接是否有效
db.testOnBorrow=false
#归还连接时执行validationQuery检测连接是否有效
db.testOnReturn=false
#打开PSCache,并且指定每个连接上PSCache的大小
db.poolPreparedStatements=true
db.maxOpenPreparedStatements=20
#配置监控统计拦截的filters,去掉后监控界面sql无法统计
db.filters=start
log4j.properties
log4j.rootLogger=DEBUG,CONSOLE,FILEOUT
log4j.addivity.org.apache=true
# CONSOLE 打印到控制台
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=DEBUG
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH\:mm\:ss} \:%m%n
#
# FILEOUT 打印到 <span style="font-family: Arial, Helvetica, sans-serif;">D\:\\report.log</span>
log4j.appender.FILEOUT=org.apache.log4j.RollingFileAppender
log4j.appender.FILEOUT.File=D\:\\report.log
log4j.appender.FILEOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.fileout.MaxFileSize=100000KB
log4j.appender.FILEOUT.Append=true
#log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d \u2013 %c -%-4r [%t] %-5p %c %x \u2013 %m%n
log4j.appender.FILEOUT.layout.ConversionPattern=[%-5p]_%d{yyyy-MM-dd HH\:mm\:ss} \:%m%n
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.ssm.dao.UserDao">
<resultMap type="com.ssm.pojo.User" id="User">
<id column="id" property="id"/>
<result column="username" property="username" />
<result column="password" property="password"/>
</resultMap>
<select id="seleceUserById" parameterType="int" resultMap="User">
select * from t_user WHERE id=#{id}
</select>
</mapper>
sp-mybatis配置
<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--扫描数据库配置文件-->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!-- 第二种方式:加载多个properties文件
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:common.properties</value>
</list>
</property>
<property name="fileEncoding" value="UTF-8"/>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties"/>
</bean>
-->
<!--Druid配置数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${db.Driver}"></property>
<property name="url" value="${db.Url}"></property>
<property name="username" value="${db.username}"></property>
<property name="password" value="${db.password}"></property>
<property name="initialSize" value="${db.initialSize}"/><!-- 配置初始化连接池数量-->
<property name="minIdle" value="${db.minIdle}"/><!-- 配置最小连接池数量-->
<property name="maxActive" value="${db.maxActive}"/><!-- 配置最大连接池数量-->
<property name="maxWait" value="${db.maxWait}"/><!-- 配置获取连接等待超时的时间 单位毫秒-->
<property name="useUnfairLock" value="${db.useUnfairLock}"/><!--使用非公平锁-->
<property name="timeBetweenEvictionRunsMillis"
value="${db.timeBetweenEvictionRunsMillis}"/><!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis"
value="${db.minEvictableIdleTimeMillis}"/><!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="validationQuery" value="${db.validationQuery}"/><!--用来检测连接是否有效的sql,要求是一个查询语句。-->
<property name="testWhileIdle"
value="${db.testWhileIdle}"/><!--申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。-->
<property name="testOnBorrow" value="${db.testOnBorrow}"/><!--申请连接时执行validationQuery检测连接是否有效,-->
<property name="testOnReturn" value="${db.testOnReturn}"/><!--归还连接时执行validationQuery检测连接是否有效,-->
<property name="poolPreparedStatements"
value="${db.poolPreparedStatements}"/><!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="maxOpenPreparedStatements" value="${db.maxOpenPreparedStatements}"/>
<property name="filters" value="${db.filters}"/><!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 -->
</bean>
<!-- mybatis和spring完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
</beans>
sp-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"
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">
<context:component-scan base-package="com.ssm.service">
</context:component-scan>
</beans>
sp-trans.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:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 注解方式配置事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 拦截器方式配置事物 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--REQUIRED支持当前存在的事务,如果没有的话句创建一个新的事务
PROPAGATION_REQUIRED:支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。
SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行。
MANDATORY:支持当前事务,如果当前没有事务,就抛出异常。
REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。
NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。
NESTED:支持当前事务,如果当前事务存在,则执行一个嵌套事务(还不是太明白),如果当前没有事务,就新建一个事务。
-->
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="append*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="modify*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="repair" propagation="REQUIRED" />
<tx:method name="delAndRepair" propagation="REQUIRED" />
<tx:method name="get*" propagation="SUPPORTS" />
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="load*" propagation="SUPPORTS" />
<tx:method name="search*" propagation="SUPPORTS" />
<tx:method name="datagrid*" propagation="SUPPORTS" />
<tx:method name="*" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* com.ssm.service..*.*(..))" />
<aop:advisor pointcut-ref="transactionPointcut"
advice-ref="transactionAdvice" />
</aop:config>
<!-- 配置druid监控spring jdbc -->
<bean id="druid-stat-interceptor"
class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
</bean>
<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut"
scope="prototype">
<property name="patterns">
<list>
<value>com.ssm.service.*</value>
</list>
</property>
</bean>
<aop:config>
<aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
</aop:config>
</beans>
Springmvc配置
<?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/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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫描controller-->
<context:component-scan base-package="com.ssm.controller"></context:component-scan>
<!--mvc驱动-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsps"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 文件上传配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="UTF-8"/>
<!-- 上传文件大小限制为31M,31*1024*1024 -->
<property name="maxUploadSize" value="32505856"/>
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="4096"/>
</bean>
</beans>
web.xml配置
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/sp-*.xml</param-value>
</context-param>
<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--Spring溢出监听器
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>-->
<!--Spring监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置Servlet-->
<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/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--session配置-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
然后基本框架已经配置好了,剩下的就是写java代码了
Controller
package com.ssm.controller;
import com.ssm.pojo.User;
import com.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
/**
* @author: hsj
* @Date: 2017/9/15
* @Description :
*/
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Resource
private UserService userService;
@RequestMapping(value = "user")
@ResponseBody
public User getUser(int userId){
return userService.findUserById(userId);
}
}
Service
package com.ssm.service;
import com.ssm.pojo.User;
import org.springframework.stereotype.Service;
/**
* @author: hsj
* @Date: 2017/9/15
* @Description :
*/
public interface UserService {
User findUserById(int userId);
}
ServiceImpl
package com.ssm.service.impl;
import com.ssm.dao.UserDao;
import com.ssm.pojo.User;
import com.ssm.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author: hsj
* @Date: 2017/9/15
* @Description :
*/
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
public User findUserById(int userId) {
return userDao.seleceUserById(userId);
}
}
pojo
package com.ssm.pojo;
/**
* @author: hsj
* @Date: 2017/9/18
* @Description :这是一个User实体类
*/
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int 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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
dao
package com.ssm.dao;
import com.ssm.pojo.User;
import org.springframework.stereotype.Repository;
/**
* @author: hsj
* @Date: 2017/9/15
* @Description :
*/
@Repository
public interface UserDao {
User seleceUserById(int userId);
}
以上这篇SSM框架搭建图文教程(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
以上是 SSM框架搭建图文教程(推荐) 的全部内容, 来源链接: utcz.com/p/215787.html