1、项目概述
项目功能点:1)、分页 2)、数据校验:Jquery前端校验+JSR303后端校验 3)、ajax 4)、RESTful风格的URI
技术点:
1)、基础框架SSM
2)、数据库MySQL
3)、前端框架BootStrap
4)、项目构建工具Maven
5)、mybatis分页插件(使用PageHelper进行分页)
6)、mybatis-generator逆向工程进行mapper生成
2、环境搭建
第1步、构建一个maven工程,工程名称为SSM-CRUD
创建完成后,项目结构如下:
web.xml内容如下:
<?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_2_5.xsd"
id="WebApp_ID" version="2.5">
</web-app>
第2步、在pom.xml中引入相关的依赖jar包
spring+springmvc+mybatis+数据连接池+数据库驱动+其它jar包(jstl+servlet-api+junit等等)
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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ssm</groupId>
<artifactId>SSM-CRUD</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<webVersion>3.0</webVersion>
<spring.version>4.3.3.RELEASE</spring.version>
<mybatis.version>3.4.2</mybatis.version>
</properties>
<dependencies>
<!-- spring相关jar包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring切面spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring-test -->
<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>
<!-- 引入MBG -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<!-- spring整合mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
<!-- jstl(和c3p0一样,是jstl>jstl下的),
servlet-api(请注意正确引入),
junit -->
<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/taglibs/standard -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<!-- <dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency> -->
<!-- 因为sprngTest要求更高版本的servlet,我们将其替换为3.0以上的版本 -->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- <dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
-->
<!-- jsp依赖 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 引入jackson的包 -->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
<!-- 后端校验JSR303的实现——hibernate-validator依赖
如果是tomcat7以下的服务器,需要额外给服务器的Lib包中替换新的EL
-->
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
第3步、引入bootstrap
下载bootstrap,然后在webapp下新建文件夹static,将bootstrap拷贝到static文件夹下,引入后如下图结构
在页面中引入bootstrap相关的css和js,就可以使用bootstrap,引入如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<link href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<!-- 先引入jQuery,再引入js-->
<script type="text/javascript" src="static/bootstrap-3.3.7-dist/js/jquery.min.js"> </script>
<script src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
This is my JSP page. <br>
</body>
</html>
第4步、配置文件
1)、web.xml配置文件
主要配置spring文件的路径和监听器用来启动spring容器;配置springmvc的前端控制器,用来拦截请求;配置springmvc的字符编码过滤器;配置HiddenHttpMethodFilter,用来处理restful风格的请求。
配置文件如下:
<?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_2_5.xsd"
id="WebApp_ID" version="2.5">
<!-- 1.启动spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 2.配置springMvc前端控制器 -->
<servlet>
<servlet-name>dispatcherServlet</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>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 3.springMvc字符编码过滤器,在所有的过滤器之前 -->
<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>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 4.配置hiddenHttpMethodFilter过滤器,处理restful风格的请求 -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
注:spring的前端控制器可以配置自定义的或者默认的。
方式1、默认的
默认的位置与web.xml同级,即放在WEB-INF下;默认的命名为${servlet-name}-Servlet.xml。如上面的<servlet-name>为dispatchServlet,那么必须在WEB-INF下springmvc的配置文件为dispatchServlet-Servlet.xml
方式2、自定义的
可以通过init-param进行初始化位置的定义,如上自定义的配置文件为spring-mvc.xml
url可以配置*.do或*.action,所有请求的url扩展名为*.do或*.action由springmvc解析,此种方法常用。但是不可以将url设置为/*,因为这样设置会将返回的jsp也交给springmvc解析。
2)、spring配置文件:applicationContext.xml
主要配置:配置扫描包;配置数据源;配置与mybatis的整合(全局配置文件引入,mapper配置文件引入,mapper接口实现扫描,加入ioc容器等);事务控制。
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 扫描包 -->
<context:component-scan base-package="com.cn">
<!-- 不扫描controller组件,其它都扫描 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 数据源配置 -->
<!-- 1、加载db.properties配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" />
<property name="driverClass" value="${jdbc.driver}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 配置和mybatis的整合 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 配置mybatis全局配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml" />
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource" />
<!-- 配置mapper文件位置 -->
<property name="mapperLocations" value="classpath:mapper/*.xml" />
</bean>
<!-- 配置扫描包,将mapper接口实现加入到IOC容器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描所有dao接口的实现 -->
<property name="basePackage" value="com.cn.dao" />
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源的开启关闭回滚 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 开启基于注解的事务,必要的都使用配置实现 -->
<aop:config>
<!-- 配置切入点,在service层控制事务, ..表示即使有子包也可以扫描 -->
<aop:pointcut expression="execution(* com.cn.service..*(..))" id="txPoint"/>
<!-- 配置事务增强 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint" />
</aop:config>
<tx:advice transaction-manager="transactionManager" id="txAdvice">
<tx:attributes>
<!-- 所有的方法都是事务 -->
<tx:method name="*" />
<!-- 所有get开头的方法都是可读的事务 -->
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>
</beans>
3)、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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
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-4.3.xsd">
<!-- 配置包扫描 -->
<context:component-scan base-package="com.cn" use-default-filters="false">
<!-- 配置只扫描@Controller注解 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置注解驱动(处理器适配器和映射) -->
<mvc:annotation-driven />
<!-- 配置静态资源访问 -->
<mvc:default-servlet-handler />
</beans>
4)、配置mybatis配置文件:mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!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>
<typeAliases>
<!-- 为类起别名 -->
<package name="com.cn.pojo"/>
</typeAliases>
</configuration>
5)、配置mybatis的自动生成代码mybatis generator
第1步、首先在maven中引入mybatis-generator-core依赖
<!-- 引入MBG -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
第2步、逆向工程配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 配置不生产注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 配置数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm"
userId="root"
password="root">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 指定javaBean生成的 位置 -->
<javaModelGenerator targetPackage="com.cn.bean"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 指定SQL映射文件的生成位置 -->
<sqlMapGenerator targetPackage="mapper"
targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 指定dao接口生成位置,即为mapper接口的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.cn.dao"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 指定每 表的生成策略 -->
<table tableName="t_emp" domainObjectName="Employee" ></table>
<table tableName="t_dept" domainObjectName="Department" ></table>
</context>
</generatorConfiguration>
第3步、测试生成代码
package com.cn.test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
public class MBGTest {
public static void main(String[] args) throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("E:\\workplace6\\SSM-CRUD\\src\\main\\resources\\mybatisGenerator.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
}
生成后的代码结构如下:多了6个java类和2个mapper.xml配置文件
第4步、测试
package com.cn.test;
/**
* dao层测试
* */
import java.util.UUID;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.cn.bean.Department;
import com.cn.bean.Employee;
import com.cn.dao.DepartmentMapper;
import com.cn.dao.EmployeeMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class DaoTest{
@Autowired
private DepartmentMapper deptMapper;
@Autowired
private EmployeeMapper employeeMapper;
@Autowired
private SqlSession sqlSession;
@Test
public void test(){
//插入部门
//deptMapper.insertSelective(new Department(9,"宣传部"));
//员工插入
//employeeMapper.insertSelective(new Employee(null,"Chrisy","F","chrisy@163.com",2));
//批量插入员工
EmployeeMapper empMapper=sqlSession.getMapper(EmployeeMapper.class);
for(int i=0;i<500;i++){
String gender=i%2==0?"M":"F";
String uid=UUID.randomUUID().toString().substring(0,5);
empMapper.insertSelective(new Employee(null,uid,gender,uid+"163.com",2));
}
}
}
至此,我们的配置文件都完成了****************************************************************************************************************