基于注解的SSH框架搭建(打算整合tiles,暂未整合)
框架中的版本:struts2:struts2.2.1 hibernate:3.6.0 spring:3.0.5
1.框架中的所有的jar:上2张图即可
2.框架中的所有配置文件(放在WEB-INF/config目录下)
2.1 dataSource.properties // 数据源和Hibernate相关的变量
2.2 log4j.properties //错误日志的配置
2.3 spring-config.xml //spring的配置
2.4 struts.xml //struts的配置
下面列出各个配置文件的详细信息:
dataSource.properties
1 ##dataSource 2 jdbc.driverClassName=com.mysql.jdbc.Driver 3 jdbc.url=jdbc:mysql://localhost:3306/test 4 jdbc.username=root 5 jdbc.password=914521 6 7 ##hibernate configuration 8 hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect 9 hibernate.show_sql=true 10 hibernate.query.substitutions=true 1, false 0 11 hibernate.default_batch_fetch_size=16 12 hibernate.max_fetch_depth=2 13 hibernate.generate_statistics=true 14 hibernate.bytecode.use_reflection_optimizer=true 15 16 ##jdbc Template 17 jdbcTemplate.maxRows=2000
log4j.properties
1 ##log4j is made of three components which is level destination and pattern 2 ##level: ERROR WARN INFO DEBUG is the order from high to low 3 4 ##destination 5 log4j.rootLogger=INFO, CONSOLE 6 7 ##console log 8 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender 9 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout 10 log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c - %m %n 11 12 ##all log 13 ##log4j.appender.DAILY_ALL=org.apache.log4j.DailyRollingFileAppender 14 ##log4j.appender.DAILY_ALL.layout=org.apache.log4j.PatternLayout 15 ##log4j.appender.DAILY_ALL.layout.ConversionPattern=%p %d{yyyy-MM-dd HH:mm:ss} %-5050c(%L) -%m%n 16 ##log4j.appender.DAILY_ALL.File=${log4j.appender.DAILY_ALL.File} 17 18 ##logger 19 ##log4j.logger.org.springframework=INFO,CONSOLE 20 ##log4j.logger.org.hibernate=INFO,CONSOLE 21 ##log4j.logger.org.apache=INFO.CONSOLE
spring-config.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:aop="http://www.springframework.org/schema/aop" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xmlns:tx="http://www.springframework.org/schema/tx" 7 xmlns:util="http://www.springframework.org/schema/util" 8 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 9 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 10 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 11 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 12 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd 13 "> 14 15 <!-- 引入配置文件 --> 16 <bean id="propertyManager" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 17 <property name="locations"> 18 <list> 19 <value>/WEB-INF/config/dataSource.properties</value> 20 </list> 21 </property> 22 </bean> 23 24 <!-- 启动注解 --> 25 <context:annotation-config/> 26 <context:component-scan base-package="com.zjut.json"/> 27 28 29 <!-- 数据源配置 --> 30 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" 31 destroy-method="close" lazy-init="true"> 32 <property name="driverClass"> 33 <value>${jdbc.driverClassName}</value> 34 </property> 35 <property name="jdbcUrl"> 36 <value>${jdbc.url}</value> 37 </property> 38 <property name="user"> 39 <value>${jdbc.username}</value> 40 </property> 41 <property name="password"> 42 <value>${jdbc.password}</value> 43 </property> 44 </bean> 45 <!-- session Factory --> 46 <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> 47 <property name="dataSource" ref="dataSource"></property> 48 <property name="packagesToScan"> 49 <list> 50 <value>com.zjut.json.ssh.entity.po</value> 51 </list> 52 </property> 53 <property name="hibernateProperties"> 54 <props> 55 <prop key="hibernate.dialect">${hibernate.dialect}</prop> 56 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> 57 <prop key="hibernate.format_sql">true</prop> 58 <prop key="hibernate.query.substitutions">${hibernate.query.substitutions}</prop> 59 <prop key="hibernate.default_batch_fetch_size">${hibernate.default_batch_fetch_size}</prop> 60 <prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop> 61 <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop> 62 <prop key="hibernate.bytecode.use_reflection_optimizer">${hibernate.bytecode.use_reflection_optimizer}</prop> 63 </props> 64 </property> 65 </bean> 66 <!-- 事物配置 --> 67 <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> 68 <property name="sessionFactory" ref="sessionFactory"></property> 69 </bean> 70 <tx:advice id="txAdvice" transaction-manager="txManager"> 71 <tx:attributes> 72 <tx:method name="*" propagation="REQUIRED"/> 73 </tx:attributes> 74 </tx:advice> 75 <!-- 事物作用对象 --> 76 <aop:config expose-proxy="true"> 77 <aop:pointcut expression="execution(* com.zjut.json..service..*.*(..))" id="txPointcut"/> 78 <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> 79 </aop:config> 80 81 <!-- hibernate Template --> 82 <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> 83 <property name="sessionFactory" ref="sessionFactory"></property> 84 </bean> 85 <!-- jdbcTemplate --> 86 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> 87 <property name="dataSource" ref="dataSource"></property> 88 <property name="maxRows" value="${jdbcTemplate.maxRows}"></property> 89 </bean> 90 </beans>
struts.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 4 "http://struts.apache.org/dtds/struts-2.0.dtd"> 5 <struts> 6 <constant name="struts.devMode" value="true"/> 7 <!-- 国际化编码 --> 8 <constant name="struts.i18n.encoding" value="UTF-8" /> 9 <constant name="struts.convention.default.parent.package" value="default-package"/> 10 <constant name="struts.convention.package.location" value="action"/> 11 <constant name="struts.objectFactory" value="spring"/> 12 <!-- 视图资源所在的路径 --> 13 <constant name="struts.convention.result.path" value="/WEB-INF/view"/> 14 <!-- action后缀 --> 15 <constant name="struts.convention.action.suffix" value="action"></constant> 16 <package name="default-package" extends="tiles-default"></package> 17 </struts>
3.框架搭配验证
3.1 验证说明:前台页面输入一个用户的信息,注册到数据库中,注册成功说明框架搭配成功
3.2 框架中涉及的Action:IndexAction
1 package com.zjut.json.ssh.action; 2 3 4 import org.apache.log4j.Logger; 5 import org.apache.struts2.convention.annotation.Action; 6 import org.apache.struts2.convention.annotation.Namespace; 7 import org.apache.struts2.convention.annotation.ParentPackage; 8 import org.apache.struts2.convention.annotation.Result; 9 import org.apache.struts2.json.annotations.JSON; 10 import org.springframework.beans.factory.annotation.Autowired; 11 import org.springframework.context.annotation.Scope; 12 import org.springframework.util.Assert; 13 14 import com.opensymphony.xwork2.ActionSupport; 15 import com.zjut.json.ssh.entity.po.User; 16 import com.zjut.json.ssh.service.UserService; 17 /** 18 * @author json 19 * 20 * @date 2013-4-15 21 */ 22 @ParentPackage("json-default") 23 @Namespace("/") 24 @Scope("prototype") 25 public class IndexAction extends ActionSupport{ 26 27 /** 28 * 29 */ 30 private static final long serialVersionUID = 1L; 31 32 private Logger log = Logger.getLogger(IndexAction.class); 33 34 @Autowired 35 private UserService userService; 36 37 private User user; 38 39 private String rlst; 40 41 @Action(value = "index", results = {@Result(name = "success", location = "index.jsp")}) 42 public String index(){ 43 return SUCCESS; 44 } 45 46 @Action(value = "register", results = {@Result(name = "success", type = "json")}) 47 public String register(){ 48 Assert.notNull(userService, "user服务对象不能为空"); 49 try{ 50 userService.saveUser(user); 51 rlst = "保存成功"; 52 }catch(final Exception e){ 53 log.info("保存用户出现异常", e); 54 rlst = "保存失败"; 55 } 56 return SUCCESS; 57 } 58 59 @JSON(serialize = false) 60 public User getUser() { 61 return user; 62 } 63 64 public void setUser(User user) { 65 this.user = user; 66 } 67 68 @JSON(serialize = true) 69 public String getRlst() { 70 return rlst; 71 } 72 73 public void setRlst(String rlst) { 74 this.rlst = rlst; 75 } 76 }
3.3 框架中涉及的Dao: UserDao, UserDaoImpl, BaseDao, BaseDaoImpl----BaseDao是Dao的基本接口,其中定义了简单的一些增删改查,UserDao调用BaseDao中的方法
下面列出各个Dao及其实现:
BaseDao--此处只是为了验证框架,所以未进行过多的书写
1 package com.zjut.json.ssh.dao; 2 3 import java.io.Serializable; 4 5 /** 6 * 基本Dao 7 * 8 *@author json 9 * 10 *@Date 2013-4-15 11 */ 12 public interface BaseDao<T> { 13 14 /** 15 * 保存实体 16 * 17 * @param t 实体 18 */ 19 public void save(T t); 20 21 /** 22 * 删除实体 23 * 24 * @param id 实体Id 25 */ 26 public void delete(Class<T> tClass, Serializable id); 27 28 /** 29 * 更新实体 30 * 31 * @param t 实体 32 */ 33 public void update(T t); 34 35 /** 36 * 获取实体 37 * 38 * @param id 实体Id 39 * 40 * @return 实体 41 */ 42 public T get(Class<T> tClass, Serializable id); 43 44 }
BaseDaoImpl--BaseDao的实现
1 package com.zjut.json.ssh.dao.impl; 2 3 import java.io.Serializable; 4 5 import org.hibernate.Session; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.jdbc.core.JdbcTemplate; 8 import org.springframework.orm.hibernate3.HibernateTemplate; 9 10 import com.zjut.json.ssh.dao.BaseDao; 11 12 /** 13 *@author json 14 * 15 *@Date 2013-4-15 16 */ 17 public class BaseDaoImpl<T> implements BaseDao<T> { 18 19 @Autowired 20 private HibernateTemplate hibernateTemplate; 21 22 @Autowired 23 private JdbcTemplate jdbcTemplate; 24 25 public HibernateTemplate getHibernateTemplate() { 26 return hibernateTemplate; 27 } 28 29 public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { 30 this.hibernateTemplate = hibernateTemplate; 31 } 32 33 public JdbcTemplate getJdbcTemplate() { 34 return jdbcTemplate; 35 } 36 37 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { 38 this.jdbcTemplate = jdbcTemplate; 39 } 40 41 @Override 42 public void save(T t) { 43 getHibernateTemplate().save(t); 44 } 45 46 @Override 47 public void delete(Class<T> tClass, Serializable id) { 48 T t = get(tClass, id); 49 if( t != null){ 50 getHibernateTemplate().delete(t); 51 } 52 } 53 54 @Override 55 public void update(T t) { 56 getHibernateTemplate().update(t); 57 } 58 59 @Override 60 public T get(Class<T> tClass, Serializable id) { 61 return getHibernateTemplate().get(tClass, id); 62 } 63 64 /** 65 * 获取当前session 66 * 67 * @return session 68 */ 69 final Session getSession(){ 70 return getHibernateTemplate().getSessionFactory().getCurrentSession(); 71 } 72 73 }
UserDao--其实什么也没有,哈哈
1 package com.zjut.json.ssh.dao; 2 3 import com.zjut.json.ssh.entity.po.User; 4 5 /** 6 *@author json 7 * 8 *@Date 2013-4-15 9 */ 10 public interface UserDao extends BaseDao<User>{ 11 12 }
UserDaoImpl--其实也木有东东。。。。。
1 package com.zjut.json.ssh.dao.impl; 2 3 import org.springframework.stereotype.Repository; 4 5 import com.zjut.json.ssh.dao.UserDao; 6 import com.zjut.json.ssh.entity.po.User; 7 8 /** 9 *@author json 10 * 11 *@Date 2013-4-15 12 */ 13 @Repository(value = "userDao") 14 public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao { 15 16 }
3.4 框架中的Service层,包含UserService和UserServiceImpl,其中只是写了一个保存User的方法,列一下接口,实现就不上源码了。。。
1 package com.zjut.json.ssh.service; 2 3 import com.zjut.json.ssh.entity.po.User; 4 5 /** 6 *@author json 7 * 8 *@Date 2013-4-15 9 */ 10 public interface UserService { 11 12 /** 13 * 保存用户 14 * 15 * @param user 用户 16 */ 17 public void saveUser(User user); 18 19 }
3.5 框架中的实体,本来不想写的,毕竟还是涉及到Hibernate嘛,装一下啦。。。User敬上,哈哈
1 package com.zjut.json.ssh.entity.po; 2 3 import java.sql.Timestamp; 4 5 import javax.persistence.Column; 6 import javax.persistence.Entity; 7 import javax.persistence.GeneratedValue; 8 import javax.persistence.GenerationType; 9 import javax.persistence.Id; 10 import javax.persistence.Table; 11 12 /** 13 *@author json 14 * 15 *@Date 2013-4-15 16 */ 17 @Entity 18 @Table(name = "JSON_USER") 19 public class User { 20 21 @Id 22 @GeneratedValue(strategy = GenerationType.AUTO) 23 @Column(name = "id", unique = true, nullable = false) 24 private int id; 25 26 @Column(name = "name") 27 private String name; 28 29 @Column(name = "nickName") 30 private String nickName; 31 32 @Column(name = "password") 33 private String password; 34 35 //注册时间 pattern yyyy-MM-dd HH:mm:ss 36 @Column(name = "registerTime") 37 private Timestamp registerTime; 38 39 //最后修改时间 40 @Column(name = "lastModifiedTime") 41 private Timestamp lastModifiedTime; 42 43 public int getId() { 44 return id; 45 } 46 47 public void setId(int id) { 48 this.id = id; 49 } 50 51 public String getName() { 52 return name; 53 } 54 55 public void setName(String name) { 56 this.name = name; 57 } 58 59 public String getNickName() { 60 return nickName; 61 } 62 63 public void setNickName(String nickName) { 64 this.nickName = nickName; 65 } 66 67 public String getPassword() { 68 return password; 69 } 70 71 public void setPassword(String password) { 72 this.password = password; 73 } 74 75 public Timestamp getRegisterTime() { 76 return registerTime; 77 } 78 79 public void setRegisterTime(Timestamp registerTime) { 80 this.registerTime = registerTime; 81 } 82 83 public Timestamp getLastModifiedTime() { 84 return lastModifiedTime; 85 } 86 87 public void setLastModifiedTime(Timestamp lastModifiedTime) { 88 this.lastModifiedTime = lastModifiedTime; 89 } 90 91 }
3.6 最后一步啦,前台页面,要成功啦,吼吼。。。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file="../common/taglib.jsp" %> <!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"> <script src="${root}/js/jquery-1.8.2.js"></script> <title>框架首页</title> <script type="text/javascript"> $.ajaxSetup({ cache: false }); $(function(){ $("input[type='button']").click(function(){ var form = $("#registerForm"); var resetNode = $("input[type='reset']"); var url = form.attr("action"); var args = form.serialize(); $.post(url, args, function(data){ data = data.rlst; alert(data); //重置表单 resetNode.trigger("click"); }); }); }); </script> </head> <body> <div class="userInfo"> <form action="${root}/register.action" method="post" id="registerForm"> <label>用户姓名:<input name="user.name"/></label><br> <label>用户昵称:<input name="user.nickName"></label><br> <label>用户密码:<input name="user.password" type="password"/></label><br> <label><input type="button" value="提交"/><input type="reset" value="重置"></label> </form> </div> </body> </html>
3.7 运行效果,惨不忍主啊,太太。。。难看了
最后说明:此框架中还涉及了sturts的ajax,只需在lib中引用struts-json-plugin.jar,包就是继承自json-default即可,成功啦,收拾东东回家dota啦