本文主要是介绍struts2 spring4 hibernate4(s2sh)整合开发--项目整体架构的搭建,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
struts2 spring4 hibernate4(s2sh)整合开发--项目整体架构的搭建
前不久弄了一个用于自己长期学习练手的s2sh项目:struts2、spring4、hibernate4的整合开发,不同于前面2篇ssh的博文,因为前面的ssh指的是spring4 springmvc hibernate4的整合开发(后面会有一个ssm的整合开发),不过搭建的目的还是比较明确,就是为了将在企业中的项目学到的东西用到自己的项目中去,内化为自己的东西!
先花两篇博客的时间介绍一下目前s2sh整合的项目中,我应用了哪些比较实用的知识。今晚先介绍一下第一篇博客,主要在搭建项目的总体架构,值得特别说明的是,对于dao的开发,我开发了一个所有dao都比较通用的dao实现类,用于所有的实体dao的实现类去继承!然后采用的当然是‘泛型’的做法,你可以在下面的代码可以清楚的看到。
先看看项目搭建完毕的总体结构吧:
项目用到的jar包可以来这里下载:s2sh整合需要的jar包
首先是项目启动的项目部署文件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"><display-name>Struts2Hibernate4Spring4</display-name><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><!-- 配置spring4 包括spring的配置文件以及管理struts2的action的IOC配置--><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><!-- openSessionInViewFileter 解决懒加载的问题 配置在Struts2过滤器之前--><filter><filter-name>openSessionInViewFileter</filter-name><filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class><init-param><param-name>singleSession</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>openSessionInViewFileter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 配置Struts2 --><filter><filter-name>Struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class></filter><filter-mapping><filter-name>Struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- log4j配置信息 --><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>6000</param-value></context-param><context-param><param-name>webAppRootKey</param-name><param-value>webApp.root</param-value></context-param><listener><listener-class>org.springframework.web.util.Log4jConfigListener</listener-class></listener></web-app>
spring的配置文件applicationContext.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: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.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"><!-- 采用注解开发,需要扫描server层,web层 --><context:component-scan base-package="com.steadyjack.server,com.steadyjack.web" /><!-- 数据库配置文件 --><context:property-placeholder location="classpath:jdbc.properties" /><!-- 配置c3p0数据源 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><!-- 数据库基本配置 --><property name="driverClass" value="${jdbc.driverClass}"></property><property name="user" value="${jdbc.user}"></property><property name="password" value="${jdbc.password}"></property><property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property><!-- 配置c3p0的其他信息 --><property name="initialPoolSize" value="${initialPoolSize}"></property><property name="maxPoolSize" value="${maxPoolSize}"></property><property name="minPoolSize" value="${minPoolSize}"></property><property name="acquireIncrement" value="${acquireIncrement}"></property><property name="maxIdleTime" value="${maxIdleTime}"></property></bean><!-- 配置spring的SessionFactory --><bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><property name="configLocation" value="classpath:hibernate.cfg.xml"></property><property name="packagesToScan" value="com.steadyjack.server.model"></property></bean><!-- 配置事务管理器 --><bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property></bean><!-- 配置事务传播属性 --><tx:advice id="txAdvice" transaction-manager="txManager"><tx:attributes><tx:method name="add*" propagation="REQUIRED"/><tx:method name="save*" propagation="REQUIRED"/><tx:method name="insert*" propagation="REQUIRED"/><tx:method name="update*" propagation="REQUIRED"/><tx:method name="modify*" propagation="REQUIRED"/><tx:method name="delete*" propagation="REQUIRED"/><tx:method name="find*" propagation="REQUIRED" read-only="true"/><tx:method name="get*" 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="txPointCut"/><aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/></aop:config></beans>
管理struts2中的action的spring的IOC配置文件applicationContext-beans.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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="userAction" class="com.steadyjack.web.action.UserAction" scope="prototype"></bean></beans>
hibenate配置文件hibernate.cfg.xml:
<?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><!-- 配置hibernate基本信息 --><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><!-- 配置ehcache二级缓存 --></session-factory>
</hibernate-configuration>
数据库配置文件:jdbc.properties:
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=123456
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/db_s2sh?useUnicode=true&characterEncoding=UTF-8initialPoolSize=5#连接池中拥有的最大连接数,如果获得新连接时会使连接总数超过这个值则不会再获取新连接,
#而是等待其他连接释放,所以这个值有可能会设计地很大,default : 15
maxPoolSize=30minPoolSize=5#连接池在无空闲连接可用时一次性创建的新数据库连接数,default:3
acquireIncrement=2#连接的最大空闲时间,如果超过这个时间,某个数据库连接还没有被使用,则会断开掉这个连接,单位 s
maxIdleTime=20
log4j日志配置文件:
#设置log4j的级别
log4j.rootLogger = INFO, console, Rlog4j.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%nlog4j.appender.R = org.apache.log4j.RollingFileAppender
log4j.appender.R.File = D:\\logs\\log.log
log4j.appender.R.MaxFileSize = 500KBlog4j.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
最后是struts2的配置文件struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!-- 基础配置 --><constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <constant name="struts.i18n.reload" value="true" /> <constant name="struts.configuration.xml.reload" value="true" ></constant> <!-- <constant name="struts.i18n.encoding" value="UTF-8" /> --> <!-- 在struts2中设置处理请求的后缀为 --><!-- <constant name="struts.action.extension" value="action"/> --> <!-- 该属性设置浏览器是否缓存静态内容。当应用处于开发阶段时,我们希望每次请求都获得服务器的最新响应,则可设置该属性为false --><!-- <constant name="struts.serve.static.browserCache" value="false" /> --><package name="default" namespace="/" extends="struts-default"> <action name="user-*" class="userAction" method="{1}"><result name="success">/WEB-INF/views/success.jsp</result> <result name="userInfo">/WEB-INF/views/userInfo.jsp</result> <result name="saveSuccess" type="redirect">user-main.action</result> <result name="error">/index.jsp</result> </action> </package> </struts>
配置文件讲完了,接下来就是需要建立后端的java代码的包目录结构:具体讲上面的第一张图,主要是dao、service与action。然后介绍一下BaseDao的开发:
package com.steadyjack.server.dao;import java.io.Serializable;
import java.util.List;/*** 通用Dao* @author 钟林森**/
public interface BaseDao<T> {/** * 保存一个对象 * @param o * @return */ public Serializable save(T o); /** * 删除一个对象 * @param o */ public void delete(T o); /** * 更新一个对象 * @param o */ public void update(T o); /** * 保存或更新对象 * @param o */ public void saveOrUpdate(T o); /** * 查询 * @param hql * @return */ public List<T> find(String hql); /** * 查询集合 * @param hql * @param param * @return */ public List<T> find(String hql, Object[] param); /** * 查询集合 * @param hql * @param param * @return */ public List<T> find(String hql, List<Object> param); /** * 查询集合(带分页) * @param hql * @param param * @param page * 查询第几页 * @param rows * 每页显示几条记录 * @return */ public List<T> find(String hql, Object[] param, Integer page, Integer rows); /** * 查询集合(带分页) * @param hql * @param param * @param page * @param rows * @return */ public List<T> find(String hql, List<Object> param, Integer page, Integer rows); /** * 获得一个对象 * @param c 对象类型 * @param id * @return Object */ public T get(Class<T> c, Serializable id); /** * 获得一个对象 * @param hql * @param param * @return Object */ public T get(String hql, Object[] param); /** * 获得一个对象 * @param hql * @param param * @return */ public T get(String hql, List<Object> param); /** * select count(*) from 类 * @param hql * @return */ public Long count(String hql); /** * select count(*) from 类 * @param hql * @param param * @return */ public Long count(String hql, Object[] param); /** * select count(*) from 类 * @param hql * @param param * @return */ public Long count(String hql, List<Object> param); /** * 执行HQL语句 * @param hql * @return 响应数目 */ public Integer executeHql(String hql); /** * 执行HQL语句 * @param hql * @param param * @return 响应数目 */ public Integer executeHql(String hql, Object[] param); /** * 执行HQL语句 * @param hql * @param param * @return */ public Integer executeHql(String hql, List<Object> param); /*** 执行sql语句* @param sql* @return*/public Integer executeSql(String sql); /*** 执行sql语句 * @param sql* @param param* @return*/public Integer executeSql(String sql, Object[] param); /*** 执行sql语句 * @param sql* @param param* @return*/public Integer executeSql(String sql, List<Object> param);
}
BaseDao的实现类BaseDaoImpl:
package com.steadyjack.server.dao.impl;import java.io.Serializable;
import java.util.List;import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;import com.steadyjack.server.dao.BaseDao;@Repository("baseDao")
@SuppressWarnings("all")
public class BaseDaoImpl<T> implements BaseDao<T> {private SessionFactory sessionFactory;public SessionFactory getSessionFactory() {return sessionFactory;}@Autowiredpublic void setSessionFactory(SessionFactory sessionFactory) {this.sessionFactory = sessionFactory;}/*** 获取当前session:如果当前会话工厂没有session,则创建一个* @return*/private Session getCurrentSession(){return getSessionFactory().getCurrentSession();}@Overridepublic Serializable save(T o) {return this.getCurrentSession().save(o);}@Overridepublic void delete(T o) {this.getCurrentSession().delete(o);}@Overridepublic void update(T o) {this.getCurrentSession().update(o);}@Overridepublic void saveOrUpdate(T o) {this.getCurrentSession().saveOrUpdate(o);}@Overridepublic List<T> find(String hql) {return this.getCurrentSession().createQuery(hql).list();}@Overridepublic List<T> find(String hql, Object[] param) {Query q=this.getCurrentSession().createQuery(hql);if (param!=null && param.length>0) {for(int i=0;i<param.length;i++){q.setParameter(i, param[i]);}}return q.list();}@Overridepublic List<T> find(String hql, List<Object> param) {Query q=this.getCurrentSession().createQuery(hql);if (param!=null && param.size()>0) {for(int i=0;i<param.size();i++){q.setParameter(i, param.get(i));}}return q.list();}@Overridepublic List<T> find(String hql, Object[] param, Integer page, Integer rows) {if (page==null || page<1) {page=1;}if (rows==null || rows<1) {rows=10;}Query q=this.getCurrentSession().createQuery(hql);if (param!=null && param.length>0) {for(int i=0;i<param.length;i++){q.setParameter(i, param[i]);}}return q.setFirstResult((page-1)*rows).setMaxResults(rows).list();}@Overridepublic List<T> find(String hql, List<Object> param, Integer page,Integer rows) {if (page==null || page<1) {page=1;}if (rows==null || rows<1) {rows=10;}Query q=this.getCurrentSession().createQuery(hql);if (param!=null && param.size()>0) {for(int i=0;i<param.size();i++){q.setParameter(i, param.get(i));}}return q.setFirstResult((page-1)*rows).setMaxResults(rows).list();}@Overridepublic T get(Class<T> c, Serializable id) {return (T) this.getCurrentSession().get(c, id);}@Overridepublic T get(String hql, Object[] param) {List<T> list=this.find(hql,param);if (list!=null && list.size()>0) {return list.get(0);}else{return null;}}@Overridepublic T get(String hql, List<Object> param) {List<T> list=this.find(hql,param);if (list!=null && list.size()>0) {return list.get(0);}else{return null;}}@Overridepublic Long count(String hql) {return (Long) this.getCurrentSession().createQuery(hql).uniqueResult();}@Overridepublic Long count(String hql, Object[] param) {Query q=this.getCurrentSession().createQuery(hql);if (param!=null && param.length>0) {for(int i=0;i<param.length;i++){q.setParameter(i, param[i]);}}return (Long) q.uniqueResult();}@Overridepublic Long count(String hql, List<Object> param) {Query q = this.getCurrentSession().createQuery(hql); if (param != null && param.size() > 0) { for (int i = 0; i < param.size(); i++) { q.setParameter(i, param.get(i)); } } return (Long) q.uniqueResult(); }@Overridepublic Integer executeHql(String hql) {return this.getCurrentSession().createQuery(hql).executeUpdate();}@Overridepublic Integer executeHql(String hql, Object[] param) {Query q=this.getCurrentSession().createQuery(hql);if (param!=null && param.length>0) {for(int i=0;i<param.length;i++){q.setParameter(i, param[i]);}}return q.executeUpdate();}@Overridepublic Integer executeHql(String hql, List<Object> param) {Query q = this.getCurrentSession().createQuery(hql); if (param != null && param.size() > 0) { for (int i = 0; i < param.size(); i++) { q.setParameter(i, param.get(i)); } } return q.executeUpdate();}@Overridepublic Integer executeSql(String sql) {Query q=this.getCurrentSession().createSQLQuery(sql);return q.executeUpdate();}@Overridepublic Integer executeSql(String sql, Object[] param) {Query q=this.getCurrentSession().createSQLQuery(sql);if(param!=null && param.length>0){for(int i=0;i<param.length;i++){q.setParameter(i, param[i]);}}return q.executeUpdate();}@Overridepublic Integer executeSql(String sql, List<Object> param) {Query q=this.getCurrentSession().createSQLQuery(sql);if(param!=null && param.size()>0){for(int i=0;i<param.size();i++){q.setParameter(i, param.get(i));}}return q.executeUpdate();}}
之后的实体dao的开发及其实现类就比较容易了!!!下面介绍UserDao以及UserDaoImpl:
package com.steadyjack.server.dao;public interface UserDao<T> extends BaseDao<T> {}
package com.steadyjack.server.dao.impl;import org.springframework.stereotype.Repository;import com.steadyjack.server.dao.UserDao;@Repository("userDao")
public class UserDaoImpl<T> extends BaseDaoImpl<T> implements UserDao<T> {}
你会发现相当简洁!!!当然啦,还有User这个实体Model别忘记了!!
package com.steadyjack.server.model;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 org.hibernate.annotations.GenericGenerator;@Entity
@Table(name="tb_user")
public class User implements Serializable{/*** */private static final long serialVersionUID = -518622128133421027L;private Integer id;private String userName;private String password;private String address;private String phoneNumber;private Date createTime;private Date updateTime;@Id@GenericGenerator(name="generator",strategy="increment")@GeneratedValue(generator="generator")@Column(name="id")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 String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Column(name="phone_number")public String getPhoneNumber() {return phoneNumber;}public void setPhoneNumber(String phoneNumber) {this.phoneNumber = phoneNumber;}@Column(name="create_time")public Date getCreateTime() {return createTime;}public void setCreateTime(Date createTime) {this.createTime = createTime;}@Column(name="update_time")public Date getUpdateTime() {return updateTime;}public void setUpdateTime(Date updateTime) {this.updateTime = updateTime;}@Overridepublic String toString() {return "User [id=" + id + ", userName=" + userName + ", password="+ password + ", address=" + address + ", phoneNumber="+ phoneNumber + ", createTime=" + createTime + ", updateTime="+ updateTime + "]";}}
然后建立UserServcie及其实现类:
package com.steadyjack.server.service;import java.util.List;import com.steadyjack.server.model.User;public interface UserService {public void saveUser(User user); public void updateUser(User user); public User findUserById(Integer id); public void deleteUser(User user); public List<User> findAllList(); public User findUserByNameAndPassword(String username, String password); }
package com.steadyjack.server.service.impl;import java.util.List;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;@Service("userService")
public class UserServiceImpl implements UserService {@Autowiredprivate UserDao<User> userDao;@Overridepublic void saveUser(User user) {userDao.save(user);}@Overridepublic void updateUser(User user) {userDao.update(user);}@Overridepublic User findUserById(Integer id) {return userDao.get(User.class, id);}@Overridepublic void deleteUser(User user) {userDao.delete(user);}@Overridepublic List<User> findAllList() {String hql="from User u order by u.createTime";return userDao.find(hql);}@Overridepublic User findUserByNameAndPassword(String username, String password) {String hql="from User u where u.userName=? and u.password=?";return userDao.get(hql, new Object[]{username,password});}}
截图中涉及到DateUtils与ResponseUtils,这两个实体类,是相当重要的,可以来我这两篇篇博客获取: DateUtils与ResponseUtils DateUtils与ResponseUtils。
最后当然是UserAction啦:
package com.steadyjack.web.action;import java.util.Date;
import java.util.List;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;import net.sf.json.JSONObject;import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.beans.factory.annotation.Autowired;import com.opensymphony.xwork2.ActionSupport;
import com.steadyjack.server.model.User;
import com.steadyjack.server.service.UserService;
import com.steadyjack.server.utils.DateUtils;
import com.steadyjack.server.utils.ResponseUtil;public class UserAction extends ActionSupport implements ServletRequestAware{/*** */private static final long serialVersionUID = 4826776981764583191L;private static Logger logger = Logger.getLogger(UserAction.class);@Autowiredprivate UserService userService;private HttpServletRequest request;private User user;private String userName;private String password;private String userId;private String delIds;public String getDelIds() {return delIds;}public void setDelIds(String delIds) {this.delIds = delIds;}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 User getUser() {return user;}public void setUser(User user) {this.user = user;}public String getUserId() {return userId;}public void setUserId(String userId) {this.userId = userId;}public String batchDelete() throws Exception{String result="批量删除成功";String[] ids=delIds.split(",");try {for (String id : ids) {User user=userService.findUserById(Integer.parseInt(id));if (user!=null) {userService.deleteUser(user);}}} catch (Exception e) {result="删除失败";}ResponseUtil.write(ServletActionContext.getResponse(), result.toString());return null;}public String delete() throws Exception{String result="删除发生异常";User user=userService.findUserById(Integer.parseInt(userId));if (user!=null) {userService.deleteUser(user);result="删除成功!";}ResponseUtil.write(ServletActionContext.getResponse(), result.toString());return null;}public String input() throws Exception{request.getSession().removeAttribute("modifyUser");return "userInfo";}public String save() throws Exception{System.out.println(user);if(user!=null && user.getId()!=null){User modifyUser=userService.findUserById(user.getId());modifyUser.setAddress(user.getAddress());modifyUser.setPassword(user.getPassword());modifyUser.setPhoneNumber(user.getPhoneNumber());modifyUser.setUserName(user.getUserName());modifyUser.setUpdateTime(new Date());userService.updateUser(modifyUser);}else{user.setCreateTime(new Date());user.setUpdateTime(new Date());userService.saveUser(user);}return "saveSuccess";}public String modify() throws Exception{User modifyUser=userService.findUserById(Integer.parseInt(userId));if (modifyUser!=null) {request.getSession().setAttribute("modifyUser", modifyUser);}return "userInfo";}public String login() throws Exception{logger.info("login方法调用: 时间: "+DateUtils.getDateString());User currentUser=userService.findUserByNameAndPassword(userName, password);JSONObject result=new JSONObject();if (currentUser!=null) {request.getSession().setAttribute("currentUser", currentUser);result.put("success", "yes");}else{request.getSession().setAttribute("errorInfo", "用户名或者密码不正确!");result.put("success", "no");}ResponseUtil.write(ServletActionContext.getResponse(), result.toString());return null; }public String main(){HttpSession session=request.getSession();List<User> userList=userService.findAllList();if (userList!=null && userList.size()>0) {session.setAttribute("userList", userList);}return "success";}@Overridepublic void setServletRequest(HttpServletRequest request) {this.request=request;}}
从UserAction代码中或许你也看出来了,我要初步实现的其实就是常说的CRUD,也就是查询,添加,修改,删除与批量删除。其中,前后端的交互将大部分采用jquery ajax的方式进行交互。我觉得这点,就相当实用!因为我发现我公司的项目很多都是jquery ajax来实现前后端交互的。
然后,贴一下项目启动时候的index.jsp,这里需要加入jquery-1.7.1.min.js放在项目WebContent目录下style目录下js目录下common目录中:
<%@ 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" />
<script type="text/javascript" src="${ctx}/style/js/common/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="${ctx}/style/js/user/user.js"></script>
<link rel="stylesheet" type="text/css" href="${ctx}/style/css/user/user.css">
<title>启动成功</title>
</head>
<body>
<input type="hidden" id="serverUrl" value="${ctx}"/>启动成功<br><br><form>用户名: <input type="text" id="userName" name="userName" /> <br><br>密码: <input type="password" id="password" name="password" /><br><br><a id="loginBtn" class="loginClass" title="登录">登录</a></form><br><br>${errorInfo}
</body>
</html>
需要的css与js:
@CHARSET "UTF-8";.loginClass{text-decoration: none;font-size: 18px;color: #ff0000;
}.loginClass:HOVER{text-decoration: underline;cursor: pointer;
}
$(function(){var serverUrl=$('#serverUrl').val();$('#loginBtn').bind('click',function(){//alert("登录");var userName=$('#userName').val();var password=$('#password').val();//也就是说如果你dataType写的是json格式,jQuery在返回时已经把返回值转换成了json对象,//这时就不需要再用eval转换了,如果dataType写的是text才需要用eval转换。console.log(userName+" -- "+password);$.post(serverUrl+"/user-login.action",{userName:userName,password:password},function(result){if (result.success=='yes') {window.location.href=serverUrl+"/user-main.action";} else {window.location.href=serverUrl+"/index.jsp";}},"json");});});
好了,启动项目,将其跑在tomcat下,启动没问题,而且会跳到登录界面,在数据库中录入相应数据, 然后进行登录,会发现需要调到success.jsp。暂时没放上来,在下一篇博客会讲到,总之搭建是没啥问题了!!!!
这篇关于struts2 spring4 hibernate4(s2sh)整合开发--项目整体架构的搭建的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!