S2S3H4 整合程式碼示例

劍握在手發表於2014-01-01

主要程式碼列舉:

 

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>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        <!-- default: /WEB-INF/applicationContext.xml -->
    </listener>

    <context-param>
        <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>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
   
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
   
     <filter>
        <filter-name>openSessionInView</filter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
    </filter>
   
    <filter-mapping>
        <filter-name>openSessionInView</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
   
    <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>

jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/world
jdbc.username=root
jdbc.password=mysql

 

log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c:%L - %m%n

### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=warn, stdout

#log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug

### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug

### log just the SQL
#log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
#log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug

### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug

### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug

### log cache activity ###
#log4j.logger.org.hibernate.cache=debug

### log transaction activity
#log4j.logger.org.hibernate.transaction=debug

### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug

### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
    "http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="true"/>

    <package namespace="" name="registration" extends="struts-default">

        <action name="u" class="test.action.UserAction">

            <result name="success">/register.jsp</result>
            <result name="fail">/registerFail.jsp</result>
            <result name="list">/userlist.jsp</result>
            <result name="load">/user.jsp</result>

        </action>
    </package>


</struts>
   

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"
    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="test" />

    <!--
        <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>test.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 * test.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>

 

jar包(含多餘)

antlr-2.7.7.jar
aopalliance-1.0.jar
asm-3.3.jar
asm-commons-3.3.jar
asm-tree-3.3.jar
aspectjrt.jar
aspectjweaver.jar
cglib-nodep-2.2.jar
commons-dbcp-1.4.jar
commons-fileupload-1.3.jar
commons-io-2.0.1.jar
commons-lang3-3.1.jar
commons-logging-1.1.3.jar
commons-pool-1.6.jar
commons-pool2-2.0.jar
dom4j-1.6.1.jar
freemarker-2.3.19.jar
hibernate-commons-annotations-4.0.2.Final.jar
hibernate-core-4.2.8.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.11.0.GA.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
log4j-1.2.17.jar
mysql-connector-java-commercial-5.1.27-bin.jar
ognl-3.0.6.jar
slf4j-log4j12-1.7.5.jar
spring-aop-3.2.5.RELEASE.jar
spring-aspects-3.2.5.RELEASE.jar
spring-beans-3.2.5.RELEASE.jar
spring-build-src-3.2.5.RELEASE.jar
spring-context-3.2.5.RELEASE.jar
spring-context-support-3.2.5.RELEASE.jar
spring-core-3.2.5.RELEASE.jar
spring-expression-3.2.5.RELEASE.jar
spring-instrument-3.2.5.RELEASE.jar
spring-instrument-tomcat-3.2.5.RELEASE.jar
spring-jdbc-3.2.5.RELEASE.jar
spring-jms-3.2.5.RELEASE.jar
spring-orm-3.2.5.RELEASE.jar
spring-oxm-3.2.5.RELEASE.jar
spring-struts-3.2.5.RELEASE.jar
spring-test-3.2.5.RELEASE.jar
spring-tx-3.2.5.RELEASE.jar
spring-web-3.2.5.RELEASE.jar
spring-webmvc-3.2.5.RELEASE.jar
spring-webmvc-portlet-3.2.5.RELEASE.jar
struts2-core-2.3.15.3.jar
struts2-spring-plugin-2.3.15.3.jar
xwork-core-2.3.15.3.jar

 

檔案目錄結構

專案結構

 

UserDaoImpl

package test.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import test.dao.UserDao;
import test.model.User;

@Component("userDao")
public class UserDaoImpl implements UserDao {

    private SessionFactory sessionFactory;
   
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    @Resource
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public int save(User u) {
        Session s = sessionFactory.getCurrentSession();
        if(!this.checkUserExistsWithName(u.getName())) {
            s.save(u);
            return 0;
        }
        return -1;
    }

    @Override
    public boolean checkUserExistsWithName(String username) {
        Session s = sessionFactory.getCurrentSession();
        List<User> users = (List<User>)s.createQuery("from User u where u.name = '" + username + "'").list();
        if(users!=null&&users.size()!=0)
            return true;
       
        return false;
    }

    @Override
    public List<User> getUsers() {
        Session s = sessionFactory.getCurrentSession();
        return (List<User>)s.createQuery("from User").list();
       
    }


}

 

User

package test.model;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import test.vo.UserRegisterInfo;

@Entity
public class User {
    private int id;
    private String name;
    private Date birthday;
    private float money;

    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }
    public float getMoney() {
        return money;
    }
    public String getName() {
        return name;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public void setId(int id) {
        this.id = id;
    }
    public void setMoney(float money) {
        this.money = money;
    }
    public void setName(String name) {
        this.name = name;
    }
   
    public User() {}
    public User(UserRegisterInfo user) {
        this.name = user.getName();
        this.money = user.getMoney();
        this.birthday = user.getBirthday();
    }
}

UserManagerImpl

package test.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import test.dao.UserDao;
import test.model.User;
import test.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;
    }

    @Transactional
    public int add(User u) throws Exception {
        return userDao.save(u);

    }

    @Transactional
    public List<User> getUsers() {
        // TODO Auto-generated method stub
        return userDao.getUsers();
    }

}

UserAction

package test.action;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import test.model.User;
import test.service.UserManager;
import test.vo.UserRegisterInfo;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@Component("u")
@Scope("prototype")
public class UserAction extends ActionSupport implements ModelDriven<UserRegisterInfo>  {

    private UserRegisterInfo userInfo = new UserRegisterInfo();
   
    private UserManager userManager;
   
    private String result;
   
    private List<User> users;
   
    public List<User> getUsers() {
        return users;
    }

    public String execute() throws Exception {
        System.out.println(userInfo==null);
        int ret = userManager.add(new User(userInfo));
        if(ret==0) {
            result = "新增成功";
        }else {
            result = "新增失敗";
        }
       
        return "success";
    }

    public String add() throws Exception {
        int ret = userManager.add(new User(userInfo));
        if(ret==0) {
            result = "新增成功";
        }else {
            result = "新增失敗";
        }
       
        return "success";
    }

    public String list() {
        this.users = this.userManager.getUsers();
        return "success";
    }
   
    public void setUsers(List<User> users) {
        this.users = users;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public UserRegisterInfo getUserInfo() {
        return userInfo;
    }

    public void setUserInfo(UserRegisterInfo userInfo) {
        this.userInfo = userInfo;
    }
   
   
    public UserManager getUserManager() {
        return userManager;
    }
    @Resource(name="userManager")
    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    public UserRegisterInfo getModel() {
        return userInfo;
    }
}

 

 

register.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'index.jsp' starting page</title>

  </head>
 
  <body>
 
      <s:property value="result"/>
 
    <form method="post" action="r/u!add">
        使用者名稱:<input type="text" name="name"><br>
        密碼:<input type="password" name="password"><br>
        生日:<input type="text" name="birthday"><br>
        錢:<input type="text" name="money"><br>
       
        <input type="submit" value="提交"/>
    </form><br>
  <% String context = request.getContextPath(); %>
  <a href="<%=context %>/r/u?name=a">hhhhh</a>
 
      <input type="button" value="list" onclick="javascript:window.location.href='./r/u!list'">
 
      <s:debug>debug</s:debug>
    <s:iterator value="users">
        <s:property value="id"/>
        <s:property value="name"/>
        <s:property value="birthday"/>
        <br>
    </s:iterator>
  </body>
</html>

相關文章