asdtiang的博客 感谢blogjava提供的博客交流平台

struts2.1.8 +spring +hibernate整合及DWR异步提交

Posted on 2010-04-12 13:07 asdtiang 阅读(1066) 评论(0)  编辑  收藏 所属分类: java ee
配置文件图:至于包导入的问题网上搜下:

web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation
="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    
<display-name>Struts Blank</display-name>
    
<servlet>
        
<servlet-name>dwr</servlet-name>
        
<!-- 指定Servlet的实现类 -->
        
<servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
        
<!-- 指定处于开发阶段 -->
        
<init-param>
            
<param-name>debug</param-name>
            
<param-value>true</param-value>
        
</init-param>
    
</servlet>
    
<!-- 指定DWR的核心Servlet拦截的URL -->
    
<servlet-mapping>
        
<servlet-name>dwr</servlet-name>
        
<url-pattern>/dwr/*</url-pattern>
    
</servlet-mapping>


    
<!-- 验证码 -->
    
<servlet>
        
<servlet-name>imagecodeservlet</servlet-name>
        
<servlet-class>cn.com.enorth.util.imgcode.ImageCodeServlet</servlet-class>
        
<init-param>
            
<param-name>type</param-name>
            
<param-value>1</param-value>
        
</init-param>
        
<init-param>
            
<param-name>length</param-name>
            
<param-value>4</param-value>
        
</init-param>
    
</servlet>
    
<servlet-mapping>
        
<servlet-name>imagecodeservlet</servlet-name>
        
<url-pattern>/imgcode</url-pattern>
    
</servlet-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>
    
<context-param>
        
<param-name>contextConfigLocation</param-name>
        
<param-value>/WEB-INF/applicationContext.xml</param-value>
    
</context-param>
    
<listener>
        
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    
</listener>
    
<context-param>
        
<param-name>webAppRootKey</param-name>
        
<param-value>trip.root</param-value>
    
</context-param>

    
<context-param>
        
<param-name>log4jConfigLocation</param-name>
        
<param-value>/WEB-INF/classes/log4j.properties</param-value>
    
</context-param>
    
<listener>
        
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    
</listener>
    
<welcome-file-list>
        
<welcome-file>index.jsp</welcome-file>
    
</welcome-file-list>

</web-app>
log4j.properties
log4j.rootLogger=INFO, stdout, logfile
log4j.logger.com.albertsong
=DEBUG

log4j.appender.stdout
=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout
=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern
=%%p [%c] - %m%n

log4j.appender.logfile
=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File
=${trip.root}/WEB-INF/log/trip.log
log4j.appender.logfile.MaxFileSize
=512KB
# Keep three backup files.
log4j.appender.logfile.MaxBackupIndex
=3
# Pattern to output: date priority [category] 
- message
log4j.appender.logfile.layout
=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern
=%%p [%c] - %m%n

**为自己的包名
applicationContext.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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation
="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">


    
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method
="close">
        
<property name="driverClass" value="com.mysql.jdbc.Driver" />
        
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/trip" />
        
<property name="user" value="root" />
        
<property name="password" value="asdtiang" />
    
</bean>
    
<bean id="sessionFactory"
        class
="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        
<property name="dataSource" ref="dataSource" />
          
        
<property name="mappingResources">
            
<list>
<!-- **改为自己的路径-->
                
<value>**/User.hbm.xml
                
</value>
                
<value>**/mysql.hbm.xml
                
</value>            
            
</list>
        
</property>
        
        
<property name="hibernateProperties">
            
<props>
                
<prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                
</prop>
                
<prop key="show_sql">true</prop>
            
</props>
        
</property>
    
</bean>
    
<bean id="userServer" class="**.UserServer">
        
<property name="sessionFactory" ref="sessionFactory" />
    
</bean>
    
<bean name="registerAction" class="**.RegisterAction">
        
<property name="userServer" ref="userServer" >
        
</property>
    
</bean>
    
</beans>
dwr.xml
<?xml version="1.0" encoding="UTF-8"?>

<!-- START SNIPPET: dwr -->
<!DOCTYPE dwr PUBLIC 
    "-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN" 
    "http://www.getahead.ltd.uk/dwr/dwr10.dtd"
>

<dwr>
    
<allow>
        
<create creator="new" javascript="validator">
            
<param name="class" value="org.apache.struts2.validators.DWRValidator"/>
        
</create>
        
<convert converter="bean" match="com.opensymphony.xwork2.ValidationAwareSupport"/>
    
</allow>

    
<signatures>
        
<![CDATA[
        import java.util.Map;
        import org.apache.struts2.validators.DWRValidator;

        DWRValidator.doPost(String, String, Map<String, String>);
        
]]>
    
</signatures>
</dwr>
<!-- END SNIPPET: dwr -->

struts2 action

<action name="checkUser" class="***.RegisterAction" method="checkUserExecute">
            <result name="check" type="stream">
            <param name="contentType">image/jpeg</param>
                <param name="inputName">inputStream</param>
            </result>
</action>

public class RegisterAction extends ActionSupport {
    
private Log log = LogFactory.getLog(RegisterAction.class);
    
private InputStream inputStream;
    
private UserServerInter userServer;
    
private UserDAO dao = new UserDAO();
    
private String userName;

    
public String checkUserExecute() throws Exception {
        
try {
            log.info(userName);
            
if (userServer.exist(userName)) {
                
this.setInputStream(new FileInputStream(new File(
                        ServletActionContext.getServletContext().getRealPath(
                                
"/images/error.jpg"))));
            } 
else {
                
this.setInputStream(new FileInputStream(new File(
                        ServletActionContext.getServletContext().getRealPath(
                                
"/images/ok.jpg"))));
            }

        } 
catch (IOException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }
        
return "check";
    }

    
public InputStream getInputStream() {
        
return inputStream;
    }

    
public void setInputStream(InputStream inputStream) {
        
this.inputStream = inputStream;
    }

    
public UserServerInter getUserServer() {
        
return userServer;
    }

    
public void setUserServer(UserServerInter userServer) {
        
this.userServer = userServer;
    }

    
public String getUserName() {
        
return userName;
    }

    
public void setUserName(String userName) {
        
this.userName = userName;
    }

}



public interface UserServerInter {
    
public boolean exist(String username);

}


public class UserServer extends HibernateDaoSupport implements UserServerInter{
    @SuppressWarnings(
"unchecked")
    
public boolean exist(String username) {
        System.out.println(username);
        List ls 
= getHibernateTemplate().findByNamedQuery("userIsExist",  username);///这个地方使用mysql.hbm.xml中配置的HQL语句
        
return ls.size() == 1 ? true : false;
    }

}

<%@ page language="java" import="java.util.*;" pageEncoding="utf-8"%>

<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sx" uri="/struts-dojo-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    
<head>
        
<title>My JSP 'index.jsp' starting page</title>
    
</head>

    
<body>
        
<script type="text/javascript">
    
function changeValidateCode(obj) {
        obj.src = "checkUser.action?userName=" +document.getElementById("userName").value;
    }
</script>
        
<!--为异步提交定义需要的url-->
        
<s:url id="userUrl" action="checkUser" />
        
<s:textfield id="userName" name="userName" maxlength="10" theme="simple"
            onblur
="changeValidateCode(img)"/>
        
<!--这个是指示器,当请求未完成时显示这个图片-->
        
<img id="img" src="images/ok.jpg" align="center" />
        
<!--这个是显示信息的目标-->
        
<span id="idInfo">请输入你要注册的用户名</span>
    
</body>
</html>

hibernate  mysql.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>

<hibernate-mapping package="com.albertsong.bitrac.dao.query">
<!-- 
    <sql-query name="userIsExist">
        <return alias="userIsExist" class="org.jinjin.trip.User" />
        select * from user u where u.username=?
    </sql-query>
     
-->
    
<query name="userIsExist">
    
<![CDATA[
      from User where username=?
      
]]>
    
</query>
</hibernate-mapping>
user.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    
<class name="org.jinjin.trip.mysql.User" table="user" catalog="trip">
        
<id name="id" type="java.lang.String">
            
<column name="id" />
            
<generator class="uuid.hex" />
        
</id>
        
<property name="password" type="java.lang.String">
            
<column name="password" length="50" />
        
</property>
        
<property name="username" type="java.lang.String">
            
<column name="username" length="25" not-null="true" unique="true" />
        
</property>
        
<property name="email" type="java.lang.String">
            
<column name="email" not-null="true" unique="true" />
        
</property>
    
</class>
</hibernate-mapping>
spring和hibernate的另外一种整合方式:通过hibernate的配置文件来整合,这样要好的多:个人感觉
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
   
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
   
    
</bean>  
配置文件和以前一样在,src目录下,其实最后也到web-inf/class下面去了。这样hibernate的配置文件就不用写到spring的配置文件里了。挺好。


天苍苍,野茫茫,风吹草底见牛羊

只有注册用户登录后才能发表评论。


网站导航:
 

posts - 80, comments - 24, trackbacks - 0, articles - 32

Copyright © asdtiang

asdtiang的博客 PaidMailz
点击广告网赚A(每天4个广告,每个0.0025美元,一个搜索广告0.03美元)