`
zhangfeiii
  • 浏览: 44607 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

struts+spring+hibernate 总结

    博客分类:
  • SSH
阅读更多
1. myeclipse 中依次加载struts,spring,hibernate
2. 加上过滤器
WEN-INF/web.xml加上
<filter>
<filter-name>encodingfilter</filter-name>
<filter-class>com.yourcompany.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
EncodingFilter.java
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class EncodingFilter implements Filter {
public void init(FilterConfig cong) {
// do nothing
}
public void doFilter(ServletRequest srequest, ServletResponse sresponse,
FilterChain chain) {
try {
srequest.setCharacterEncoding("UTF-8");
chain.doFilter(srequest, sresponse);
} catch (Exception e) {
e.printStackTrace();
}
}
public void destroy() {
// do nothing
}
}
3. 加上Log4j.properties日志
Log4j.properties
# Configure logging for testing: optionally with log file
log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
4. struts加载spring的两种方式
第一种:通过web.xml配置加载spring上下文环境,其配置方式如下
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
//通过listener加载
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
或者利用severlet类加载
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
第二种方式使用Struts 插件在struts-config.xml中
<plug-inclassName="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/applicationContext.xml" />
</plug-in>
这两种配置的明显区别就是,第一种方式可以配置多个spring配置文件。
5. Spring 整合 Struts
替换 struts-config.xml Action 的 Type
<action path="/login” type="org.springframework.web.struts.DelegatingActionProxy" />
在 Spring 配置文件applicationContext.xml中配置 Bean
要点: 通过 path 和 bean 的 name 进行匹配, 这两个值必须一样
<bean name="/login" class="com.test.struts.action.LoginAction"></bean>
6. 组织结构
dao 存放dao 接口
dao.hibernate 存放持欠层实现
model存放pojo
service 存放业务层接口
service.impl存放业务层实现
web存放UI action
7. 事务代理
Spring也提供了声明式事务管理。这是通过Spring AOP实现的。
Spring 中进行事务管理的通常方式是利用AOP(面向切片编程)的方式,为普通java类封装事务控制,它是通
过动态代理实现的,由于接口是延迟实例化的, spring在这段时间内通过拦截器,加载事务切片。
applicationContext.xml
定义 sessionFactory
中定义 sessionFactory时注意
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
定义 dataSource
定义 sessionFactory
定义dao
类所定义的为dao实现类
<bean id="UserDAO" class="com.yourcompany.hibernate.UserDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
定义transactionManager
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
定义代理的bean
UserService为业务层实现
userDao为spring在业务层对象中注入
transactionAttributes中定义了事务代理需要拦截方法的处理
<bean id="UserServiceProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="proxyTargetClass">
<value>true</value>
</property>
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="target">
<bean class="com.yourcompany.hibernate.UserService">
<property name="userDao"><ref bean="UserDAO" /></property>
</bean>
</property>
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED,-MyCheckedException</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
对事务物代理的别另一种写法
<bean id="baseTxProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
lazy-init="true">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
<bean id="UserServiceProxy1" parent="baseTxProxy">
<property name="target">
<bean class="com.yourcompany.hibernate.UserService">
<property name="userDao">
<ref bean="UserDAO" />
</property>
</bean>
</property>
</bean>
8. POJO打印与测试
BaseObject.java
package com.yourcompany.hibernate;
import java.io.Serializable;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
public class BaseObject extends ActionForm implements Serializable {
public static final Log log = LogFactory.getLog(BaseObject.class);
public String toString() {
return ToStringBuilder.reflectionToString(this,
ToStringStyle.MULTI_LINE_STYLE);
}
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
9. 单元测试
继承 TestCase
public void testAdd() {
ApplicationContext ctx =new FileSystemXmlApplicationContext("D:\\wwwroot\\SSH\\WebRoot\\WEBINF\\
applicationContext.xml");
//new ClassPathXmlApplicationContext("springConfig.xml");
IUserService userService = (IUserService) ctx.getBean("UserService");
assertNotNull( "userService is NULL!", userService );
User user = new User();
user.setUsername("luo");
userService.save(user);
List list=userService.findByProperty("username",user.getUsername());
User user01=(User)list.get(0);
assertEquals(user01.getUsername(),"luo");
user01.setPassword("123456");
user01.setEmail("beauty2001@163.com");
user01.setBirthday("1980-8-8");
user01.setIntro("I love you!");
userService.attachDirty(user01);
userService.delete(user01);
}
chainmobile学习
1. 组织结构
struts定义UI相关的action和form
po定义pojo及相关的映射文件
filter定义相关的过滤器
dao 定义相关的dao接口与实现
business定义相关的业务逻辑接口与实现
调用流程
2. web.xml
定义了过滤器和struts配置
3. 过滤器
过滤器方法的定义
第一层过滤 对全站进行编码控制
public void doFilter(ServletRequest srequest, ServletResponse sresponse,FilterChain chain) {
try{
//编码
srequest.setCharacterEncoding("GBK");
//继续请求
chain.doFilter(srequest, sresponse);
}catch(Exception e){
e.printStackTrace();
}
}
第二层控制 判断用户是否有进入系统的权限
Struts action
Action form spring注入
Business接口dao接口
public void doFilter(ServletRequest srequest, ServletResponse sresponse,FilterChain chain) {
try {
HttpServletRequest requst = (HttpServletRequest) srequest;
HttpServletResponse response = (HttpServletResponse) sresponse;
HttpSession session = requst.getSession();
//从session从取出操作员对象,如果为空说明没有登录,将其转到登录页面.
Toperator operator = (Toperator) session.getAttribute("operator");
if (operator == null) {
response.sendRedirect("/chinamobile/index.html");
} else {
chain.doFilter(srequest, sresponse);
}
} catch (Exception e) {
e.printStackTrace();
}}
第三层控制 判断用户是否是管理员
public void doFilter(ServletRequest srequest, ServletResponse sresponse,FilterChain chain) {
try {
HttpServletRequest requst = (HttpServletRequest) srequest;
HttpServletResponse response = (HttpServletResponse) sresponse;
HttpSession session = requst.getSession();
//从session中取得操作员
Toperator operator = (Toperator) session.getAttribute("operator");
String ad=operator.getIsAdmin().toString();
//如果是普通业务员,则无此操作权限
if (operator == null || ad.equals("0")) {
response.sendRedirect("/chinamobile/web/main.jsp");
} else {
chain.doFilter(srequest, sresponse);
}
} catch (Exception e) {
e.printStackTrace();
}}
web.xml中配置
 <filter>
<filter-name>encodingfilter</filter-name>
<filter-class>filter.EncodingFilter</filter-class>//过滤器对映的类
</filter>
<filter-mapping>
<filter-name>encodingfilter</filter-name>
<url-pattern>/*</url-pattern>//对那些资源进行过滤
</filter-mapping>
struts-config.xml定义action,actionForm,及数据转发
action类中
/*这个地方是用spring的关键所在
* 通过FileSystemXmlApplicationContext类得到spring配置文件
* 通过ApplicationContext得到应用程序上下文context.
* 用getBean(类对象名)方法即可得到业务层对象
* 直接用接口类就可以调用相关方法.
*/
具体代码示例:
ApplicationContext context=new
FileSystemXmlApplicationContext("C:\\eclipse\\workspace\\chinamobile\\src\\applicationContext.xml");
IOperator dooperator=(IOperator)context.getBean("operatorservice");
//Ioperator 为业务层接口 实现由spring托管注入
业务层对象
这里通过注入dao层实现,从而实现业务层对持久层的调用
具体代码示例:
//数据访问层operatordao受理业务对象OperatorImp ,由spring注入(托管)
<bean id="operatorservice" class="business.OperatorImp">
<property name="operator">
<ref bean="operatordao"/>
</property>
</bean>
//数据访问层注入sessionFactory,实现持久化
具体代码示例:
<bean id="operatordao" class="dao.OperatorDAOImp">
<property name="factory">
<ref bean="MySessionFactory"/>
</property>
</bean>
sessionFactory 与事物提交
private SessionFactory factory;
//增加操作
public boolean addOperator(Toperator operator) {
Session session=factory.openSession();
Transaction ts=session.beginTransaction();
session.save(operator);
ts.commit();
boolean isok=ts.wasCommitted();
session.close();
return isok;
}
public boolean setMoney(Tcharge charge) {
boolean isok=true;
Session session=factory.openSession();
Transaction ts=session.beginTransaction();
System.out.println(charge.getChargeCode());
Connection conn=session.connection();
try {
Statement state = conn.createStatement();
int i=state.executeUpdate("update TCHARGE set
charge="+charge.getCharge()+" where charge_code='"+charge.getChargeCode()+"'");
if(i==0){
isok=false;
}
} catch (SQLException e) {
e.printStackTrace();
}
ts.commit();
session.close();
return isok;
spring注入spring注入spring注入
业务层接口
业务层实现
数据访问层接口
数据访问层实现sessionFactory
数据访问层实现
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics