spring springmvc hibernate(ssh)项目整合开发---总体架构搭建
国庆觉得没啥地方想去,于是乎想自己搭建一个长期的用于练手的ssh项目(注意:这里的ssh指的是spring4 springmvc4 hibernate4),在其中融进自己学到的技术,并持续进行更新,与诸位博友共享。目前开发了一个在web项目中比较实用的邮件通信工具类,其中在这个ssh项目中主要用于:“注册成功时采用邮箱验证”与“忘记密码时通过邮件找回密码”。我觉得两个是比较实用的小模块。
好了,废话不多说,在介绍上述的两个小模块之前,毫无疑问的,得先把项目的整体架构搭建起来!项目的后端架构采用spring4 springmvc4 hibernate4,前端采用jsp、jquery、ajax。
首先先预览一下项目的总体架构图:
放入jar包,可以到这里下载:ssm整合jar包
接下来,配置web.xml,如下所示:
<?xml version="1.0" encoding="UTF-8"?>spring的配置文件:(已在xml文件中进行详细的注释,不多说明)
<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">
<display-name>springspringmvchibernate</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- spring配置文件名称与位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-spring.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 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:applicationContext-springmvc.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>
<!-- 配置编码过滤器 -->
<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>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>数据库配置文件jdbc.properties:
<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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 添加注解支持 -->
<context:annotation-config />
<!-- 扫描server层包 -->
<context:component-scan base-package="com.steadyjack.server"></context:component-scan>
<!-- 导入jdbc数据库连接信息的配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 配置数据源 c3p0 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClassName}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
<property name="acquireIncrement" value="${jdbc.acquireIncrement}"></property>
<property name="maxStatements" value="${jdbc.maxStatements}"></property>
<property name="maxStatementsPerConnection" value="${jdbc.maxStatementsPerConnection}"></property>
<property name="maxIdleTime" value="${jdbc.maxIdleTime}"></property>
</bean>
<!-- 配置hibernate的sessionFactory,并让spring的ioc进行管理 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- 配置数据源属性 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 引入hibernate的属性配置文件 -->
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<!-- 扫描实体类,将其映射为具体的数据库表 -->
<property name="packagesToScan" value="com.steadyjack.server.model"></property>
</bean>
<!-- 配置事务管理,采用Hibernate4 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置事务传播属性,注意需要有事务管理(transaction-manager) : 其实就是事务(方法)发生的时间和要发生的故事-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="REQUIRED" read-only="true"/>
<tx:method name="load*" propagation="REQUIRED" read-only="true"/>
<tx:method name="query*" propagation="REQUIRED" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务切面,并关联事务的传播属性: 其实就是一个方法,只是这个方法是事务性的事务,它的发生不是随机的,而是具有时间,地点和该发生的故事的 -->
<aop:config>
<!-- 切点: 其实就是告诉了地点 -->
<aop:pointcut expression="execution(* com.steadyjack.server.service.*.*(..))" id="pointCut"/>
<!-- 要执行那样的事务,那当然得需要通知,通知它什么时候发生,在哪里发生,发生啥事 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/>
</aop:config>
</beans>
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_springspringmvchibernate?autoReconnect=true&useUnicode=true&characterEncoding=utf-8
jdbc.user=root
jdbc.password=123456
jdbc.initialPoolSize=4
jdbc.minPoolSize=3
jdbc.maxPoolSize=15
jdbc.acquireIncrement=3
jdbc.maxStatements=10
jdbc.maxStatementsPerConnection=5
jdbc.maxIdleTime=6000
hibernate配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- 配置二级缓存相关 -->
</session-factory>
</hibernate-configuration>
springmvc的配置文件:
<?xml version="1.0" encoding="UTF-8"?>最后是日志配置log4j.properties:
<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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 扫描web层 -->
<context:component-scan base-package="com.steadyjack.web.controller" />
<!-- 配置静态资源不经过dispatcher处理 -->
<mvc:default-servlet-handler/>
<mvc:annotation-driven />
<!-- 解析的结果: 前缀+ viewName +后缀 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
log4j.rootLogger = INFO, console, R
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n
log4j.appender.R = org.apache.log4j.RollingFileAppender
log4j.appender.R.File = D:\\logs\\log.log
log4j.appender.R.MaxFileSize = 500KB
log4j.appender.R.MaxBackupIndex = 1
log4j.appender.R.layout = org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] - %m%n
然后,建立com.steadyjack.server.dao、com.steadyjack.server.dao.impl这两个package,并在impl包创建BaseDaoImpl.java文件,用于获取hibernate的sessionFactory,以便给各个dao通用。
package com.steadyjack.server.dao.impl;在 com.steadyjack.server.model包下建立 User 这个Model
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class BaseDaoImpl{
@Autowired
private SessionFactory sessionFactory;
public Session getSession(){
return sessionFactory.getCurrentSession();
}
}
package com.steadyjack.server.model;在com.steadyjack.server.dao建立UserDao以及在 com.steadyjack.server.dao.impl建立UserDaoImpl
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="tb_user")
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = -5813264827007873950L;
private Integer id;
private String userName;
private String password;
private String email;
//1-男 0-女
private Integer sex;
//序列码
private String validateSerCode;
//序列码过时日期
private Date validateOverDate;
//用户名的字节编码
private String userNameEncodes;
//是否已经被验证:0表示未验证 1表示已经验证
private Integer isValidated=0;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name="user_name")
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;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name="validate_ser_code")
public String getValidateSerCode() {
return validateSerCode;
}
public void setValidateSerCode(String validateSerCode) {
this.validateSerCode = validateSerCode;
}
@Column(name="validate_over_date")
public Date getValidateOverDate() {
return validateOverDate;
}
public void setValidateOverDate(Date validateOverDate) {
this.validateOverDate = validateOverDate;
}
@Column(name="user_name_encodes")
public String getUserNameEncodes() {
return userNameEncodes;
}
@Column(name="is_validated")
public Integer getIsValidated() {
return isValidated;
}
public void setIsValidated(Integer isValidated) {
this.isValidated = isValidated;
}
public void setUserNameEncodes(String userNameEncodes) {
this.userNameEncodes = userNameEncodes;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", password="
+ password + ", email=" + email + ", sex=" + sex + "]";
}
}
package com.steadyjack.server.dao;
import java.util.List;
import com.steadyjack.server.model.User;
public interface UserDao {
public void saveUser(User user);
public User queryUser(User user);
public User findUserById(Integer id);
public User findUserPassword(String userName,String email);
public List<User> findUser(List<Object> params,String hql);
public void updateUser(User user);
public User findUserByUserName(String userName);
}
package com.steadyjack.server.dao.impl;import java.util.List;import org.hibernate.Query;import org.springframework.stereotype.Repository;import com.steadyjack.server.dao.UserDao;import com.steadyjack.server.model.User;@Repositorypublic class UserDaoImpl extends BaseDaoImpl implements UserDao { @SuppressWarnings("unchecked") public User queryUser(User user) { String hql="from User where userName=? and password=?"; Query query=getSession().createQuery(hql); query.setParameter(0, user.getUserName()); query.setParameter(1, user.getPassword()); User currentUser=null; List<User> userList=query.list(); if (userList!=null && userList.size()>0) { currentUser=userList.get(0); } return currentUser; } public void saveUser(User user) { getSession().save(user); } public User findUserById(Integer id) { String hql="from User where id=?"; Query query=getSession().createQuery(hql); query.setParameter(0, id); User user=(User) query.uniqueResult(); return user; } public User findUserPassword(String userName, String email) { String hql="from User where userName=? and email=?"; Query query=getSession().createQuery(hql); query.setParameter(0, userName); query.setParameter(1, email); User currentUser=(User) query.uniqueResult(); return currentUser; } public void updateUser(User user) { getSession().update(user); } @SuppressWarnings("unchecked") public List<User> findUser(List<Object> params,String hql) { Query query=getSession().createQuery(hql); if (params!=null && params.size()>0) { for(int i=0;i<params.size();i++){ query.setParameter(i, params.get(i)); } } return query.list(); } public User findUserByUserName(String userName) { String hql="from User where userName=?"; Query query=getSession().createQuery(hql); query.setParameter(0, userName); return (User) query.uniqueResult(); } }
在com.steadyjack.server.service包下建立UserService以及在com.steadyjack.server.service.impl包下建立UserServiceImpl
package com.steadyjack.server.service;
import java.util.List;
import java.util.Map;
import com.steadyjack.server.model.User;
public interface UserService {
public void addUser(User user);
public User queryUser(User user);
public User getUserById(Integer id);
public User findUserPassword(String userName,String email);
public List<User> findUsers(Map<String, Object> map);
public void updateUser(User user);
public void saveUser(User user);
public User findUserByUserName(String userName);
}
package com.steadyjack.server.service.impl;import java.util.LinkedList;import java.util.List;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.steadyjack.server.dao.UserDao;import com.steadyjack.server.model.User;import com.steadyjack.server.service.UserService;@Servicepublic class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public void addUser(User user) { userDao.saveUser(user); } public User queryUser(User user) { return userDao.queryUser(user); } public User getUserById(Integer id) { return userDao.findUserById(id); } public User findUserPassword(String userName, String email) { return userDao.findUserPassword(userName, email); } public void updateUser(User user) { userDao.updateUser(user); } public List<User> findUsers(Map<String, Object> map) { StringBuffer hql=new StringBuffer("from User where 1=1 "); List<Object> params=new LinkedList<Object>(); if (map.get("userName")!=null) { hql.append(" and userName=? "); params.add(map.get("userName")); } if (map.get("email")!=null) { hql.append(" and email=? "); params.add(map.get("email")); } if (map.get("sex")!=null) { hql.append(" and sex=? "); params.add(map.get("sex")); } if (map.get("validateOverDate")!=null) { hql.append(" and validateOverDate=? "); params.add(map.get("validateOverDate")); } if (map.get("validateSerCode")!=null) { hql.append(" and validateSerCode=? "); params.add(map.get("validateSerCode")); } if (map.get("userNameEncodes")!=null) { hql.append(" and userNameEncodes=? "); params.add(map.get("userNameEncodes")); } System.out.println(hql.toString()); return userDao.findUser(params, hql.toString()); } public User findUserByUserName(String userName) { return userDao.findUserByUserName(userName); } public void saveUser(User user) { userDao.saveUser(user); } }
最后,我们需要在com.steadyjack.web.controller包建立UserController(先介绍登录这个功能)
package com.steadyjack.web.controller;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.steadyjack.server.model.User;
import com.steadyjack.server.service.UserService;
import com.steadyjack.server.utils.DateUtils;
import com.steadyjack.server.utils.JavaMailUtils;
import com.steadyjack.server.utils.SystemUtils;
import com.steadyjack.server.utils.UUIDUtils;
@RequestMapping("/user")
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/index/{id}")
public String index(ModelMap map,@PathVariable Integer id){
System.out.println(userService.getUserById(id));
map.put("loginUser", userService.getUserById(id));
return "user/index";
}
@ResponseBody
@RequestMapping("/login")
public Map<String, Object> userLogin(ModelMap map,HttpServletRequest request) throws Exception{
Map<String, Object> resultMap=new HashMap<String, Object>();
User user=new User();
user.setUserName(request.getParameter("userName"));
user.setPassword(request.getParameter("password"));
User currentUser=userService.queryUser(user);
if (currentUser!=null) {
resultMap.put("id", currentUser.getId());
resultMap.put("res", "yes");
}else{
resultMap.put("res", "no");
}
return resultMap;
}
}
最后是webContent的启动jsp文件index.jsp(这里用到了jquery ajax的交互):
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<c:set value="${pageContext.request.contextPath }" var="ctx"></c:set>
<script type="text/javascript" src="${ctx}/style/js/jquery-1.7.2.min.js"></script>
<title>用户登录</title>
<script type="text/javascript">
$(function(){
var serverUrl=$('#serverUrl').val();
$('#loginBtn').click(function(){
var userName = $('#userName').val();
var password = $('#password').val();
if (userName == null || password == null || trim(userName) == "" || trim(password) == "") {
$('#errorTip').html("用户名或密码不能为空!");
return false;
}
$('#errorTip').html("");
$.post(serverUrl+'/user/login',{
userName:userName,
password:password
},function(requestData){
if (requestData.res=='yes') {
window.location.href=serverUrl+'/user/index/'+parseInt(requestData.id);
} else {
$('#errorInfo').html('*用户名或者密码错误!');
}
});
});
});
function resetValue() {
$('#userName').val("");
$('#password').val("");
}
//去掉最后的空格
function trim(str) {
return str.replace(/(^\s+)|(\s+$)/g, "");
}
</script>
</head>
<body>
<input type="hidden" id="serverUrl" value="${pageContext.request.contextPath}" />
<div align="center" style="padding-top: 50px;">
<form>
<table>
<tr>
<td>用户名:</td>
<td><input type="text" id="userName" name="userName" /></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" id="password" name="password" /></td>
</tr>
<tr>
<td><input type="button" value="登录" id="loginBtn"/></td>
<td><input type="button" value="重置" /></td>
</tr>
<tr>
<td></td>
<td id="errorInfo" style="color: #ff0000;"></td>
</tr>
</table>
<div id="errorTip"></div>
</form>
<a href="${ctx}/user/forgetPassword">忘记密码</a> <a href="${ctx}/user/toRegister">用户注册</a>
</div>
</body>
</html>
右键项目,run 到tomcat,跑起来。如果没有报错,说明启动成功了!然后我们需要在我们的数据库录入用户的信息,测试登录功能。如下图:
好了,初步就先介绍到这里吧,明天介绍博文开篇提到的两个小模块!