【Spring】Spring+struts2+Hibernate框架的搭建
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"; } }
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; } }
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); } }
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); } }
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>
db-config.properties文件
db.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8 db.username=root db.password=517839 db.dirverClass=com.mysql.jdbc.Driver
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>
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>
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>
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>
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>
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的过滤器配置