Struts2和hibernate和spring的整合。
源码http://download.csdn.net/download/qq_36992605/10153234
文档http://download.csdn.net/download/qq_36992605/10153230
实验 Struts 2与hibernate和spring框架的整合
一、 实验目的
掌握在Java EE中连接数据库的步骤与方法,以及Hibernate的配置和基本的连接,和增删改查,以及整合Struts2和spring。
二、 实验内容
建一个zhenghe数据库,然后建一个t_student表,表中有四个字段sno,name ,major,javaGrade,表中有三行数据,第一个是自己的信息,其他随便,插入一条记录,显示表中的数据
三、 实验步骤
1、 先建数据库和表
2、 然后打开myeclpise数据库的视图,新建一个数据库的连接。
3、 在项目明下点反键
先搭建好spring的框架,选择spring的框架
然后一直下一步就可以了。
4、 接着导入hibernate框架,先建一个org.vo包用存放映射关系,和实体类。
切换到数据库视图
主键生成策略选native其他的下一步就可以了。
5、 导入Struts2包到lib下,配置web.xml和建Struts.xml文件并配置过滤器
6、 LoginAction.java代码
package org.action;
importjava.util.*;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.FileSystemXmlApplicationContext;
importorg.vo.*;//++
import org.dao.*;
importorg.dao.impl.*;//++
importcom.opensymphony.xwork2.*;
importorg.dao.LoginDao;
importorg.dao.impl.LoginDaoImpl;
public classLoginAction extends ActionSupport{
private TStudent tstudent;
public TStudent getTstudent() {
return tstudent;
}
public void setTstudent(TStudenttstudent) {
this.tstudent = tstudent;
}
public String regist() throws Exception{
LoginDao loginDao = newLoginDaoImpl();
ApplicationContext context = newFileSystemXmlApplicationContext(
"file:C:/Users/wqh/Workspaces/MyEclipse10/SSH2/src/applicationContext.xml");
LoginDao loginDAO = (LoginDao)context.getBean("loginDAO");
int i =loginDAO.regist(tstudent.getSno(), tstudent.getName(), tstudent.getMajor(),tstudent.getJavaGrade());
if(i > 0){
return SUCCESS;
}
else
return ERROR;
}
}
ShowAction.java
packageorg.action;
importjava.util.List;
importjava.util.Map;
import org.dao.*;
importorg.dao.impl.StudentDao;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.FileSystemXmlApplicationContext;
import org.vo.TStudent;
importcom.opensymphony.xwork2.ActionContext;
importcom.opensymphony.xwork2.ActionSupport;
public classShowAction extends ActionSupport {
private TStudent tstudent;
public TStudent getTstudent() {
return tstudent;
}
public void setTstudent(TStudent tstudent){
this.tstudent = tstudent;
}
public String execute() throws Exception {
ApplicationContext context = newFileSystemXmlApplicationContext(
"file:C:/Users/wqh/Workspaces/MyEclipse10/SSH2/src/applicationContext.xml");
IStudent userDAO = (IStudent)context.getBean("userDAO");
List l = userDAO.serch();
if (l != null) {
Map session =ActionContext.getContext().getSession(); // 获得会话,用来保存当前登录用户的信息
session.put("list",l);
System.out.println(l);
return "success";
} else {
return ERROR; // 验证失败返回字符串ERROR
}
}
}
BaseDao.java
package org.dao;
importorg.hibernate.Session;
importorg.hibernate.SessionFactory;
public classBaseDao {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory(){
return sessionFactory;
}
public voidsetSessionFactory(SessionFactory sessionFactory){
this.sessionFactory=sessionFactory;
}
public Session getSession(){
Sessionsession=sessionFactory.openSession();
return session;
}
}
IStudent.java
packageorg.dao;
import java.util.List;
public interface IStudent {
public Listserch();
}
LoginDao.java
packageorg.dao;
public interface LoginDao {
public int regist(String sno,Stringname,String major ,Integer javaGrade);
}
LoginDaoImpl.java
packageorg.dao.impl;
importorg.dao.BaseDao;
importorg.dao.IStudent;
importorg.dao.LoginDao;
importorg.hibernate.Query;
importorg.hibernate.Session;
import org.hibernate.Transaction;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.FileSystemXmlApplicationContext;
importorg.vo.TStudent;
public classLoginDaoImpl extends BaseDao implementsLoginDao {
public int regist(String sno,Stringname,String major ,Integer javaGrade) {
try {
ApplicationContext context = newFileSystemXmlApplicationContext(
"file:C:/Users/wqh/Workspaces/MyEclipse10/SSH2/src/applicationContext.xml");
//LoginDao loginDAO = (LoginDao)context.getBean("loginDAO");
Session session = getSession();
TStudent tStudent = new TStudent();
tStudent.setSno(sno);
tStudent.setMajor(name);
tStudent.setName(major);
tStudent.setJavaGrade(javaGrade);
session.save(tStudent);
Transaction ts =session.beginTransaction();
ts.commit();
return 1;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
StudentDao.java
packageorg.dao.impl;
importjava.util.List;
importorg.dao.BaseDao;
importorg.dao.IStudent;
importorg.hibernate.Query;
importorg.hibernate.Session;
public classStudentDao extends BaseDao implements IStudent {
public List serch() {
Session session = getSession();
List list = null;
Query query =session.createQuery("from TStudent");
list = query.list();
return list;
}
}
log4j.properties
#Configure logging for testing: optionally with log file
log4j.rootLogger=WARN, stdout
#log4j.rootLogger=WARN, stdout,logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d%p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d%p [%c] - %m%n
TStudent.java
packageorg.vo;
/**
* TStudent entity. @author MyEclipse Persistence Tools
*/
public class TStudent implements java.io.Serializable {
// Fields
private Integerid;
private String sno;
private Stringname;
private Stringmajor;
private IntegerjavaGrade;
// Constructors
/** default constructor */
public TStudent() {
}
/** full constructor */
public TStudent(String sno, String name, String major, Integer javaGrade) {
this.sno = sno;
this.name = name;
this.major = major;
this.javaGrade = javaGrade;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSno() {
return this.sno;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getMajor() {
return this.major;
}
public void setMajor(String major) {
this.major = major;
}
public Integer getJavaGrade() {
return this.javaGrade;
}
public void setJavaGrade(Integer javaGrade) {
this.javaGrade = javaGrade;
}
}
TStudent.hbm.xml
<?xmlversion="1.0"encoding="utf-8"?>
<!DOCTYPEhibernate-mapping PUBLIC"-//Hibernate/HibernateMapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated byMyEclipse Persistence Tools
-->
<hibernate-mapping>
<classname="org.vo.TStudent"table="t_student"catalog="zhenghe">
<idname="id"type="java.lang.Integer">
<columnname="id"/>
<generatorclass="native"/>
</id>
<propertyname="sno"type="java.lang.String">
<columnname="sno"length="45"/>
</property>
<propertyname="name"type="java.lang.String">
<columnname="name"length="45"/>
</property>
<propertyname="major" type="java.lang.String">
<columnname="major"length="45"/>
</property>
<propertyname="javaGrade"type="java.lang.Integer">
<columnname="javaGrade"/>
</property>
</class>
</hibernate-mapping>
applicationContext.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="baseDao"class="org.dao.BaseDao">
<propertyname="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="userDAO"class="org.dao.impl.StudentDao" parent="baseDao" />
<bean id="loginDAO"class="org.dao.impl.LoginDaoImpl" parent="baseDao" />
<bean id="login"class="org.action.ShowAction" />
<bean id="regist"class="org.action.LoginAction" />
<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/zhenghe">
</property>
<property name="username"value="root"></property>
<property name="password"value="root"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<propertyname="dataSource">
<ref bean="dataSource" />
</property>
<propertyname="hibernateProperties">
<props>
<propkey="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>
<propertyname="mappingResources">
<list>
<value>org/vo/TStudent.hbm.xml</value>
</list>
</property>
</bean>
</beans>
struts.xml
<!DOCTYPEstruts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="struts"extends="struts-default">
<action name="ShowAction"class="org.action.ShowAction" method="execute">
<result name="success">/show.jsp</result>
<resultname="error">/index.jsp </result>
</action>
<action name="regist"class="org.action.LoginAction" method="regist">
<resultname="success">/success.jsp</result>
<resultname="input">/regist.jsp</result>
<resultname="error">/index.jsp</result>
</action>
</package>
<constantname="struts.i18n.encoding"value="UTF-8"></constant>
</struts>
index.jsp
<%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%>
<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML4.01 Transitional//EN">
<html>
<head>
<h1>这是一个导航条</h1>
</head>
<body>
<ahref="ShowAction.action">查看数据</a>
<ahref = "regist.jsp">添加数据</a>
<br>
</body>
</html>
regist.jsp
<%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%>
<!DOCTYPEHTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<formaction= "regist.action">
请 输 入 学 号 <inputtype= textname ="tstudent.sno" ><br>
请输入您 的 姓 名<input type = textname = "tstudent.name" ><br>
请输如你的 专业<inputtype = textname = "tstudent.major"><br>
请输入你的java成绩<inputtype = textname = "tstudent.javaGrade" > <br>
<inputtype= "submit"value ="确定">
<input type= "reset" value="重置">
</form>
</body>
</html>
show.jsp
<%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%>
<%@tagliburi="/struts-tags"prefix="s"%>
<!DOCTYPEHTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">
<html>
<head>
<h1>6666</h1>
</head>
<body>
<tableborder= "1"align="center">
<s:iteratorvalue="#session.list">
<!-- <tr>
<th>xx</th>
<th>学号</th><th>姓名</th><th>专业</th><th>Java成绩</th>
</tr> -->
<tr>
<!-- <td>xx</td> -->
<td><s:propertyvalue="sno"/></td>
<td><s:propertyvalue="name"/></td>
<td><s:propertyvalue="major"/></td>
<td><s:propertyvalue="javaGrade"/></td>
</tr>
</s:iterator>
</table>
</body>
</html>
success.jsp
<%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%>
<!DOCTYPEHTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
插入成功 <br>
</body>
</html>
四、 实验结果
五、 实验小结
了解了Hibernate框架和Struts2和spring整合的基础。