F、N层结构+Entity+Service+Impl+Hibernate+DAO+Impl+Struts+Spring
Struts中常量的读取顺序:
a.struts-default.xml
b.struts-plugin.xml
c.struts.xml
d.struts.properties
e.web.xml
(1)加入Spring的jar包,配置文件
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="com.zgy" />
<!--
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/spring" />
<property name="username" value="root" />
<property name="password" value="bjsxt" />
</bean>
-->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--
<property name="annotatedClasses">
<list>
<value>com.bjsxt.model.User</value>
<value>com.bjsxt.model.Log</value>
</list>
</property>
-->
<property name="packagesToScan">
<list>
<value>com.zgy.registration.model</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<aop:config>
<aop:pointcut id="bussinessService"
expression="execution(public * com.zgy.registration.service.*.*(..))" />
<aop:advisor pointcut-ref="bussinessService"
advice-ref="txAdvice" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="exists" read-only="true" />
<tx:method name="add*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
</beans>
(2)UserManagerImpl交由Spring处理
package com.zgy.registration.serviceImpl;
import java.sql.SQLException;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import com.zgy.registration.dao.UserDao;
import com.zgy.registration.model.User;
import com.zgy.registration.service.UserManager;
@Component("userManager")
public class UserManagerImpl implements UserManager {
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
@Resource
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
/* (non-Javadoc)
* @see com.zgy.registration.serviceImpl.UserManager#exists(com.zgy.registration.model.User)
*/
@Override
public boolean exists(User u) throws SQLException, ClassNotFoundException {
return userDao.checkUserExistsWithName(u.getUsername());
}
/* (non-Javadoc)
* @see com.zgy.registration.serviceImpl.UserManager#add(com.zgy.registration.model.User)
*/
@Override
public void add(User u) {
userDao.save(u);
}
}
(3)UserDaoImpl交由Spring处理
package com.zgy.registration.daoImpl;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Component;
import com.zgy.registration.dao.UserDao;
import com.zgy.registration.model.User;
import com.zgy.registration.util.HibernateUtil;
@Component("userDao")
public class UserDaoImpl implements UserDao {
private HibernateTemplate hibernateTemplate;
public void save(User u) {
hibernateTemplate.save(u);
}
public boolean checkUserExistsWithName(String username) {
List<User> user = (List<User>) hibernateTemplate.find("from User u where u.username=?", username);
if(user != null && user.size() > 0){
return true;
}
return false;
}
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
@Resource
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
}
(4)加入struts-spring-plugin.jar
(5)配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<!-- 加入Spring的监听器,在容器启动时,自动加载Spring中的bean -->
<!-- 默认值是读取 /WEB-INF/applicationContext.xml这个文件 -->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<!-- 通过以下配置修改默认的读取Spring配置,此时会读取classpath下的beans.xml文件 -->
<param-name>contextConfigLocation</param-name>
<!-- <param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value> -->
<param-value>classpath:beans.xml</param-value>
</context-param>
<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>
</web-app>
(6)将UserAction交由Spring处理
package com.zgy.registration.action;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.zgy.registration.model.User;
import com.zgy.registration.service.UserManager;
import com.opensymphony.xwork2.ActionSupport;
@Component("user")
@Scope("prototype")
public class UserAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private String password;
private String password2;
UserManager um;
public UserAction(){
}
public UserManager getUm() {
return um;
}
@Resource(name="userManager")
public void setUm(UserManager um) {
this.um = um;
}
@Override
public String execute() throws Exception {
User u = new User();
u.setUsername(username);
u.setPassword(password);
if(um.exists(u)) {
return "fail";
}
um.add(u);
return "success";
}
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 getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
}
(7)启动Web工程,验证通过。
G、DTO/VO
(1)在使用Struts的时候,使用ModelDriven接受参数
package com.zgy.registration.action;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.zgy.registration.model.User;
import com.zgy.registration.service.UserManager;
import com.zgy.registration.vo.UserRegisterInfo;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
@Component("user")
@Scope("prototype")
public class UserAction extends ActionSupport implements ModelDriven {
/**
*
*/
private static final long serialVersionUID = 1L;
private UserRegisterInfo info = new UserRegisterInfo();
private UserManager um;
public UserRegisterInfo getInfo() {
return info;
}
public void setInfo(UserRegisterInfo info) {
this.info = info;
}
public UserAction(){
}
public UserManager getUm() {
return um;
}
@Resource(name="userManager")
public void setUm(UserManager um) {
this.um = um;
}
@Override
public String execute() throws Exception {
User u = new User();
u.setUsername(info.getUsername());
u.setPassword(info.getPassword());
if(um.exists(u)) {
return "fail";
}
um.add(u);
return "success";
}
@Override
public Object getModel(){
return info;
}
}
(2)ModelDriven背后的运行机制
ModelDriven背后的机制就是ValueStack。界面通过:username/password/password2这样的名称,就能够被直接赋值给user对象,这证明user对象正是ValueStack中的一个root对象!
那么,为什么user对象会在ValueStack中呢?它是什么时候被压入ValueStack的呢?答案是:ModelDrivenInterceptor(关于Interceptor的概念,请参考后续章节的说明)。ModelDrivenInterceptor是缺省的拦截器链的一部分,当一个请求经过ModelDrivenInterceptor的时候,在这个拦截器中,会判断当前要调用的Action对象是否实现了ModelDriven接口,如果实现了这个接口,则调用getModel()方法,并把返回值(本例是返回user对象)压入ValueStack。
请看ModelDrivenInterceptor的代码:
public class ModelDrivenInterceptor extends AbstractInterceptor {
protected boolean refreshModelBeforeResult = false;
public void setRefreshModelBeforeResult(boolean val) { this.refreshModelBeforeResult = val; }
@Override public String intercept(ActionInvocation invocation) throws Exception { Object action = invocation.getAction();
if (action instanceof ModelDriven) { ModelDriven modelDriven = (ModelDriven) action; ValueStack stack = invocation.getStack(); Object model = modelDriven.getModel(); if (model != null) { stack.push(model); } if (refreshModelBeforeResult) { invocation.addPreResultListener(new RefreshModelBeforeResult(modelDriven, model)); } } return invocation.invoke(); } |
从ModelDrivenInterceptor中,即可以看到model对象被压入ValueStack中!