源码已经上传到github上传送门
过滤器配置
springMVC对json日期格式化
springMVC整合swagger
一:导包
pom.xml
<!-- 本人将配置包的版本信息都统一放入此处,方便以后管理 -->
<properties>
<springVersion>4.3.1.RELEASE</springVersion>
<hibernateVersion>4.3.5.Final</hibernateVersion>
<jstlVersion>1.2</jstlVersion>
<taglibVersion>1.1.2</taglibVersion>
<servletVersion>3.0-alpha-1</servletVersion>
<jsonVersion>1.9.13</jsonVersion>
<jacksonVersion>2.5.0</jacksonVersion>
<mysqlVersion>5.1.38</mysqlVersion>
<c3p0Version>0.9.1.2</c3p0Version>
<log4jVersion>1.2.17</log4jVersion>
<fileuploadVersion>1.3.1</fileuploadVersion>
<lombokVersion>1.16.10</lombokVersion>
</properties>
<dependencies>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.11</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.1_3</version>
</dependency>
<!-- spring web + spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springVersion}</version>
</dependency>
<!-- hibernate配置 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernateVersion}</version>
</dependency>
<!-- hibernate 缓存, 视情况添加 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernateVersion}</version>
</dependency>
<!-- jsp页面使用的jstl支持 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstlVersion}</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>${taglibVersion}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servletVersion}</version>
<scope>provided</scope>
</dependency>
<!-- DataBase数据库连接 mysql包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysqlVersion}</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0Version}</version>
</dependency>
<!-- json数据 使springMVC可以返回json值 ,视情况添加 -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${jsonVersion}</version>
</dependency>
<!-- Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jacksonVersion}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jacksonVersion}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jacksonVersion}</version>
</dependency>
<!-- log4j配置, 视情况添加 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4jVersion}</version>
</dependency>
<!--文件 上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${fileuploadVersion}</version>
</dependency>
<!-- lombok插件导包 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombokVersion}</version>
<scope>provided</scope>
</dependency>
二:spring和hibernate整合
dbconfig.properties
#database connection config
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc\:mysql\://localhost\:3306/ctc?useUnicode\=true&characterEncoding\=utf-8
jdbc.username = root
jdbc.password = 123456
#hibernate config
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto =update
spring-hibernate.xml
<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" 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-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
<!-- 自动扫描 -->
<context:component-scan base-package="com.ssh">
<!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!--********************************************配置hibernate******************************************** -->
<!--扫描配置文件(这里指向的是之前配置的那个config.properties) -->
<context:property-placeholder location="classpath:dbconfig.properties" />
<!--配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}" /> <!--数据库连接驱动 -->
<property name="jdbcUrl" value="${jdbc.url}" /> <!--数据库地址 -->
<property name="user" value="${jdbc.username}" /> <!--用户名 -->
<property name="password" value="${jdbc.password}" /> <!--密码 -->
<property name="maxPoolSize" value="40" /> <!--最大连接数 -->
<property name="minPoolSize" value="1" /> <!--最小连接数 -->
<property name="initialPoolSize" value="10" /> <!--初始化连接池内的数据库连接 -->
<property name="maxIdleTime" value="20" /> <!--最大空闲时间 -->
</bean>
<!--配置session工厂 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!--hibernate根据实体自动生成数据库表 -->
<prop key="hibernate.dialect">${hibernate.dialect}</prop> <!--指定数据库方言 -->
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <!--在控制台显示执行的数据库操作语句 -->
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <!--在控制台显示执行的数据哭操作语句(格式) -->
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext
</prop>
</props>
</property>
<!-- <property name="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</property> -->
<property name="packagesToScan">
<list>
<value>com.ssh.entity</value>
</list>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置事务管理器 -->
<bean name="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<aop:aspectj-autoproxy />
</beans>
Person.java
package com.ssh.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
//@Data
@Entity
@Table(name = "Person")
public class Person implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
// @Column(name = "created")
// private long created = System.currentTimeMillis();
@Column(name = "username")
private String username;
@Column(name = "address")
private String address;
@Column(name = "phone")
private String phone;
@Column(name = "remark")
private String remark;
@Column(name="mony")
private int mony;
public int getMony() {
return mony;
}
public void setMony(int mony) {
this.mony = mony;
}
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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Override
public String toString() {
return "Person [id=" + id + ", username=" + username + ", address=" + address + ", phone=" + phone + ", remark="
+ remark + ", mony=" + mony + "]";
}
}
BaseDao.java
package com.ssh.dao;
import java.util.List;
public interface BaseDao {
<T> void save(T entity);
<T> void delets(T entity);
<T> void update(T entity);
<T> T findById(int id);
<T> List<T> findAll();
<T> List<T> page(int first,int lenth);
}
BaseDaoImpl.java
package com.ssh.dao.impl;
import java.awt.print.Pageable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.ssh.dao.BaseDao;
public class BaseDaoImpl<T> implements BaseDao {
private Class<T> entityClass;
@Autowired
protected SessionFactory sessionFactory;
public BaseDaoImpl() {
Class<T> actualclass = (Class<T>) getClass();
ParameterizedType type = (ParameterizedType) actualclass.getGenericSuperclass();
Type[] types = type.getActualTypeArguments();
entityClass = (Class<T>) types[0];
}
public Session getSession() {
return this.sessionFactory.getCurrentSession();
}
public <T> void save(T entity) {
getSession().save(entity);
}
public <T> void delets(T entity) {
getSession().delete(entity);
}
public <T> void update(T entity) {
getSession().update(entity);
}
public <T> T findById(int id) {
return (T) getSession().get(entityClass, id);
}
public <T> List<T> findAll() {
return getSession().createQuery("from "+entityClass.getName()).list();
}
public <T> List<T> page(int first,int lenth) {
List<T> list = null;
try {
Query query = getSession().createQuery("from "+entityClass.getName());
query.setFirstResult(first);
query.setMaxResults(lenth);
list = query.list();
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
}
PersonDao.java
package com.ssh.dao;
public interface PersonDao extends BaseDao{
}
PersonDaoImpl.java
package com.ssh.dao.impl;
import org.springframework.stereotype.Repository;
import com.ssh.dao.PersonDao;
import com.ssh.entity.Person;
@Repository("personDao")
public class PersonDaoImpl extends BaseDaoImpl<Person> implements PersonDao {
}
PersonService.java
package com.ssh.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ssh.dao.PersonDao;
import com.ssh.entity.Person;
import com.ssh.page.Page;
@Service("personService")
@Transactional
public class PersonService {
@Autowired
private PersonDao personDao;
public void add(Person person) {
personDao.save(person);
}
public void remove(Person person){
personDao.delets(person);
}
public void update(Person person){
personDao.update(person);
}
public Person getByid(int id) {
return personDao.findById(id);
}
public List<Person> getAll() {
return personDao.findAll();
}
public List<Person> page(Page page){
return personDao.page(page.getFirst(), page.getLenth());
}
public PersonDao getPersonDao() {
return personDao;
}
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
}
测试spring和hibernate是否整合成功
package com.ssh.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ssh.entity.Person;
import com.ssh.service.PersonService;
public class Test {
@org.junit.Test
public void add() {
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-hibernate.xml");
PersonService service = (PersonService) ac.getBean("personService");
Person person = new Person();
person.setUsername("sucess");
person.setPhone("12344455");
person.setRemark("wewe");
service.add(person);
}
// @org.junit.Test
// public void update() {
// ApplicationContext ac = new ClassPathXmlApplicationContext("spring-hibernate.xml");
// PersonService service = (PersonService) ac.getBean("personService");
//
// Person person = service.getByid(2);
// person.setUsername("update name");
// service.update(person);
//
// }
}
若数据库里有记录增加,说明整合成功
springMVC与spring+hibernate整合
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_3_0.xsd"
version="3.0" id="WebApp_1513733828861">
<!-- 地址为http://localhost:8080/ 显示的默认网页 -->
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<!-- spring MVC config start -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 此处指向的的是SpringMVC的配置文件 -->
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!--配置容器在启动的时候就加载这个servlet并实例化 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<!-- spring MVC config end -->
<!-- 加载spring bean -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring-hibernate.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 字符集过滤 -->
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
spring-mvc.xml
<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-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- 启动注解驱动的spring MVC功能,注册请求url和注解POJO类方法的映射 -->
<mvc:annotation-driven />
<context:component-scan base-package="com.ssh.controller" />
<!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/views/" /> <!-- 前缀 -->
<property name="suffix" value=".jsp" /> <!-- 后缀 -->
</bean>
<!--这里是对静态资源的映射 -->
<!-- <mvc:resources mapping="/js/**" location="/resources/js/" /> -->
<!-- <mvc:resources mapping="/css/**" location="/resources/css/" /> -->
<!-- <mvc:resources mapping="/img/**" location="/resources/img/" /> -->
<!-- </bean> -->
</beans>
PersonController.java
package com.ssh.controller;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.ssh.entity.Person;
import com.ssh.json.AjaxJson;
import com.ssh.service.PersonService;
import net.sf.json.JSONArray;
@Controller
@RequestMapping("/person")
public class PersonController {
@Autowired
private PersonService personService;
@RequestMapping("list")
public ModelAndView list(HttpServletRequest request, Model model) {
model.addAttribute("list", personService.getAll());
return new ModelAndView("list");
}
@RequestMapping("show")
public String findById(HttpServletRequest request, int id, Model model) {
Person person = personService.getByid(id);
model.addAttribute("persob", person);
return "show";
}
public PersonService getPersonService() {
return personService;
}
public void setPersonService(PersonService personService) {
this.personService = personService;
}
}
部署到tomcat并进行测试
源码已经上传到github上传送门