ssh整合 小例子

实现了用户的查插删改操作。

原理:struts负责接收、分发请求。spring采用面向接口编程的思想整合整体框架,负责连接数据库。hibernate负责操作数据库语言。

思路:

1.配置struts的配置信息
2.创建struts和hibernate的关联(主要是加载jar包)
3.创建struts和spring的关联(主要是加载jar包)
4.编写页面信息。action
5.纵向开发模式(但是平时按照横向开发)。纵向开发好处是思路清晰,先写完dao层
service层action层编写模式
6.开始编写spring的配置文件。添加bean。采用依赖注入完成面向接口编程(面向切面编
程更准确些)。
7.编写struts的配置文件。将action映射到spring的配置文件中的bean中


防止表单重复提交(重定向)

好了,不多说了,用例子说话才是最权威的。

1.配置struts

a.wen.xml文件添加struts的过滤器、映射,spring的监听器

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

    <!-- 解决中文乱码问题 -->
    <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>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>

</web-app>

b.struts的jar包支持

c.struts的配置文件 struts.xml(放在src目录下)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
    
    <struts>
      <constant name="struts.i18n.encoding" value="UTF-8"></constant>
        <package name="ssh2" extends="struts-default">
            <action name="saveUser" class="saveUserAction">
                <result name="success" type="redirect">listUser.action</result>
            </action>
            
            <action name="listUser"  class="listUserAction">
                <result name="success">/list.jsp</result>
            </action>
            
            <action name="deleteUser" class="removeUserAction">
                <result name="success" type="redirect">/listUser.action</result>
            </action>
            
            <!--请求转发  -->
            <action name="updatePUser" class="updatePUserAction">
                <result name="success">/update.jsp</result>
            </action>
            
            <!-- 重定向 -->
            <action name="updateUser" class="updateUserAction">
                <result name="success" type="redirect">/listUser.action</result>
            </action>
        </package>
        
        
    
    </struts>

2.导入hibernate的jar包支持,采用myeclipse自带的jar包

a.右击项目名称选择 myeclipse-->Add Hibernate Capabilities 如下图(为了将hibernate配置文件放置在src目录下,其实哪里都一样。。。)

b.点击next,不用向导配置完成后,打开配置文件

c.只是导入一些jar包,不需要连接数据库

d.不用创建session工厂

e.点击Finish完成

3.添加spring的jar包支持

同上面一样,导入jar包

4.编写页面信息、bean以及此bean的映射文件User.hbm.xml(放在com.test.bean目录下)

a.index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"   %>
<%
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>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
   
    <h1><font color="red">Operation List</font></h1>
    
    <s:a href="save.jsp">Sav e User</s:a><br/>
    <s:a href="listUser.action">List Users</s:a>
  </body>
</html>

b.创建bean

package com.test.bean;

public class User {

    private int id;
    private String firstname;
    private String lastname;
    private int age;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

3.bean的映射文件User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.test.bean.User" table="users">
        <id name="id" column="id" type="int">
            <generator class="increment"></generator>
        </id>
        
        <property name="firstname" column="firstname" type="string"></property>
        <property name="lastname" column="lastname" type="string"></property>
        <property name="age" column="age" type="int"></property>
    </class>
</hibernate-mapping>

 

6.因为要良好封装,所以从dao层开始编写

a.dao层接口

package com.test.dao.impl;

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.test.bean.User;
import com.test.dao.UserDAO;

public class UserDAOImpl extends HibernateDaoSupport implements UserDAO 
{
    
    public void saveUser(User user) {
        this.getHibernateTemplate().save(user);
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public List<User> findAllUsers() {
        String hql = "from User user order by user.id desc";
        return     (List<User>)this.getHibernateTemplate().find(hql);
    }
    
    @Override
    public void removeUser(User user) {
        this.getHibernateTemplate().delete(user);
    }
    
    @Override
    public void updateUser(User user) {
        this.getHibernateTemplate().update(user);
    }
    
    @Override
    public User findUserById(Integer id) {

        User user = (User)this.getHibernateTemplate().get(User.class, id);
        return user;
    }

}

b.dao层实现类

package com.test.dao.impl;

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.test.bean.User;
import com.test.dao.UserDAO;

public class UserDAOImpl extends HibernateDaoSupport implements UserDAO 
{
    
    public void saveUser(User user) {
        this.getHibernateTemplate().save(user);
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public List<User> findAllUsers() {
        String hql = "from User user order by user.id desc";
        return     (List<User>)this.getHibernateTemplate().find(hql);
    }
    
    @Override
    public void removeUser(User user) {
        this.getHibernateTemplate().delete(user);
    }
    
    @Override
    public void updateUser(User user) {
        this.getHibernateTemplate().update(user);
    }
    
    @Override
    public User findUserById(Integer id) {

        User user = (User)this.getHibernateTemplate().get(User.class, id);
        return user;
    }

}

7.编写service层

a.service的接口

package com.test.service;

import java.util.List;

import com.test.bean.User;

public interface UserService {
    
    public void save(User user);
    
    public List<User> findAll();
    
    public void delete(User user);
    
    public User findById(Integer id);
    
    public void update(User user);

}

b.service的实现类

package com.test.service.impl;

import java.util.List;

import com.test.bean.User;
import com.test.dao.UserDAO;
import com.test.service.UserService;

public class UserServiceImpl implements UserService
{
    private UserDAO userDAO;
    
    public UserDAO getUserDAO() {
        return userDAO;
    }

    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    @Override
    public void save(User user) {
        
        this.userDAO.saveUser(user);//完成真正的业务逻辑
    }

    @Override
    public List<User> findAll() {
        return this.userDAO.findAllUsers();
    }
    
    @Override
    public void delete(User user) {
        this.userDAO.removeUser(user);
    }

    @Override
    public User findById(Integer id) {
        User user = this.userDAO.findUserById(id);
        System.out.println(user);
        return user;
    }

    @Override
    public void update(User user) {
        
        this.userDAO.updateUser(user);
    }
}

8.action的实现

a.完成的是显示全部用户信息功能的action

package com.test.action.user;

import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.test.bean.User;
import com.test.service.UserService;

public class ListUserAction extends ActionSupport {

    private UserService service;

    public UserService getService() {
        return service;
    }

    public void setService(UserService service) {
        this.service = service;
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public String execute() throws Exception {

        Map request = (Map)ActionContext.getContext().get("request");
        request.put("list", this.service.findAll());
        return SUCCESS;
    }
}

b.根据id删除用户信息

package com.test.action.user;

import com.opensymphony.xwork2.ActionSupport;
import com.test.bean.User;
import com.test.service.UserService;

public class RemoveUserAction extends ActionSupport {

    private User user;
    private UserService service;
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public UserService getService() {
        return service;
    }
    public void setService(UserService service) {
        this.service = service;
    }
    
    @Override
    public String execute() throws Exception {
        this.service.delete(user);
        return  SUCCESS;
    }
}

c.添加用户信息

package com.test.action.user;

import com.opensymphony.xwork2.ActionSupport;
import com.test.bean.User;
import com.test.service.UserService;

public class SaveUserAction extends ActionSupport {

    private User user;
    private UserService service;

    public UserService getService() {
        return service;
    }

    public void setService(UserService service) {
        this.service = service;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
    
    @Override
    public String execute() throws Exception {
        
        //调用service相关的方法,完成实际的业务逻辑
        //action只负责收集数据,验证校验
        this.service.save(this.user);
        return SUCCESS;
    }
}

d.通过ID查找用户信息

package com.test.action.user;

import com.opensymphony.xwork2.ActionSupport;
import com.test.bean.User;
import com.test.service.UserService;

public class UpdatePUserAction extends ActionSupport {

    private User user;
    private UserService service;
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public UserService getService() {
        return service;
    }
    public void setService(UserService service) {
        this.service = service;
    }
    
    @Override
    public String execute() throws Exception {

        this.user = this.service.findById(this.user.getId());
        return SUCCESS;
    }
}
View Code

e.通过ID修改用户信息

package com.test.action.user;

import com.opensymphony.xwork2.ActionSupport;
import com.test.bean.User;
import com.test.service.UserService;

public class UpdateUserAction extends ActionSupport {

    private User user;
    private UserService service;
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public UserService getService() {
        return service;
    }
    public void setService(UserService service) {
        this.service = service;
    }
    
    @Override
    public String execute() throws Exception {
        this.service.update(user);
        return SUCCESS;
    }
}

9.添加spring的配置信息

bean的实现(放在WEB-INF目录下)

<?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="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
    
        <property name="driverClassName">
            <value>com.mysql.jdbc.Driver</value>
        </property>
        
        <property name="url">
            <value>jdbc:mysql://localhost:3306/hibernate</value>
        </property>
        
        <property name="username">
            <value>root</value>
        </property>
        
        <property name="password">
            <value>123456</value>
        </property>
    </bean>
    
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        
        <property name="dataSource">
            <ref local="dataSource"/>
        </property>
        
        <property name="mappingResources">
            <list>
                <value>com/test/bean/User.hbm.xml</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="userDao" class="com.test.dao.impl.UserDAOImpl" scope="singleton">    
        <property name="sessionFactory">
            <ref bean="sessionFactory"/>
        </property>
    </bean>
    
    <bean id="userService" class="com.test.service.impl.UserServiceImpl" scope="singleton">
        <property name="userDAO"  ref="userDao" />
    </bean>
    
    <bean id="saveUserAction" class="com.test.action.user.SaveUserAction" scope="prototype">
        <property name="service" ref="userService"></property>
    </bean>
    
    <bean name="listUserAction" class="com.test.action.user.ListUserAction" scope="prototype">
        <property name="service" ref="userService"></property>
    </bean>
    
    <bean name="removeUserAction" class="com.test.action.user.RemoveUserAction"  scope="prototype">
        <property name="service" ref="userService"></property>
    </bean>
    
    <bean name="updateUserAction" class="com.test.action.user.UpdateUserAction"  scope="prototype">
        <property name="service" ref="userService"></property>
    </bean>
    
    <bean name="updatePUserAction" class="com.test.action.user.UpdatePUserAction">
        <property name="service" ref="userService"></property>
    </bean>
</beans>

10.struts.xml(放在src目录下)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
    
    <struts>
    
        <package name="ssh2" extends="struts-default">
            <action name="saveUser" class="saveUserAction">
                <result name="success" type="redirect">listUser.action</result>
            </action>
            
            <action name="listUser"  class="listUserAction">
                <result name="success">/list.jsp</result>
            </action>
            
            <action name="deleteUser" class="removeUserAction">
                <result name="success" type="redirect">/listUser.action</result>
            </action>
            
            <!--请求转发  -->
            <action name="updatePUser" class="updatePUserAction">
                <result name="success">/update.jsp</result>
            </action>
            
            <!-- 重定向 -->
            <action name="updateUser" class="updateUserAction">
                <result name="success" type="redirect">/listUser.action</result>
            </action>
        </package>    
    
    </struts>

11.页面展示

a.list.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'list.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
<SCRIPT type="text/javascript">
    function del()
    {
        if(comfirm("are you sure?"))
        {
            return true;
        }
        return false;
    }
</SCRIPT>
  </head>
  
  <body> 
    <h1><font color="red"><center>User List</center></font></h1>
    
    <table border="1" width=80% align="center">
        <tr>
            <td>序号:</td>
            <td>姓:</td>
            <td>名:</td>
            <td>年龄:</td>
            <td>删除:</td>
            <td>更新:</td>
        </tr>
        
        <s:iterator value="#request.list" id="us">
            <tr>
                <td>
                    <s:property value="#us.id"/>
                </td>
                <td>
                    <s:property value="#us.firstname"/>
                </td>
                <td>
                    <s:property value="#us.lastname"/>
                </td>
                <td>
                    <s:property value="#us.age"/>
                </td>
                <td>
                    <s:a href="deleteUser.action?user.id=%{#us.id}" onclick="return del();">delete</s:a>
                </td>
                <td>
                    <s:a href="updatePUser.action?user.id=%{#us.id}">update</s:a>
                </td>
            </tr>
        </s:iterator>
        
    </table>
  </body>
</html>

b.save.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags"  prefix="s"%>
<%
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 'save.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
  
    <h1><font color="red">Operation User</font></h1>
    
    <s:form action="saveUser">
        <s:textfield name="user.firstname" label="firstname"></s:textfield>
        <s:textfield name="user.lastname" label="lastname"></s:textfield>
        <s:textfield name="user.age" label="age"></s:textfield>
        
        <s:submit value="submit"></s:submit>
        
    </s:form>
    
  </body>
</html>

c.update.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"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'update.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
   
    <h1><font color="red"><center> Update User</center></font></h1>
     
     <s:form action="updateUser">
         
         <table>
             <tr>
                 <td>
                     <s:hidden name="user.id" value="%{user.id}"></s:hidden>
                 </td>
                 <td>
                     <s:textfield name="user.firstname" value="%{user.firstname}"></s:textfield>
                 </td>
                 <td>
                     <s:textfield name="user.lastname" value="%{user.lastname}"></s:textfield>
                 </td>
                 <td>
                     <s:textfield name="user.age" value="%{user.age}"></s:textfield>
                 </td>
                 <td>
                     <s:submit value="submit"></s:submit>
                 </td>
             </tr>
         </table>
     </s:form>
  </body>
</html>

总体的框架

lib目录下jar包信息

好了完工。。。。坐等评论。

珍惜现在,珍惜每一分,每一秒。 从不放弃,坚持。。。。。
原文地址:https://www.cnblogs.com/feiguo/p/3675892.html