SSH框架整合应用

罗嗦一下:经过struts,hibernate ,spring三个框架的非系统学习,,最后将三者整合起来,,今天下午开会完毕,晚上就再搞一下,尝试从简单着手,经过修改,最后搭建成功,具体步骤如下:

首先是整个web project的工程目录结构图,具体如下:

1,创建web工程,然后导入struts2,spring,hibernate的包,可以单独建立一个lib文件夹,放在其中,然后通过add jar 放到library中,,

2,创建domain包,然后创建名为UserVo.java的持久化类文件,创建名为UserVo.hbm.xml的持久化类映射文件,,,,,,(对应的数据库schema为fcshopping,表为uservo)  代码如下:

UserVo.java

View Code
package domain;
public class UserVo {

     private Integer userId;
     private String userName;
     private String passWord;

    public UserVo() {
    }
    public UserVo(String userName, String passWord) {
        this.userName = userName;
        this.passWord = passWord;
    }

    public Integer getUserId() {
        return this.userId;
    }
    
    public void setUserId(Integer userId) {
        this.userId = userId;
    }

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

    public String getPassWord() {
        return this.passWord;
    }
    
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

}

UserVo.hbm.xml:

View Code
<?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>
    <class name="domain.UserVo" table="uservo" catalog="fcshopping">
        <id name="userId" type="java.lang.Integer">
            <column name="userID" />
            <generator class="native"></generator>
        </id>
        <property name="userName" type="java.lang.String">
            <column name="userName" length="20" not-null="true" />
        </property>
        <property name="passWord" type="java.lang.String">
            <column name="passWord" length="20" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

3,在dao包中创建持久化类的接口以及该接口的实现类,具体如下:

  接口UserDAO.java:

View Code
package dao;
import java.util.List;
import domain.UserVo;
public interface UserDAO{
    public List<UserVo> findByProperty(String userName,String userPsw);    
}

  接口实现类UserDAOImpl.java:

View Code
package dao;
import java.util.List;
import domain.UserVo;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class UserDAOImpl extends HibernateDaoSupport implements UserDAO{
    @SuppressWarnings("unchecked")
    public List<UserVo> findByProperty(String userName,String userPsw){
        String sql="from UserVo u where u.userName='"+userName+"'and u.passWord = '"+userPsw+"'";
        List<UserVo> list=(List<UserVo>)getHibernateTemplate().find(sql);
        return list;
        
    }

}

4,在service包中创建业务层的接口以及该接口的实现类,具体如下:

  接口UserService.java:

View Code
package service;
import domain.UserVo;

public interface UserService {
    public UserVo validateUser(String userName,String userPsw);

}

  接口实现类UserServiceImpl.java:

View Code
package service;
import dao.UserDAO;
import domain.UserVo;

public class UserServiceImpl implements UserService{
    private UserDAO userDAO;

    public UserDAO getUserDAO() {
        return userDAO;
    }

    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }
    
    public UserVo validateUser(String userName,String userPsw){
        if(userDAO.findByProperty(userName, userPsw).size()!=0){
            return userDAO.findByProperty(userName, userPsw).get(0);
        }
        return null;
    }

}

5,在action包中创建用户登录模块的action类LoginAction.java:

View Code
package action;
import service.UserService;
import domain.UserVo;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class LoginAction extends ActionSupport {

    /**
     * @return
     */
    private UserVo user;
    private UserService userService;
    
    
    public UserVo getUser() {
        return user;
    }


    public void setUser(UserVo user) {
        this.user = user;
    }


    public UserService getUserService() {
        return userService;
    }


    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    public String execute()throws Exception {
        // TODO Auto-generated method stub
        UserVo u=userService.validateUser(user.getUserName(), user.getPassWord());
        if(u!=null){
            return SUCCESS;
        }
        else{
            return ERROR;
        }
    }
}

6,为解决中文乱码问题,在包filter中创建过滤器:

  CharacterEncodingFilter.java:

View Code
package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class CharacterEncodingFilter implements Filter {
    private String characterEncoding;//编码方式在web.xml中
    private boolean enabled;//是否启动filter,初始值在web.xml中
    
    @Override
    public void init(FilterConfig config) throws ServletException {
        // TODO Auto-generated method stub
        //初始化时加载参数
        //从配置文件中读取设置到编码方式
        characterEncoding=config.getInitParameter("characterEncoding");
        //启动该过滤器完成编码方式到修改
        enabled="true".equalsIgnoreCase(characterEncoding.trim())
            ||"1".equalsIgnoreCase(characterEncoding.trim());
        
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        if(enabled||characterEncoding!=null){
            request.setCharacterEncoding(characterEncoding);//设置request编码方式
            response.setCharacterEncoding(characterEncoding);//设置response编码方式
        }
        chain.doFilter(request, response);//doFilter将修改好的request和response参数向下传递;
        
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        characterEncoding=null;
        
    }

    



}

7,Struts2配置文件代码如下:

  struts2.xml:

View Code
<?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>
    

    <include file="struts-default.xml"></include>
    
<package name="main" extends="struts-default">
    <action name="login" class="action.LoginAction">
        <result name="success">/success.jsp</result>
        <result name="error">/error.jsp</result>
    </action></package></struts>

  struts.properties:

View Code
struts.objectFactory=spring
struts.action.extension=action
struts.locale=en_GB

8,applicationContext.xml文件的代码如下:

View Code
<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/fcshopping"></property>
        <property name="username" value="root"></property>
        <property name="password" value="lpshou"></property>

    </bean>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="datasource"></ref>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            </props>
        </property>
        <property name="mappingResources">
            <list>
                <value>domain/UserVo.hbm.xml</value>
            </list>
        </property>
    </bean>
    
    <bean id="userDAO" class="dao.UserDAOImpl">
        <property name="sessionFactory"><ref local="sessionFactory"/></property>
    </bean>
    
    <bean id="userService" class="service.UserServiceImpl">
        <property name="userDAO"><ref bean="userDAO"></ref></property>
    </bean>
    
    <bean id="login" class="action.LoginAction">
        <property name="userService"><ref bean="userService"></ref></property>
    </bean>

</beans>

9,在web.xml文件中配置Spring,Sturts2的监听,具体:

View Code
<?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>
  
    <!-- struts2过滤器 -->
    <filter>
      <filter-name>struts</filter-name>
      <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
      <init-param>
          <param-name>struts.action.extension</param-name>
          <param-value>action</param-value>
      </init-param>
  </filter>
  <filter-mapping>
      <filter-name>struts</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- 字符集过滤器 -->
  <filter>
      <filter-name>characterEncodingFilter</filter-name>
      <filter-class>filter.CharacterEncodingFilter</filter-class>
      <init-param>
          <param-name>characterEncoding</param-name>
          <param-value>UTF-8</param-value>
      </init-param>
      <init-param>
          <param-name>enable</param-name>
          <param-value>true</param-value>
      </init-param>
  </filter>
  <filter-mapping>
      <filter-name>characterEncodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- spring的监听 -->
  <listener>
      <listener-class>
          org.springframework.web.context.ContextLoaderListener
      </listener-class>
  </listener>
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/classes/applicationContext.xml</param-value> 
  </context-param>
</web-app>

10,用户登录模块,包含三个部分,分别时login.jsp,  success.jsp,  error.jsp,具体如下:

  login.jsp:

View Code
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="struts" %>
<%
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>登录页面</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>
   <center>
        <h2>用户登录</h2><p>
        <struts:form action="login" method="post">
            <struts:textfield name="user.userName" label="帐号:"></struts:textfield>
            <struts:password name="user.passWord" label="密码:"></struts:password>
            <struts:submit value="登录"></struts:submit>
        </struts:form>
    </center>
  </body>
</html>

  success.jsp:

View Code
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="struts" %>
<%
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 'success.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>
       <center><h2>欢迎登录</h2></center><br/>
    你好!用户:<struts:property value="user.userName"/>登录成功
  </body>
</html>

  error.jsp:

View Code
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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 'error.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>
        登录失败
  </body>
</html>

11,启动tomcat,发布工程即可,测试成功。

参考:JavaEE框架技术进阶式教程

原文地址:https://www.cnblogs.com/lpshou/p/2795316.html