分享

SSH2框架整合(Struts2.1.6+hibernate3.3.2+spring2.5.6)(spring+hibernate+servlet的源代码在文章底部)

 horse_home 2014-06-08

其实整合也不是很麻烦,大家只要有个整合的思路就可以了,这里我个人认为,整合的话先

spring >>  hibernate  >> struts    这样一步步下去比较容易点(纯属我个人认为,不认同的也没关系,顺序随便大家怎么样加入都是没有关系的,不废话了,看下面。。。。。。有兴趣的可以加入QQ群号:227861629  ,验证信息就写:啊强介绍加入。。。)

---------------------------------------------------------------------------------------------------------------------------------

设计好数据库(也不一定要的,那个就先不说了),这里使用mysql数据库,相关信息如下(数据库名:ssh2_demo,表就一张userinfo

 

1.先是建立一个web项目,我这里命名为  SSH2_DEMO_1 (大家喜欢随便怎么命名都ok)

 

2. 先加入Spring的需要的jarspring的配置文件xml,如下图所示(没有可以到官网去下载)

Spring需要的jar: http://pan.baidu.com/share/link?shareid=309734&uk=4245483071


然后在项目的web.xml里面加入spring的信息

 

<context-param>

     <param-name>contextConfigLocation</param-name>

     <param-value>classpath:applicationContext.xml</param-value>

</context-param>

<listener>

  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

至此,spring算是ok  

---------------------------------------------------------------------------------------------------------------------------------3.加入hibernate的需要的jar,如下图所示(没有可以到官网去下载,hibernate也是有配置的xml的,不过我这里整合到applicationContext.xml里面去了,所有看不到hibernate的那个配置文件hibernate.cfg.xml)  不要少了mysql的驱动啊  

hibernate需要的jar: http://pan.baidu.com/share/link?shareid=121003906&uk=4245483071

mysql 的驱动包    : http://pan.baidu.com/share/link?shareid=309731&uk=4245483071

 


然后在applicationContext.xml 里面加入数据源的配置信息(我这里是用mysql数据库,就要写上对应数据库的方言什么的)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<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/ssh2_demo" />
<property name="username" value="root" />
<property name="password" value="123" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="current_session_context_class">thread</prop>
<prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
</props>
</property>
</bean>

 

到这里执行项目如果没有问题的就继续往下走。。。

 

4.建立实体类  Userinfo.java hibernate的映射文件Userinfo.hbm.xml(命名不要错了  实体类名.hbm.xml)

Userinfo.java

package cn.wzqiang.dto;

 

public class Userinfo {

 

         privateint id;

         privateString username;

         privateString password;

         publicUserinfo() {

         }

         publicUserinfo(String username, String password) {

                   this.username= username;

                   this.password= password;

         }

         publicint getId() {

                   returnthis.id;

         }

         publicvoid setId(int id) {

                   this.id= id;

         }

         publicString getUsername() {

                   returnthis.username;

         }

         publicvoid setUsername(String username) {

                   this.username= username;

         }

         publicString getPassword() {

                   returnthis.password;

         }

         publicvoid setPassword(String password) {

                   this.password= password;

         }

}        

 Userinfo.hbm.xml

 

<?xml version="1.0"encoding="utf-8"?> 

<!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN" 

"http://hibernate./hibernate-mapping-3.0.dtd">

<hibernate-mapping> 

   <class name="cn.wzqiang.dto.Userinfo"table="userinfo" catalog="ssh2_demo"> 

       <id name="id" type="java.lang.Integer"> 

           <column name="id" /> 

           <generator class="native" /> 

       </id> 

       <property name="username"type="java.lang.String"> 

           <columnname="username" length="64" /> 

       </property> 

       <property name="password"type="java.lang.String"> 

           <column name="password" length="64" /> 

       </property> 

   </class> 

</hibernate-mapping>

 

 然后在applicationContext.xml加上该信息(红色字体那

<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/ssh2_demo" />

<property name="username" value="root" />

<property name="password" value="123" />

</bean>

<bean id="sessionFactory"

class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<property name="dataSource" ref="dataSource" />

<property name="hibernateProperties">

<props>

<prop key="hibernate.hbm2ddl.auto">update</prop>

<prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>

<prop key="hibernate.show_sql">true</prop>

<prop key="current_session_context_class">thread</prop>

<prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>

</props>

</property>

</bean>

 <property name="mappingResources">

<list>

<value>cn/wzqiang/dto/Userinfo.hbm.xml</value>

</list>

</property>

</bean>

 

5.有了这些自然就要有增删改查这些方法了,编写一个接口UserInfo_dao  写一个Userinfo_impl类实现这个接口

package cn.wzqiang.dao;                   

import java.util.List;                   

import cn.wzqiang.dto.Userinfo;                     

public interface UserInfo_dao {                    

    /** 

     * 用户登录 

     * @param uname , upwd 

     * @return 

     */

    boolean LoginInfo(String uname ,String upwd); 

    /** 

     * 添加信息 

     * @param info 

     * @return 

     */

    boolean AddInfo(Userinfo info); 

                        

    /** 

     * 删除 

     * @param info 

     * @return 

     */

    boolean DeleteInfo(Userinfo info); 

                        

    /** 

     * 修改 

     * @param info 

     * @return 

     */

    boolean UpdateInfo(Userinfo info); 

                        

    /** 

     * 根据ID得到对应的信息 

     * @param id 

     * @return 

     */

    Userinfo QueryInfo(int id); 

                        

    /** 

     * 查询全部 

     * @return 

     */

    List<Userinfo> QueryALLInfo(); 

}

------------------------------------------------------------------------------------------------------------------------------------------------

Userinfo_impl.java

package cn.wzqiang.dao.impl; 


import java.util.ArrayList;

import java.util.List;


import org.hibernate.HibernateException;

import org.hibernate.SessionFactory;


import cn.wzqiang.dao.UserInfo_dao;

import cn.wzqiang.dto.Userinfo;

                   


                   

public class Userinfo_impl implements UserInfo_dao { 

                   

    //注入SessionFactory 

    private SessionFactory sessionFactory; 

    

    public void setSessionFactory(SessionFactory sessionFactory) { 

        this.sessionFactory = sessionFactory; 

    } 

                  

    public boolean AddInfo(Userinfo info) { 

        // TODO Auto-generated method stub 

        try { 

            sessionFactory.getCurrentSession().persist(info); 

            return true; 

        } catch (HibernateException e) { 

            // TODO Auto-generated catch block 

            e.printStackTrace(); 

            return false; 

        } 

                           

    } 

                   

    public boolean DeleteInfo(Userinfo info) { 

        // TODO Auto-generated method stub 

        try { 

            sessionFactory.getCurrentSession().delete(info); 

            return true; 

        } catch (HibernateException e) { 

            // TODO Auto-generated catch block 

            e.printStackTrace(); 

            return false; 

        } 

    } 

                   

    public boolean UpdateInfo(Userinfo info) { 

        // TODO Auto-generated method stub 

        try { 

            sessionFactory.getCurrentSession().merge(info); 

            return true; 

        } catch (HibernateException e) { 

            // TODO Auto-generated catch block 

            e.printStackTrace(); 

            return false; 

        } 

    } 

                   

    public Userinfo QueryInfo(int id) { 

        // TODO Auto-generated method stub 

        Userinfo info = new Userinfo(); 

        info = (Userinfo)sessionFactory.getCurrentSession().createQuery("from Userinfo where id = "+id) .uniqueResult();; 

        return info; 

    } 

                   

    public List<Userinfo> QueryALLInfo() { 

        // TODO Auto-generated method stub 

        List<Userinfo> list = new ArrayList<Userinfo>(); 

        list = sessionFactory.getCurrentSession().createQuery("from Userinfo").list(); 

        return list; 

    } 

                   

    @SuppressWarnings("rawtypes") 

    public boolean LoginInfo(String uname ,String upwd) { 

        // TODO Auto-generated method stub 

        try { 

            List list = sessionFactory.getCurrentSession().createQuery("from Userinfo where username = '"+uname+"' and password = '"+upwd+"'").list(); 

            if(list.size()!=0){ 

                return true; 

            }else{ 

                return false; 

            } 

        } catch (HibernateException e) { 

            e.printStackTrace(); 

            return false; 

        }    

    } 

    

}

6.学过hibernate的都知道  操作数据库一般要进行事务处理(查询不用),这里这个事务处理可以由spring来进行管理(添加红色字体到applicationContext.xml)

 

<!--使用切面 -->

<aop:aspectj-autoproxy />

<aop:config>

<!-- execution(* cn.wzqiang.dao.impl..*(..)) 是指cn.wzqiang.dao.imp下的所有类的所有方法 -->

<aop:advisor pointcut="execution(* cn.wzqiang.dao.impl..*(..))"advice-ref="txAdvice" />

</aop:config>


<!--hibernate的事务处理管理 -->

<tx:annotation-driven transaction-manager="transactionManager" />

<tx:advice id="txAdvice" transaction-manager="transactionManager">

<tx:attributes>

<tx:method name="Add*" propagation="REQUIRED" isolation="DEFAULT" />

<tx:method name="Delete*" propagation="REQUIRED" isolation="DEFAULT" />

<tx:method name="Update*" propagation="REQUIRED" isolation="DEFAULT" />

<tx:method name="Query*" propagation="NOT_SUPPORTED" isolation="DEFAULT" />

<tx:method name="LoginInfo*" propagation="NOT_SUPPORTED" isolation="DEFAULT" />

<tx:method name="QueryAll*" propagation="NOT_SUPPORTED"isolation="DEFAULT" />

</tx:attributes>

</tx:advice>


<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">

<property name="sessionFactory" ref="sessionFactory"></property>

</bean>

 

---------------------------------------------------------------------------------------------------------------------------------运行ok,没问题

 

7.加入struts2的需要的jar跟配置信息struts.mxl,如下图所示(没有可以到官网去下载struts2)

Struts2需要的jar: http://pan.baidu.com/share/link?shareid=309737&uk=4245483071


 

修改web.xml信息,添加struts2的信息进去

         <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>


-------------------------------------------------------------------------------------------------------------------------------------------------

运行ok,可以跑^_^一个基本的ssh2算是ok

 

------

写两个action 一个登录,一个useinfo的增删改查

 

LoginAction.java

package cn.wzqiang.action;


import java.util.List;


import org.apache.struts2.ServletActionContext;


import cn.wzqiang.dao.UserInfo_dao;

import cn.wzqiang.dto.Userinfo;


public class LoginAction {


/**

* 注入Userinfo_impl

*/

private UserInfo_dao userinfo_impl;

public void setUserinfo_impl(UserInfo_dao userinfo_impl) {

this.userinfo_impl = userinfo_impl;

}



public String userLogin(){

String uname = ServletActionContext.getRequest().getParameter("uname");//接收传过来的用户名

String upwd = ServletActionContext.getRequest().getParameter("upwd");//接收传过来的用户密码

boolean b = false;

try {

b = userinfo_impl.LoginInfo(uname, upwd);

System.out.println("你们祈祷不要是乱码啊:^_^"+uname+";"+upwd+";>>>>"+b);

if(b==true){

List<Userinfo> list = userinfo_impl.QueryALLInfo();

ServletActionContext.getRequest().getSession().setAttribute("listinfos", list);

return "loginok";

}else{

return "loginerror";

}

} catch (Exception e) {

e.printStackTrace();

return "loginerror";

}

}

}

--------------------------------------------------------------------------------------------------------- 

UserinfoAction.java

package cn.wzqiang.action;


import org.apache.struts2.ServletActionContext;


import cn.wzqiang.dao.UserInfo_dao;

import cn.wzqiang.dto.Userinfo;


public class UserinfoAction {


/**

* 注入Userinfo_impl

*/

private UserInfo_dao userinfo_impl;

public void setUserinfo_impl(UserInfo_dao userinfo_impl) {

this.userinfo_impl = userinfo_impl;

}


private String msg;

public String getMsg() {

return msg;

}

public void setMsg(String msg) {

this.msg = msg;

}


/**

* 添加用户

* @return

*/

public String AddUserinfo(){

return null;

}

/**

* 删除用户

* @return

*/

public String DeleteUserinfo(){

int id =Integer.parseInt(ServletActionContext.getRequest().getParameter("id"));

try {

Userinfo info = userinfo_impl.QueryInfo(id);

boolean b = userinfo_impl.DeleteInfo(info);

if(b){

msg = "删除成功!";

}else{

msg = "操作删除失败!";

}

} catch (Exception e) {

e.printStackTrace();

}

return "json";

}

/**

* 修改用户

* @return

*/

public String UpdateUserinfo(){

return "json";

}


/**

* 查询所有用户

* @return

*/

public String QueryAllUserinfo(){

return null;

}

/**

* 根据ID查询用户信息

* @return

*/

public String QueryById(){

return null;

}

}


------------------------------------------------------------------------------------------------

设置好struts.xml相关信息

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC

    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

    "http://struts./dtds/struts-2.0.dtd">


<struts>

<!-- 用户登录 -->

<package name="struts" namespace="/login" extends="struts-default">

<action name="ulogin" class="loginAction">

<result name="loginok">/Userinfo/ok.jsp</result>

<result name="loginerror">/error.jsp</result>

</action>

</package>

<!-- 用户管理操作 -->

<package name="struts_1" namespace="/loginIsok" extends="struts-default,json-default">

<action name="loginok_*" class="userinfoAction" method="{1}">

<result name="json" type="json"/>

</action>

</package>

</struts>

<!--<action name="ulogin" class="loginAction"> , <action name="loginok" class="userinfoAction">的logingAction跟userinfoAction是由spring管理了-->

----------------------

  然后在 applicationContext.xml加入以下信息(这些方法交给spring来管理)


</bean>

<bean id="Userinfo_impl" class="cn.wzqiang.dao.impl.Userinfo_impl">

<property name="sessionFactory" ref="sessionFactory"></property>

</bean>

<bean id="loginAction" class="cn.wzqiang.action.LoginAction">

<property name="userinfo_impl" ref="Userinfo_impl"></property>

</bean>

<bean id="userinfoAction" class="cn.wzqiang.action.UserinfoAction">

<property name="userinfo_impl" ref="Userinfo_impl"></property>

</bean>

---------------------------------------页面处理--------------------------------------------------------------------------

Index.jsp

<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>

<%

String path =request.getContextPath();

String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML 1.0 Transitional//EN""http://www./TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

 <head>

   <basehref="<%=basePath%>"/>

   

   <title>这是个首页</title>

   <metahttp-equiv="pragma"content="no-cache"/>

   <metahttp-equiv="cache-control"content="no-cache"/>

   <metahttp-equiv="expires"content="0"/>    

   <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"/>

   <metahttp-equiv="description"content="This is my page"/>

 </head>

 

 <body>

  <divstyle="margin0 autowidth:200px;">

      <formaction="<%=basePath%>login/ulogin!userLogin"method="post">

         UserName:<inputname="uname"type="text"value=""style="width:140pxheight:22px;"/><br/>

         PassWord:<inputname="upwd"type="password"value=""style="width:140pxheight:22px;"/><br/><br/>

         <inputtype="submit"value="   "/>

      </form>

   </div>

 </body>

</html>

 

由于我使用到了jstl表达式,加入对于的jar

Jstl jar: http://pan.baidu.com/share/link?shareid=309742&uk=4245483071

 

登陆成功的页面 Ok.jsp

 

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

<%

String path = request.getContextPath();

String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<%@ taglib prefix="s"uri="/struts-tags" %>

<%@ taglib prefix="c"uri="http://java./jsp/jstl/core"  %>

<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML 1.0 Transitional//EN""http://www./TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

 <head>

   <base href="<%=basePath%>"></base>

    

   <title>登录成功界面!</title>

    

         <metahttp-equiv="pragma" content="no-cache"/>

         <metahttp-equiv="cache-control" content="no-cache"/>

         <metahttp-equiv="expires" content="0"/>    

         <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"/>

         <metahttp-equiv="description" content="This is my page"/>

       <script type="text/javascript"src="<%=basePath%>js/jquery-1.7.2.js"></script>

       <scripttype="text/javascript">

                $(function(){

                         //删除

                         $(".delete").click(function(){

                                   var uid =$(this).attr("id");

                                    $.ajax({

                                               type:'POST',

                                               url:'<%=basePath%>loginIsok/loginok_DeleteUserinfo',

                                               data:{id:uid},

                                               success:function(data){

                                                        alert(data.msg);

                                                        if(data.msg.length> 4){

                                                                 $(".contents"+uid).remove();

                                                        }

                                               },

                                               error:function(){

                                                        alert("Error");

                                               }

                                     });

                                   

                         });

                         //修改

                         $(".update").click(function(){

                                   alert("由于例子简单,所以就不写这个功能了@_@"); 

                         });

                         //鼠标移动变色

                            $(".contents").each(function(){

                                     $(this).hover(function(){

                                               $(this).css({"background-color":"#333333","cursor":"pointer"});

                                     },function(){

                                               $(this).css("background-color","#666633");

                                     });

                            });

                });

       </script>

 </head>

  

 <body>

             <center>欢迎进入后台操作界面:${user}</center>

 <hr/>

         

 <table width="514" border="0"align="center" cellpadding="1"cellspacing="1">

 <tr>

   <td width="102" height="39"align="center" bgcolor="#333300">序号</td>

   <td width="187" align="center"bgcolor="#333300">用户名</td>

   <td width="215" align="center"bgcolor="#333300">操作</td>

 </tr>

 <c:forEach items="${listinfos }" var="infos"varStatus="status">

 <tr class="contents${infos.id}"style="background-color: #666633">

   <td align="center">${status.index+1}</td>

   <td align="center">${infos.username}</td>

   <td align="center"><button id="${infos.id}"class="update">修改</button>  <buttonid="${infos.id}" class="delete">删除</button></td>

 </tr>

 </c:forEach>

</table>

</body>

</html>

------------------------------------------------------------------------------------------------------------------------------------------------------------

如果有什么不对的,请大家指正,一起学习,

源码 http://pan.baidu.com/share/link?shareid=119384352&uk=4245483071

 如果是eclipse开发的话 还需要加入这个 servlet-api.jar

地址:http://pan.baidu.com/share/link?shareid=1400130585&uk=4245483071


---------------------------------------------------------------------------------------------------------------------

这个是spring+hibernate+servlet的例子源代码

开发步骤我就不写了,跟ssh2整合差不多,去掉struts2的相关信息就可以了 有问题的话可以看源代码或者留言。。。

http://pan.baidu.com/share/link?shareid=1295577698&uk=4245483071

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多