搭建SpringMVC4.x+Spring4.x+Hibernate4.x(非Maven版)
来源:互联网 发布:怎么增加淘宝搜索引擎 编辑:程序博客网 时间:2024/05/19 17:49
1.创建数据库ssh-pro,使用utf-8编码
2.首先创建一个Java Web项目输入相关参数点击下一步,知道出现要求创建web.xml,勾选创建web.xml,点击完成即可
3.将ssh所需要的jar全部复制到WebContent/WEB-INF/lib文件夹下,程序会自动将jar添加到编译环境中
4.在ssh项目下创建一个Source Folder的文件夹名为config,用来放一些配置文件。创建test,用来放置测试代码
5.再src下面创建org.ccnu.dao,来存放数据操作的相关代码。创建org.ccnu.service,来存放服务的相关代码。创建org.ccnu.entity,来存放数据模型代码。创建org.ccnu.controller,来存放控制层相关代码。
6.项目第一步是创建数据连接层
在config里创建config.properties,注意里面不能出现中文。代码如下:
#application configs#jdbc c3p0 configjdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/ssh-pro?useUnicode=true&characterEncoding=utf-8jdbc.username=rootjdbc.password=root#hibernate confighibernate.dialect=org.hibernate.dialect.MySQL5Dialecthibernate.show_sql=truehibernate.format_sql=falsehibernate.hbm2ddl.auto=updatehibernate.c3p0.validate=truehibernate.temp.use_jdbc_metadata_defaults=false#second cachecache.use_second_level_cache=truecache.use_query_cache=truecache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactorycache.provider_configuration_file_resource_path=ehcache.xml###############################################################file save pathnormal_file_path=/home/lyt/TmpDemo7.创建相关配置文件
WEB-INF的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"> <display-name>ssh-pro</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>webAppRootKey</param-name> <param-value>ssh-pro.root</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml,classpath:spring-hibernate.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</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> <servlet> <servlet-name>ssh-servlet</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>ssh-servlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet> <description>JAX-RS Tools Generated - Do not modify</description> <servlet-name>JAX-RS Servlet</servlet-name> <servlet-class> com.sun.jersey.spi.spring.container.servlet.SpringServlet </servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>org.nercel.ccnu.edu.service</param-value> </init-param> <init-param> <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> <param-value>true</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>JAX-RS Servlet</servlet-name> <url-pattern>/jaxrs/*</url-pattern> </servlet-mapping> <session-config> <session-timeout>240</session-timeout> </session-config></web-app>
在config文件夹里创建相关的配置文件
spring-mvc.xml来配置控制层的相关操作。代码如下:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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" 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"> <!-- 自动扫描@Controller注入为bean --> <context:component-scan base-package="org.ccnu.controller"/> <!-- 以下为SpringMVC配置 --> <mvc:annotation-driven> <!-- 返回json数据,@response使用 --> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <mvc:resources mapping="/resources/**" location="/resources/" /> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 文件上传下载 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/></beans>
spring-hibernate.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-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"><!-- 配置数据源 c3p0 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"destroy-method="close"><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="checkoutTimeout" value="30000" /><!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 --><property name="idleConnectionTestPeriod" value="30" /><!-- 连接数据库连接池最大空闲时间 --><property name="maxIdleTime" value="30" /><!-- 连接池初始化连接数 --><property name="initialPoolSize" value="5" /><property name="minPoolSize" value="5" /><property name="maxPoolSize" value="20" /><!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 --><property name="acquireIncrement" value="5" /></bean><!-- 配置hibernate的SessionFactory --><bean id="sessionFactory"class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><!-- 注入数据源 相关信息 --><property name="dataSource" ref="dataSource" /><!-- hibernate配置信息 --><property name="hibernateProperties"><props><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.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop><prop key="hibernate.temp.use_jdbc_metadata_defaults">${hibernate.temp.use_jdbc_metadata_defaults}</prop></props></property><!-- 扫描hibernate注解配置的entity --><property name="packagesToScan" value="org.ccnu.entity" /></bean><!-- 配置事务管理器 --><bean id="transactionManager"class="org.springframework.orm.hibernate4.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory" /></bean><!-- 使用基于注解的事物 --><tx:annotation-driven transaction-manager="transactionManager" /></beans>8.在entity创建User类,代码如下:
package org.ccnu.entity;import java.io.Serializable;import java.util.Date;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;import javax.persistence.Temporal;import javax.persistence.TemporalType;import javax.persistence.UniqueConstraint;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;import org.ccnu.util.DateAdapter;import org.hibernate.annotations.GenericGenerator;import com.fasterxml.jackson.annotation.JsonFormat;/** * 用户 * @author liuyuantao * */@XmlRootElement@Entity@Table(name = "user", catalog = "ssh-pro", uniqueConstraints = @UniqueConstraint(columnNames = "userName") )public class User implements Serializable{/** * */private static final long serialVersionUID = 1L;private String id;private String userName;private String password;private String fullName;private String email;private Date birthDay;@Id @GenericGenerator(name = "idGenerator", strategy = "uuid") @GeneratedValue(generator = "idGenerator") @Column(length = 40)public String getId() {return id;}public void setId(String id) {this.id = id;} @Column(name = "username", nullable = true, length = 40)public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}@Column(name = "password", nullable = true, length = 40)public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Column(name = "fullName", nullable = true, length = 40)public String getFullName() {return fullName;}public void setFullName(String fullName) {this.fullName = fullName;}@Column(name = "email", nullable = true, length = 40)public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}@Temporal(TemporalType.DATE) @Column(name = "addTime", length = 19) @XmlJavaTypeAdapter(DateAdapter.class) @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "GMT+8")public Date getBirthDay() {return birthDay;}public void setBirthDay(Date birthDay) {this.birthDay = birthDay;}}9.在service创建UserService,在dao层创建userDao和BaseDao
package org.ccnu.dao;import java.io.Serializable;import java.lang.reflect.ParameterizedType;import java.util.List;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.springframework.beans.factory.annotation.Autowired;/** * 基础公共Dao类 * * @author liuyuantao * @param <T> * @param <PK> */public class BasicDao<T, PK extends Serializable> {protected Class<T> entityClass;@SuppressWarnings("unchecked")public BasicDao() {entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];}@Autowiredprivate SessionFactory sessionFactory;/** * 获取当前线程的session * * @return */private Session getCurrentSession() {return this.sessionFactory.getCurrentSession();}@SuppressWarnings("unchecked")public T load(PK id) {return (T) this.getCurrentSession().load(entityClass, id);}@SuppressWarnings("unchecked")public T get(PK id) {return (T) this.getCurrentSession().get(entityClass, id);}public List<T> findAll() {String sql = "select e from " + entityClass.getSimpleName() + " e";@SuppressWarnings("unchecked")List<T> list = this.getCurrentSession().createQuery(sql).list();return list != null ? list : null;}public void persist(T entity) {this.getCurrentSession().persist(entity);}@SuppressWarnings("unchecked")public PK save(T entity) {return (PK) this.getCurrentSession().save(entity).toString();}@SuppressWarnings("unchecked")public PK merge(T entity) {return (PK) this.getCurrentSession().merge(entity);}public void saveOrUpdate(T entity) {this.getCurrentSession().saveOrUpdate(entity);}public void delete(T entity) {this.getCurrentSession().delete(entity);}public void flush() {this.getCurrentSession().flush();}}
package org.ccnu.dao;import java.util.List;import org.ccnu.entity.User;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;@Repository(value = "userDao")public class UserDao extends BasicDao<User, String> {@Autowiredprivate SessionFactory sessionFactory;/** * 获取当前线程的session * * @return */private Session getCurrentSession() {return sessionFactory.getCurrentSession();// 还是可以得到session}/** * 通过姓名模糊查找用户 * * @param fullName * @return */@SuppressWarnings("unchecked")public List<User> findUserByFullName(String fullName) {String sql = "select model from User model where model.fullName like :fullName";Query query = this.getCurrentSession().createQuery(sql);query.setParameter("fullName", "%" + fullName + "%");return query.list();}}
package org.ccnu.service;import java.util.List;import org.ccnu.dao.UserDao;import org.ccnu.entity.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;@Transactional@Service("userService")public class UserService {@Autowiredprivate UserDao userDao;@Transactional(readOnly = false)public String saveUser(User user) {return userDao.save(user);}@Transactional()public List<User> findUserByFullName(String fullName) {return userDao.findUserByFullName(fullName);}}
1 0
- 搭建SpringMVC4.x+Spring4.x+Hibernate4.x(非Maven版)
- Spring4.x+Hibernate4.x整合
- springmvc4+spring4+hibernate4搭建
- spring4.x + hibernate4.x 配置详解
- spring4.x + hibernate4.x 配置详解
- spring4.x + hibernate4.x 配置详解
- spring4.x + hibernate4.x 配置详解
- 2.5 maven+spring4.X基础上搭建mybatis
- Struts2.x、Hibernate4.x、Spring4.x重点梳理
- 2.2 maven基础上搭建springmvc4.X,一步一步超简单。
- 搭建Spring4.x.x开发环境
- spring4.x hibernate4.x 整合 ehcache 注解 annotate
- spring4.x hibernate4.x 整合 ehcache 注解 annotate
- SPRING4.X HIBERNATE4.X 整合 EHCACHE 注解 ANNOTATE
- Spring4.x+Hibernate4.x整合出现的问题
- spring4.x hibernate4.x 整合 ehcache 注解 annotate
- spring4.x + hibernate4.x+sqlite3 配置--不容易啊
- 蓝缘管理系统第三版推出。springMVC4.0+shiro1.2.3+spring4.x+Mybaits3.2.8
- 关于产品工作的三个问题分析
- 一个关于CodeIgniter框架的麻烦以及解决
- 方法重载规则
- 排序算法扩展之对象排序
- tomcat相关知识
- 搭建SpringMVC4.x+Spring4.x+Hibernate4.x(非Maven版)
- Qt遇到的问题
- Git命令详解-个人使用
- hdu 3068
- LeetCode153. Find Minimum in Rotated Sorted Array如何用五行代码解决它
- 如何执行java程序
- 信息资源管理综述
- Pixhawk之UAV控制理论、ardupilot源码框架介绍
- Django URL传递参数的方法总结