1. 程式人生 > >Spring+struts2+Hibernate框架的搭建

Spring+struts2+Hibernate框架的搭建

param 配置 tro 會有 net click ast scan amp

1.搭建過程

首先需要引入Spring、Struts2、Hibernate的開發包,已經數據庫的驅動包。

技術分享

UserAction.java文件

技術分享
package cn.shop.action;


import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.apache.struts2.convention.annotation.Result; import cn.shop.bean.User; import cn.shop.service.UserService; @ParentPackage(
"struts-default") @Namespace("/") @Controller @Scope("prototype") public class UserAction { @Resource private UserService userService; private String username;//接受參數 private String password;//接受參數 private String message; public String getMessage() {
return message; } public void setMessage(String message) { this.message = message; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Action(value="userlogin",results={ @Result(name="result",location="/loginResult.jsp",type="dispatcher") }) public String execute() throws IOException{ List<User> userinfo=userService.userlogin(username, password); if(userinfo.size()!=0){ message="登錄成功"; }else{ message="登錄失敗"; } return "result"; } }
UserAction.java

User.java文件

技術分享
package cn.shop.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import org.springframework.context.annotation.Scope;

@Entity
@Table(name="user")
public class User {
    
    @Id
    @Column(name="uid")
    private int id;
    
    @Column(name="uname")
    private String name;
    
    @Column(name="upass")
    private String password;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}
User.java

UserDao.java文件

技術分享
package cn.shop.dao;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;

import cn.shop.bean.User;

@Repository("userDao")
public class UserDao {

    @Resource
    private HibernateTemplate template;
    
    public List findUserById(String name,String password){
        return template.find("from User where name=? and password=?",name,password);
    }
}
UserDao.java

UserService.java文件

技術分享
package cn.shop.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cn.shop.bean.User;
import cn.shop.dao.UserDao;

@Service
public class UserService {

    @Resource
    private UserDao userDao;
    
    public List<User> userlogin(String username, String password) {
        return userDao.findUserById(username, password);
    }

}
UserService.java

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:context="http://www.springframework.org/schema/context" 
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
    
    <context:component-scan base-package="cn.shop"></context:component-scan>

  <bean id="config" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
     <property name="locations">
       <list>
         <value>classpath:db-config.properties</value>
       </list>
   </property>
   </bean>

    <bean id="c3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${db.username}"></property>
        <property name="password" value="${db.password}"></property>
        <property name="driverClass" value="${db.dirverClass}"></property>
        <property name="jdbcUrl" value="${db.url}"></property>
    </bean>
    
    <!-- 配置hibernatetemplate -->
    <bean id="template" class="org.springframework.orm.hibernate4.HibernateTemplate">
        <!-- 註入一個SqlSessionFactory對象 -->
        <property name="sessionFactory" ref="sessionFactory">
        </property>
    </bean>
    
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <!-- 指定hibernate.cfg.xml -->
        <property name="configLocations" value="classpath:hibernate.cfg.xml">
        </property>
        <property name="dataSource" ref="c3p0"></property>
    </bean>
    
    
</beans>
applicationContext.xml

db-config.properties文件

技術分享
db.url=jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf8
db.username=root
db.password=517839
db.dirverClass=com.mysql.jdbc.Driver
db-config.properties

hibernate.cfg.xml文件

技術分享
<?xml version=‘1.0‘ encoding=‘UTF-8‘?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="dialect">
            org.hibernate.dialect.MySQLDialect
        </property>
        
        <!-- 加載映射描述信息 -->
        <mapping class="cn.shop.bean.User" />
        
    </session-factory>
</hibernate-configuration>
hibernate.cfg.xml文件

struts.xml文件

技術分享
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
    "http://struts.apache.org/dtds/struts-2.1.7.dtd">

<struts>
      <!--Struts默認只會通過.action和無後綴的請求,我們可以通過指定extension來使得Struts只通過.do的URL的請求。-->
      <constant name="struts.action.extension" value="do"/>
</struts>
struts.xml

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" version="3.0">
  <display-name>ssh</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>struts</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts</filter-name>
    <url-pattern>*</url-pattern>
  </filter-mapping>
  <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>
</web-app>
web.xml

login.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="userlogin.do" method="post">
用戶名:<input type="text" name="username"/><br/>
密碼:<input type="password" name="password"/><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
login.jsp

loginResult.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>登錄結果</title>
</head>
<body>
登錄結果是:${message}
</body>
</html>
loginResult.jsp

2.常見錯誤

問題一:

HTTP Status 500 - cn.xdl.entity.Dept$$javassist_0 cannot be cast to javassist.util.proxy.Proxy

解決方法: javassist.jar 包沖突,去除低版本的。

問題二:

org.hibernate.LazyInitializationException: could not initialize proxy - no Session

解決方法:使用了延遲加載方法,但是 HibernateTemplate 默認方法結束就會關閉 session. 需要追加 OpenSessioninViewFilter 過濾器(必須放到struts的過濾器之前,否則不會有效果),在 JSP 解析後關
閉 session.

    <filter>
        <filter-name>opensession</filter-name>
        <filter-class>
    org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>opensession</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

//...StrutsPrepareAndExecuteFilter的過濾器配置

Spring+struts2+Hibernate框架的搭建