采用SSM(注解+xml) 框架快速搭建Web 项目
- idea + maven 创建好web 项目的目录架构
idea + maven快速搭建web项目 - 设置数据库数据表
1、创建数据库test
create database test;
2、创建学生表
CREATE TABLE `student` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`last_name` varchar(255) DEFAULT NULL COMMENT '学生名字',
`sex` varchar(255) DEFAULT NULL COMMENT '学生性别',
PRIMARY KEY (`Id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COMMENT='一个学生表';
3、创建教师表
CREATE TABLE `student` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`last_name` varchar(255) DEFAULT NULL COMMENT '教师名字',
`age` int(11) DEFAULT NULL COMMENT '教师年龄',
PRIMARY KEY (`Id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COMMENT='一个教师表';
- 导入SSM 框架所需的所有依赖坐标信息
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- spring版本号 -->
<spring.version>4.2.5.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依赖 -->
<dependency>
<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-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>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<type>jar</type>
<scope>compile</scope>
</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>
</dependencies>
<build>
<finalName>SSM</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
- 配置web.xml 文件的信息
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- 配置Spring 的监听器,默认只是加WEB-INF 目录下的applicationContext.xml 文件-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 设置配置文件的路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 设置 SpringMVC 的前端控制器 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 加载SpringMVC 配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 启动服务器就创建该servlet -->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 设置要拦截的路径 -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 中文乱码问题 -->
<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>
- 配置SpringMVC 的全局配置文件信息——springmvc.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 开启注解扫描,只扫描Controller 注解 -->
<context:component-scan base-package="cn.zdxh.lcy">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<!-- 设置视图的前缀 -->
<property name="prefix" value="/WEB-INF/page/" />
<!-- 设置视图的后缀 -->
<property name="suffix" value=".jsp" />
</bean>
<!-- 过滤静态资源 -->
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/javascript/**" location="/javascript/" />
<!-- 开启SpringMVC 注解支持 -->
<mvc:annotation-driven />
</beans>
- 配置 Spring 的全局配置文件信息——applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" 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/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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 整合Spring 和 SpringMVC 框架-->
<!-- 开启注解扫描,希望只扫描service 和 dao 层,而controller 层不需要Spring 框架管理 -->
<context:component-scan base-package="cn.zdxh.lcy">
<!-- 配置不扫描哪些注解 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 整合Spring 和 Mybatis 框架-->
<!-- 配置数据库连接池(数据源) -->
<bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///test" />
<property name="user" value="root" />
<property name="password" value="123456" />
</bean>
<!-- 配置SQLSessionFactory 工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 把数据源放入容器中 -->
<property name="dataSource" ref="pooledDataSource" />
<!-- 指定mybatis全局配置文件的位置 -->
<property name="configLocation" value="classpath:mybatis-config.xml" />
<!-- 指定mybatis,mapper文件的位置 -->
<!--<property name="mapperLocations" value="classpath:mapper/*.xml"></property>-->
</bean>
<!-- 配置dao 接口包 -->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.zdxh.lcy.dao" />
<property name="SqlSessionFactoryBeanName" value="sqlSessionFactory" />
<property name="annotationClass" value="org.springframework.stereotype.Repository" />
</bean>
<!-- 配置一个可以执行批量的sqlSession -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
<constructor-arg name="executorType" value="BATCH"></constructor-arg>
</bean>
<!-- 配置Spring 框架声明式事务管理 -->
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="pooledDataSource" />
</bean>
<!-- 设置xml方式事务通知-->
<!--<tx:advice id="txAdvice" transaction-manager="transactionManager">-->
<!--<tx:attributes>-->
<!--<!– 设置以fing 开头的方法名为只读的事务行为 –>-->
<!--<tx:method name="find*" read-only="true"/>-->
<!--<!– 设置方法开启事务的隔离级别 –>-->
<!--<tx:method name="*" isolation="DEFAULT" />-->
<!--</tx:attributes>-->
<!--</tx:advice>-->
<!--<!– 配置AOP 增强 –>-->
<!--<aop:config>-->
<!--<!– execution()中的参数,(public)类型、(*)返回值、(cn.zdxh.lcy.service.*impl.*)方法的全路径、(..)方法的参数–>-->
<!--<aop:advisor advice-ref="txAdvice" pointcut="execution(public * cn.zdxh.lcy.service.*impl.*(..))" />-->
<!--</aop:config>-->
<!-- 设置注解方式事务管理 -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
- 配置 Mybatis 全局配置文件信息——mybatis-config.xml
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 开启驼峰命名法(可以解决表字段名和对象属性名不一致而映射不到问题) -->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!--<!– 环境配置 –>-->
<!--<environments default="mysql">-->
<!--<environment id="mysql">-->
<!--<transactionManager type="JDBC" />-->
<!--<dataSource type="POOLED">-->
<!--<property name="driver" value="com.mysql.jdbc.Driver"></property>-->
<!--<property name="url" value="jdbc:mysql:///test"></property>-->
<!--<property name="username" value="root"></property>-->
<!--<property name="password" value="123456"></property>-->
<!--</dataSource>-->
<!--</environment>-->
<!--</environments>-->
<!-- 配置信息 -->
<!--<typeAliases>-->
<!--<typeAlias type=""-->
<!--</typeAliases>-->
<!-- 引入映射配置文件 -->
<mappers>
<!-- 扫描该包下的所有文件 -->
<!--<package name="cn.zdxh.lcy.mapper"/>-->
<mapper resource="mapper/TeacherMapper.xml" />
</mappers>
</configuration>
- 为项目设置日志配置文件——log4j.properties
log4j.rootLogger=INFO,Console,File
#控制台日志
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%p][%t][%d{yyyy-MM-dd HH\:mm\:ss}][%C] - %m%n
#普通文件日志
log4j.appender.File=org.apache.log4j.RollingFileAppender
log4j.appender.File.File=logs/ssm.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][%t][%d{yyyy-MM-dd HH\:mm\:ss}][%C] - %m%n
- 设置model 层domain 实体类
/**
* 创建一个Student 的JavaBean
*/
public class Student implements Serializable {
private Integer id;
private String lastName;
private String sex;
public Student() {
}
public Student(String lastName, String sex) {
this.lastName = lastName;
this.sex = sex;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", lastName='" + lastName + '\'' +
", sex='" + sex + '\'' +
'}';
}
}
#################################################################################
public class Teacher {
private Integer id;
private String lastName;
private Integer age;
public Teacher() {
}
public Teacher(String name, Integer age) {
this.lastName = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Teacher{" +
"id=" + id +
", name='" + lastName + '\'' +
", age=" + age +
'}';
}
}
- 设置持久化dao 层接口
/**
* Student 的dao接口
*/
@Repository
public interface StudentMapper {
/**
* 查询全部Student 的方法
* @return
*/
@Select("select * from student")
public List<Student> findAll();
/**
* 添加Student 的方法
* @return
*/
@Insert("insert into student(last_name, sex) value(#{lastName}, #{sex})")
public int saveStudent(Student student);
/**
* 更新Student 的方法
* @return
*/
@Update("update student set last_name=#{lastName}, sex=#{sex} where id = #{id}")
public int updateStudent(Student student);
/**
* 删除Student 的方法
* @return
*/
@Delete("delete from student where id=#{id}")
public int deleteStudent(int id);
}
######################################################################################
/**
* 关联mapper/TeacherMapper.xml 文件
*/
@Repository
public interface TeacherMapper {
public List<Teacher> findAll();
public int addTeacher(Teacher teacher);
}
- 设置业务层service 接口与实现
/**
* service 层接口会自动映射关联dao 层接口
*/
public interface StudentService {
//一个查询全部Student 的方法
public List<Student> findAll();
//一个添加Student 的方法
public int saveStudent(Student student);
//一个更新Student 的方法
public int updateStudent(Student student);
//一个删除Student 的方法
public int deleteStudent(int id);
}
===============================================================================
/**
* Student 的接口实现类
*/
@Service("studentService")//给spring容器添加一个名为“studentService”组件
public class ImplStudentService implements StudentService {
@Autowired
private StudentMapper studentMapper;
//把这个类的执行信息打印到日志中
Logger logger = (Logger) Logger.getLogger(ImplStudentService.class);
//采用注解的方式设置事务的参数(传播性,隔离级别)
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public List<Student> findAll() {
List<Student> list = studentMapper.findAll();
System.out.println("Spring 管理service 层搭建成功!");
return list;
}
public int saveStudent(Student student) {
System.out.println("Spring 管理service 层搭建成功!");
return 0;
}
public int updateStudent(Student student) {
System.out.println("Spring 管理service 层搭建成功!");
return 0;
}
public int deleteStudent(int id) {
System.out.println("Spring 管理service 层搭建成功!");
return 0;
}
}
######################################################################################
public interface TeacherService {
public List<Teacher> findAll();
public int addTeacher(Teacher teacher);
}
========================================================================
@Service("teacherService")
public class ImplTeacherService implements TeacherService {
@Autowired
private TeacherMapper teacherMapper = null;
@Override
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public List<Teacher> findAll() {
return teacherMapper.findAll();
}
@Override
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public int addTeacher(Teacher teacher) {
teacherMapper.addTeacher(teacher);
return 0;
}
}
- 设置控制层controller 逻辑操作
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping("/findAll")
public String findAllStudent(Map<String, Object> map){
System.out.println("成功配置完成SpringMVC 框架!");
List<Student> list = studentService.findAll();
map.put("success", "欢迎来到SpringMVC 的框架");
map.put("students", list);
return "success";
}
}
###############################################################################
@Controller
@RequestMapping("/teacher")
public class TeacherController {
@Autowired
private TeacherService teacherService;
@RequestMapping("/findAll")
public String findAll(Map<String, Object> map){
List<Teacher> list = teacherService.findAll();
map.put("teacher", "恭喜您SSM框架整合成功!");
map.put("teachers", list);
return "success";
}
}
- 设置响应视图page
###index.jsp
<html>
<body>
<h2>Hello World!</h2>
<a href="/student/findAll">student</a><br />
<a href="/teacher/findAll">teacher</a>
</body>
</html>
######################################################################
####success.jsp
<!DOCTYPE html>
<html lang="en">
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>${student}</h1>
<table border="1">
<tr>
<td>学生ID</td>
<td>学生名字</td>
<td>学生性别</td>
</tr>
<c:forEach items="${students}" var="student">
<tr>
<td>${student.id}</td>
<td>${student.lastName}</td>
<td>${student.sex}</td>
</tr>
</c:forEach>
</table>
<h1>${teacher}</h1>
<table border="1">
<tr>
<td>教师ID</td>
<td>教师名字</td>
<td>教师年龄</td>
</tr>
<c:forEach items="${teachers}" var="teacher">
<tr>
<td>${teacher.id}</td>
<td>${teacher.lastName}</td>
<td>${teacher.age}</td>
</tr>
</c:forEach>
</table>
<br>
<a href="/index.jsp">返回</a>
</body>
</html>
好了到这里SSM 框架的整合就已经完成了。