spring 整合 mybatis,struts2 整合 spring

来源:互联网 发布:数据库 书名号 编辑:程序博客网 时间:2024/05/17 22:40

1、项目引用 jar 列表

#
# --spring-framework-3.0.6.RELEASE--
#
org.springframework.aop-3.0.6.RELEASE.jar
org.springframework.asm-3.0.6.RELEASE.jar
org.springframework.aspects-3.0.6.RELEASE.jar
org.springframework.beans-3.0.6.RELEASE.jar
org.springframework.context-3.0.6.RELEASE.jar
org.springframework.context.support-3.0.6.RELEASE.jar
org.springframework.core-3.0.6.RELEASE.jar
org.springframework.expression-3.0.6.RELEASE.jar
org.springframework.instrument-3.0.6.RELEASE.jar
org.springframework.instrument.tomcat-3.0.6.RELEASE.jar
org.springframework.jdbc-3.0.6.RELEASE.jar
org.springframework.jms-3.0.6.RELEASE.jar
org.springframework.orm-3.0.6.RELEASE.jar
org.springframework.oxm-3.0.6.RELEASE.jar
org.springframework.test-3.0.6.RELEASE.jar
org.springframework.transaction-3.0.6.RELEASE.jar
org.springframework.web-3.0.6.RELEASE.jar
org.springframework.web.portlet-3.0.6.RELEASE.jar
org.springframework.web.servlet-3.0.6.RELEASE.jar
org.springframework.web.struts-3.0.6.RELEASE.jar
#
# --mybatis-spring--
#
mybatis-spring-1.0.1.jar
#
# --mybatis about--
#
# asm-1.5.3.jar
# cglib-2.1_3.jar
# commons-logging-1.1.1.jar
# log4j-1.2.13.jar
# mybatis-3.0.2.jar
# mybatis-3.0.2-sources.jar
# mybatis-generator-core-1.3.0.jar
# slf4j-api-1.5.8.jar
# slf4j-log4j12-1.5.8.jar

# --struts-2.2.3--
#
asm-3.1.jar
asm-commons-3.1.jar
asm-tree-3.1.jar
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
commons-lang-2.5.jar
freemarker-2.3.16.jar
javassist-3.11.0.GA.jar
ognl-3.0.1.jar
struts2-core-2.2.3.jar
xwork-core-2.2.3.jar


# --struts2-spring--
#
struts2-spring-plugin-2.2.3.jar
#
# postgresql-8.4
#
postgresql-8.4-702.jdbc4.jar
#
# log4j-1.2.16
#
commons-logging-1.1.1.jar
commons-logging-adapters-1.1.1.jar
commons-logging-api-1.1.1.jar

2、jndi配置

<?xml version="1.0" encoding="UTF-8"?>
<context>
    <Resource 
        name="jdbc/hss" 
        type="javax.sql.DataSource"
        driverClassName="org.postgresql.Driver" 
        url="jdbc:postgresql://localhost:5432/mydb"
        validationQuery="select version()"
        username="postgres" 
        password="123456"
        maxWait="50"  
        maxIdle="2"
        maxActive="4" />
</context>


3、spring-config.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-3.0.xsd">
<!-- 使用JNDI数据源 -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/hss" />
</bean>
<!-- 启用SPRING默认事务管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- SPRING编程事务管理 -->
<bean id="txTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="transactionManager"></property>
        <property name="propagationBehaviorName" value="PROPAGATION_REQUIRED"></property>
    </bean>
<!-- 自动扫描指定目录中的xxxmapper.xml文件,生成类似tbUserMapper的mapper对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.guorui.mybatis.dao" />
</bean>
<!-- 供开发人员使用的后台service服务对象 -->
<bean id="fooService" class="com.guorui.app.FooService">
<property name="tbUserMapper" ref="tbUserMapper" />
<property name="txTemplate" ref="txTemplate" />
</bean>

</beans>

4、得到的service

package com.guorui.app;


import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;


import com.guorui.mybatis.dao.TbUserMapper;
import com.guorui.mybatis.model.TbUser;


public class FooService {


private TransactionTemplate txTemplate;
private TbUserMapper tbUserMapper;


public void setTbUserMapper(TbUserMapper tbUserMapper) {
this.tbUserMapper = tbUserMapper;
}


public void setTxTemplate(TransactionTemplate txTemplate) {
this.txTemplate = txTemplate;
}

// spring的手动事务管理
public void doSomeBusinessStuff_man(final Long userId) {
txTemplate.execute(new TransactionCallback<Boolean>(){
          public Boolean doInTransaction(TransactionStatus status){
             try {
             TbUser record = new TbUser();
             record.setTu002("0003");
             record.setTu003("郭一鸣22"+userId);
             FooService.this.tbUserMapper.insert(record);
             System.out.println(record.getTu001());
             } catch (Exception e) {
                 status.setRollbackOnly();//
                 e.printStackTrace();
                 return false;
             }
             return true;
          }
      });
}
// spring的自动事务管理
public void doSomeBusinessStuff_auto(final Long userId) {
             TbUser record = new TbUser();
             record.setTu002("0003");
             record.setTu003("郭一鸣22"+userId);
             FooService.this.tbUserMapper.insert(record);
             System.out.println(record.getTu001());


}
}

5、在servlet中调研spring中的service

package com.guorui.app;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;


import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


import com.guorui.mybatis.dao.TbUserMapper;


public class GuoTestBS extends HttpServlet {

private static final long serialVersionUID = 1L;


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
queryTest(response);
}


private void queryTest(HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter writer = response.getWriter();
ServletContext application;     
        WebApplicationContext wac;     
        application = getServletContext();     
        wac = WebApplicationContextUtils.getWebApplicationContext(application);
        FooService fooService = (FooService)wac.getBean("fooService");
        fooService.doSomeBusinessStuff_man(Long.valueOf(2));
writer.print(Calendar.getInstance().toString());
writer.close();
}


}

===============================开始struts整合spring============================================

6、在web.xml里面配置struts2用到的核心过滤器。

  1. <filter>  
  2.     <filter-name>struts2</filter-name>  
  3.     <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>  
  4. </filter>  
  5. <filter-mapping>  
  6.     <filter-name>struts2</filter-name>  
  7.     <url-pattern>/*</url-pattern>  
  8. </filter-mapping>  


7、测试struts2和spring整合对不对? 
写一个jsp页面index.jsp来测试: 

Html代码  收藏代码
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
  2. <%@ taglib prefix="s" uri="/struts-tags" %>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. <title>Insert title here</title>  
  8. </head>  
  9. <body>  
  10.     <s:form action="Login" method="post">  
  11.         <s:textfield name="userName" label="userName"></s:textfield>  
  12.         <s:password name="password" label="password"></s:password>  
  13.         <s:submit label="submit"></s:submit>  
  14.     </s:form>  
  15. </body>  
  16. </html>  

第二个jsp页面result.jsp来测试结果: 

Html代码  收藏代码
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
  2. <%@ taglib prefix="s" uri="/struts-tags" %>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. <title>Insert title here</title>  
  8. </head>  
  9. <body>  <s:property value="result"/>
  10.  
  11. </body>  
  12. </html>  


8、struts2的action

package com.guorui.struts.action;


import com.guorui.app.FooService;
import com.opensymphony.xwork2.ActionSupport;


public class LoginAction extends ActionSupport {

private static final long serialVersionUID = -829916501012605182L;
// input
private String userName;
private String password;
// output
private String result;
// tools
private FooService fooService;


public void setFooService(FooService fooService) {
this.fooService = fooService;
}
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 getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
@Override
public String execute() throws Exception {
if(fooService.doSomeBusinessStuff_man(Long.valueOf(100))) {
result = "goooooood";
return SUCCESS;
} else {
result = "nooooooot";
return INPUT;
}
}
}

9、在spring-config..xml里面配置: 

<bean id="loginActionBean" class="com.guorui.struts.action.LoginAction" scope="prototype">
<property name="fooService" ref="fooService"></property>
</bean>

10、在struts.xml里面配置: 
Xml代码  收藏代码
  1. <package name="struts2" extends="struts-default">  
  2.     <action name="Login" class="loginActionBean">  // 这里的class就是上面的bean id
  3.         <result name="success">/result.jsp</result>  
  4.         <result name="input">/login.jsp</result>  
  5.     </action>  
  6. </package>  

原创粉丝点击