spring4+hibernate4+struts2整合实例
spring4+hibernate4+struts2整合实例
liuhuics10 发表于2年前
spring4+hibernate4+struts2整合实例
  • 发表于 2年前
  • 阅读 658
  • 收藏 14
  • 点赞 0
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

项目的整体结构如下:

项目用到的所有jar包如下:


项目所有的类和文件如下:

1.src/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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop  
          http://www.springframework.org/schema/aop/spring-aop.xsd
           http://www.springframework.org/schema/tx  
     http://www.springframework.org/schema/tx/spring-tx.xsd " >
       
    <context:annotation-config ></context:annotation-config >
    <tx:annotation-driven transaction-manager ="transactionManager" />
   
     
      <bean id = "userService" class= "service.UserServiceImpl">
      </bean >
     
      <bean id = "userDao" class= "dao.UserDaoImpl">
      </bean >
     
      <bean id = "userAction" class= "action.UserAction">
      </bean >
     
      <bean id = "dataSource" class= "org.apache.commons.dbcp.BasicDataSource" >
          <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= "*******"/>
      </bean >
      <bean id = "transactionManager" 
         class = "org.springframework.orm.hibernate4.HibernateTransactionManager" > 
      <property name = "sessionFactory" ref= "sessionFactory" />
      </bean >
     
      <bean id = "sessionFactory" class= "org.springframework.orm.hibernate4.LocalSessionFactoryBean" > 
        <property name = "dataSource" ref= "dataSource" /> 
        <property name = "hibernateProperties">  
            <props > 
                <prop key= "hibernate.dialect" >org.hibernate.dialect.MySQLDialect </prop > 
                <prop key = "hibernate.show_sql"> true</ prop>
                <prop key = "hibernate.hbm2ddl.auto"> update</ prop>  
                <prop key = "hibernate.format_sql"> true</ prop>  
            </props > 
        </property >
       
        <property name = "packagesToScan">  
            <list > 
                <value >entity </value > 
            </list > 
        </property >   
    </bean > 
         <!-- 配置HibernateTemplate Bean -->
    <bean id = "hibernateTemplate" class= "org.springframework.orm.hibernate4.HibernateTemplate" >
      <property name = "sessionFactory" ref= "sessionFactory" ></property >
    </bean >
     
</ beans>

2.src/log4j.properites:

### 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 {1}:%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

3.src/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 >
     <package name = "reg" extends = "struts-default">
           <action name = "user" class = "action.UserAction">
               <result name = "success" >/ reg/regSuccess.jsp </ result>
               <result name = "input" >/ reg/regFail.jsp </ result>
           </action >
         </package >
 </ struts >

4.WebContent/reg/reg.jsp:

<%@ page language = "java" contentType= "text/html; charset=utf-8"
    pageEncoding= "utf-8"%>
<! 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">
< title> Insert title here</ title>
</ head>
< body>
      <form action = "user.action" method= "post">< br>
            uname: <input type = "text" name= "uname"/>< br>
            pwd:< input type= "password" name = "pwd"/>< br>
            repwd< input type= "password" name = "repwd"/>< br>
           提交: <input type = "submit" value= "提交 "/>
      </form >
</ body>
</ html>

5.WebContent/reg/regSuccess.jsp:

<%@ page language = "java" contentType= "text/html; charset=utf-8"
    pageEncoding= "utf-8"%>
<! 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">
< title> Insert title here</ title>
</ head>
< body>
      <h1 >注册成功 </h1 >
</ body>
</ html>

6.WebContent/reg/regFail.jsp:

<%@ page language = "java" contentType= "text/html; charset=utf-8"
    pageEncoding= "utf-8"%>
<! 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">
< title> Insert title here</ title>
</ head>
< body>
      <h1 >注册失败:用户名重复 </h1 >
</ body>
</ html>

7.WEB-INF/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_3_0.xsd" id= "WebApp_ID" version = "3.0">
  < display-name >SSHJunior </display-name >
  < welcome-file-list >
    <welcome-file >index.html </welcome-file >
    <welcome-file >index.htm </welcome-file >
    <welcome-file >index.jsp </welcome-file >
    <welcome-file >default.html </welcome-file >
    <welcome-file >default.htm </welcome-file >
    <welcome-file >default.jsp </welcome-file >
  </ welcome-file-list >
  < 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 >
 
  < listener>
        < listener-class> org.springframework.web.context.ContextLoaderListener </listener-class >
    </listener >
    <context-param >
      <param-name >contextConfigLocation </param-name >
            <!-- 默认找/WEB-INF/applicationContext.xml -->
      <param-value >classpath:beans.xml </param-value >
    </context-param >
</ web-app>

8.entity.User.jsp:

package entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class User {
     private int id;
     private String uname;
     private String pwd;
     @Id
     @GeneratedValue
     public int getId() {
          return id;
     }
     public void setId(int id) {
          this.id = id;
     }
     public String getUname() {
          return uname;
     }
     public void setUname(String uname) {
          this.uname = uname;
     }
     public String getPwd() {
          return pwd;
     }
     public void setPwd(String pwd) {
          this.pwd = pwd;
     }
    
}

9.service.UserService.java:

package service;

import entity.User;

public interface UserService {

      boolean exists(User user);

      void add(User user);

}

10.service.UserServiceImpl.java:

package service;

import javax.annotation.Resource;
import org.springframework.transaction.annotation.Transactional ;

import dao.UserDao;
import entity.User;

public class UserServiceImpl implements UserService {
     
      private UserDao userDao;
     
     

      public UserDao getUserDao() {
            return userDao;
     }
     
      @Resource
      public void setUserDao(UserDao userDao) {
            this. userDao = userDao;
     }

      /* (non-Javadoc)
      * @see service.UserService#exists(entiey.User)
      */
      @Override
      public boolean exists(User user) {
            return userDao.checkUserExistsByUname( user.getUname());
        
     }

      /* (non-Javadoc)
      * @see service.UserService#add(entiey.User)
      */
      @Override
      @Transactional
      public void add(User user) {
            userDao.save( user); 
     }
}

11.dao.UserDao.java:

package dao;

import entity.User;

public interface UserDao {

      boolean checkUserExistsByUname(String uname);

      void save(User user);

}

12.dao.UserDaoImpl.java:

package dao;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.orm.hibernate4.HibernateTemplate;
import entity.User;
public class UserDaoImpl implements UserDao {
     private HibernateTemplate hibernateTemplate;
    
    
     public HibernateTemplate getHibernateTemplate() {
          return hibernateTemplate;
     }
    
     @Resource
     public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
          this.hibernateTemplate = hibernateTemplate;
     }
    
    
     /* (non-Javadoc)
     * @see dao.UserDao#checkUserExistsByUname(java.lang.String)
     */
     @Override
     public boolean checkUserExistsByUname(String uname){
          //String sql = "select count(*) from User where uname = '"+uname+"'";
          String sql = "from User where uname = '"+uname+"'";
          List list = (List) hibernateTemplate.find(sql);
          if(list!=null&&list.size()>0){
               return true;
          }
         
         return false;
     }
    
     /* (non-Javadoc)
     * @see dao.UserDao#save(entiey.User)
     */
     @Override
     public void save(User user){
          hibernateTemplate.save(user);
     }
}

13.action.UserAction.java:

package action;


import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;

import com.opensymphony.xwork2.ActionSupport;

import entity.User;
import service.UserService;
@Scope( "prototype")
public class UserAction extends ActionSupport {
     
      private String uname;
      private String pwd;
      private String repwd;
      private UserService userService;
     

      public String getUname() {
            return uname;
     }

      public void setUname(String uname) {
            this. uname = uname;
     }

      public String getPwd() {
            return pwd;
     }

      public void setPwd(String pwd) {
            this. pwd = pwd;
     }


      public String getRepwd() {
            return repwd;
     }

      public void setRepwd(String repwd) {
            this. repwd = repwd;
     }

      public UserService getUserService() {
            return userService;
     }
     
      @Resource
      public void setUserService(UserService userService) {
            this. userService = userService;
     }

      @Override
      public String execute() throws Exception {
           User user = new User();
            user.setUname( uname);
            user.setPwd( pwd);
            if( userService.exists( user)){
                 return INPUT;
           }
            userService.add( user);
            return SUCCESS;
     }
}


共有 人打赏支持
粉丝 5
博文 96
码字总数 39010
×
liuhuics10
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: