目录结构如下:
在mysql数据库中,建立一个数据库 stu,建立一张表stuinfo,如下图所示:
1.新建一个web project,命名为ch15,然后导入struts 2核心包和hibernate核心包,导入方法是:右击ch15这个项目,选择倒数第二项:,myeclipse,选择Add Struts 2...,导入hibernate的核心包也是一样。
2.首先要导入struts 2 核心包和hibernate核心包,但是struts 2 的核心包内的 antlr-2.x.x.jar包要删掉,删除方法是:window——>preferences——>Myeclipse——>Project Capabilitie——>Struts 2. 然后选中右边的antlr-2.x.x.jar包,选择右边的remove,就OK啦
3.在src下建立四个包,分别为addHibernateFile, Dao, PO, studentAction
4.addHibernateFile下的代码(HibernateSessionFactory.java):
package addHibernateFile; import javax.swing.JOptionPane; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateSessionFactory { private static SessionFactory sessionFactory; private static Configuration configuration=new Configuration(); public HibernateSessionFactory(){ } static{ try{ Configuration configure = configuration.configure("hibernate.cfg.xml"); sessionFactory=configure.buildSessionFactory(); }catch(Exception e){ message("生成SessionFactoyr失败:"+e); } } public static Session getSession(){ return sessionFactory.openSession(); } public static void message(String mess){ int type=JOptionPane.YES_NO_OPTION; String title="提示信息"; JOptionPane.showMessageDialog(null, mess, title, type); } }
package Dao; import addHibernateFile.HibernateSessionFactory; import PO.Stuinfo; import java.util.List; import javax.swing.JOptionPane; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; public class StudentDao { private Transaction transaction; private Session session; private Query query; public StudentDao(){ } public boolean saveInfo(Stuinfo info){ try{ session=HibernateSessionFactory.getSession(); transaction=session.beginTransaction(); session.save(info); transaction.commit(); session.close(); return true; }catch(Exception e){ message("saveInfo.error:"+e); e.printStackTrace(); return false; } } public List findInfo(String type,Object value){ session=HibernateSessionFactory.getSession(); try{ transaction=session.beginTransaction(); String queryString="from Stuinfo as model where model."+type+"=?"; query=session.createQuery(queryString); query.setParameter(0, value); List list=query.list(); transaction.commit(); session.close(); return list; }catch(Exception e){ message("findInfo.error:"+e); e.printStackTrace(); return null; } } public List findAllInfo(){ session=HibernateSessionFactory.getSession(); try{ transaction=session.beginTransaction(); String queryString="from Stuinfo"; query=session.createQuery(queryString); List list=query.list(); transaction.commit(); session.close(); return list; }catch(Exception e){ message("findInfo.error:"+e); e.printStackTrace(); return null; } } public boolean deleteInfo(String id){ try{ session=HibernateSessionFactory.getSession(); transaction=session.beginTransaction(); Stuinfo info=new Stuinfo(); info=(Stuinfo)session.get(Stuinfo.class, id); session.delete(info); transaction.commit(); session.close(); return true; }catch(Exception e){ message("deleteInfo.error:"+e); e.printStackTrace(); return false; } } public boolean updateInfo(Stuinfo info){ try{ session=HibernateSessionFactory.getSession(); transaction=session.beginTransaction(); session.update(info); transaction.commit(); session.close(); return true; }catch(Exception e){ message("updateInfo.error:"+e); e.printStackTrace(); return false; } } public void message(String mess){ int type=JOptionPane.YES_NO_OPTION; String title="提示信息"; JOptionPane.showMessageDialog(null, mess, title, type); } }
(1)Stuinfo.java
package PO; public class Stuinfo implements java.io.Serializable { private String id; private String name; private String sex; private int age; private float weight; public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getSex() { return this.sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return this.age; } public void setAge(int age) { this.age = age; } public float getWeight() { return this.weight; } public void setWeight(float weight) { this.weight = weight; } }
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 2011-12-9 12:17:31 by Hibernate Tools 3.2.1.GA --> <hibernate-mapping> <class name="PO.Stuinfo" table="stuinfo" catalog="stu"> <id name="id" type="string"> <column name="id" length="20" /> <generator class="assigned" /> </id> <property name="name" type="string"> <column name="name" length="20" not-null="true" /> </property> <property name="sex" type="string"> <column name="sex" length="5" not-null="true" /> </property> <property name="age" type="int"> <column name="age" not-null="true" /> </property> <property name="weight" type="float"> <column name="weight" precision="10" scale="0" not-null="true" /> </property> </class> </hibernate-mapping>
(1)AddMessageAction.java
package studentAction; import Dao.StudentDao; import PO.Stuinfo; import com.opensymphony.xwork2.ActionSupport; import java.util.List; import javax.swing.JOptionPane; public class AddMessageAction extends ActionSupport{ private String id; private String name; private String sex; private int age; private float weight; private String message="input"; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public float getWeight() { return weight; } public void setWeight(float weight) { this.weight = weight; } public void validate(){ if(this.getId()==null||this.getId().length()==0){ addFieldError("id","学号不允许为空!"); }else{ StudentDao dao=new StudentDao(); List list=dao.findInfo("id", this.getId()); if(!list.isEmpty()){ addFieldError("id","学号已存在!"); } } if(this.getName()==null||this.getName().length()==0){ addFieldError("name","姓名不允许为空!"); } if(this.getAge()>130){ addFieldError("age","请认真核实年龄!"); } if(this.getWeight()>500){ addFieldError("weight","请认真核实体重!"); } } public String execute() throws Exception{ StudentDao dao=new StudentDao(); boolean save=dao.saveInfo(info()); if(save){ message="success"; } return message; } public Stuinfo info(){ Stuinfo info=new Stuinfo(); info.setId(this.getId()); info.setName(this.getName()); info.setSex(this.getSex()); info.setAge(this.getAge()); info.setWeight(this.getWeight()); return info; } public void message(String mess){ int type=JOptionPane.YES_NO_OPTION; String title="提示信息"; JOptionPane.showMessageDialog(null, mess, title, type); } }
package studentAction; import Dao.StudentDao; import com.opensymphony.xwork2.ActionSupport; import javax.swing.JOptionPane; public class DeleteMessageAction extends ActionSupport{ private String id; private String message; public String getId() { return id; } public void setId(String id) { this.id = id; } public void validate(){ if(this.getId().equals("null")){ message("暂无学生信息!"); addFieldError("id","暂无学生信息!"); } } public String execute() throws Exception{ StudentDao dao=new StudentDao(); boolean del=dao.deleteInfo(this.getId()); if(del){ message="success"; } return message; } public void message(String mess){ int type=JOptionPane.YES_NO_OPTION; String title="提示信息"; JOptionPane.showMessageDialog(null, mess, title, type); } }
package studentAction; import Dao.StudentDao; import com.opensymphony.xwork2.ActionSupport; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.swing.JOptionPane; import org.apache.struts2.ServletActionContext; public class FindMessageAction extends ActionSupport{ private String id; private HttpServletRequest request; private String message="input"; public String getId() { return id; } public void setId(String id) { this.id = id; } public void validate(){ if(this.getId().equals("null")){ message("暂无学生信息!"); addFieldError("id","暂无学生信息!"); } } public String execute() throws Exception{ request=ServletActionContext.getRequest(); StudentDao dao=new StudentDao(); List list=dao.findInfo("id", this.getId()); request.getSession().setAttribute("oneInfo", list); message="success"; return message; } public void message(String mess){ int type=JOptionPane.YES_NO_OPTION; String title="提示信息"; JOptionPane.showMessageDialog(null, mess, title, type); } }
package studentAction; import Dao.StudentDao; import com.opensymphony.xwork2.ActionSupport; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; public class LookMessageAction extends ActionSupport{ private HttpServletRequest request; private String message="input"; public String execute() throws Exception{ request=ServletActionContext.getRequest(); StudentDao dao=new StudentDao(); List list=dao.findAllInfo(); request.getSession().setAttribute("count", list.size()); request.getSession().setAttribute("allInfo", list); message="success"; return message; } }
package studentAction; import Dao.StudentDao; import PO.Stuinfo; import com.opensymphony.xwork2.ActionSupport; import javax.swing.JOptionPane; public class UpdateMessageAction extends ActionSupport{ private String id; private String name; private String sex; private int age; private float weight; private String message="input"; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public float getWeight() { return weight; } public void setWeight(float weight) { this.weight = weight; } public void validate(){ if(this.getName()==null||this.getName().length()==0){ addFieldError("name","姓名不允许为空!"); } if(this.getAge()>130){ addFieldError("age","请认真核实年龄!"); } if(this.getWeight()>500){ addFieldError("weight","请认真核实体重!"); } } public String execute() throws Exception{ StudentDao dao=new StudentDao(); boolean update=dao.updateInfo(info()); if(update){ message="success"; } return message; } public Stuinfo info(){ Stuinfo info=new Stuinfo(); info.setId(this.getId()); info.setName(this.getName()); info.setSex(this.getSex()); info.setAge(this.getAge()); info.setWeight(this.getWeight()); return info; } public void message(String mess){ int type=JOptionPane.YES_NO_OPTION; String title="提示信息"; JOptionPane.showMessageDialog(null, mess, title, type); } }
<?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"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/stu</property><span style="white-space:pre"> </span><span style="font-family: Arial, Helvetica, sans-serif;"><!--stu是你建的数据库名--></span><span style="white-space:pre"> </span> <property name="hibernate.connection.username">root</property><span style="white-space:pre"> </span><!--数据库用户名--> <property name="hibernate.connection.password">1234</property><span style="white-space:pre"> </span><span style="font-family: Arial, Helvetica, sans-serif;"><!--数据库用户密码--></span><span style="white-space:pre"> </span> <mapping resource="PO/Stuinfo.hbm.xml"/> </session-factory> </hibernate-configuration>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- Configuration for the default package. --> <package name="default" extends="struts-default"> <action name="lookMessageAction" class="studentAction.LookMessageAction"> <result name="success">/student/lookMessage.jsp</result> <result name="input">/student/index.jsp</result> </action> <action name="addMessageAction" class="studentAction.AddMessageAction"> <result name="success" type="chain">lookMessageAction</result> <result name="input">/student/addMessage.jsp</result> </action> <action name="findMessageAction" class="studentAction.FindMessageAction"> <result name="success">/student/updateMessage.jsp</result> <result name="input">/student/findMessage.jsp</result> </action> <action name="updateMessageAction" class="studentAction.UpdateMessageAction"> <result name="success" type="chain">lookMessageAction</result> <result name="input">/student/updateMessage.jsp</result> </action> <action name="deleteMessageAction" class="studentAction.DeleteMessageAction"> <result name="success" type="chain">lookMessageAction</result> <result name="input">/student/deleteMessage.jsp</result> </action> </package> </struts>
<?xml version="1.0" encoding="UTF-8"?> <Context antiJARLocking="true" path="/ch15"/>
(1)addMessage.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><s:text name="学生信息管理系统-增加"/></title> </head> <body bgcolor="pink"> <s:div align="center"> <hr color="red"/> <br/> <table align="center" width="80%"> <tr> <td width="25%"> <s:a href="http://localhost:8080/ch15/student/lookMessage.jsp">查看学生信息</s:a> </td> <td width="25%"> 添加学生信息 </td> <td width="25%"> <s:a href="http://localhost:8080/ch15/student/findMessage.jsp">修改学生信息</s:a> </td> <td width="25%"> <s:a href="http://localhost:8080/ch15/student/deleteMessage.jsp">删除学生信息</s:a> </td> </tr> </table> <br/> <hr color="red"/> <center><font color="red" size="6">添加学生信息</font></center> </s:div> <s:form action="addMessageAction" method="post"> <table align="center" width="30%" bgcolor="gray" border="5"> <tr> <td> <s:textfield name="id" label="学号" maxLength="16"></s:textfield> </td> <td> <s:textfield name="name" label="姓名" maxLength="16"/> </td> <td> <s:select name="sex" label="性别" list="{'男','女'}"/> </td> <td> <s:textfield name="age" label="年龄"/> </td> <td> <s:textfield name="weight" label="体重"/> </td> <td colspan="2"> <s:submit value="提交"/> <s:reset value="清除"/> </td> </tr> </table> </s:form> </body> </html>
<%@page import="PO.Stuinfo"%> <%@page import="java.util.ArrayList"%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><s:text name="学生信息管理系统-删除"/></title> </head> <body bgcolor="pink"> <s:div align="center"> <hr color="red"/> <br/> <table align="center" width="80%"> <tr> <td width="25%"> <s:a href="http://localhost:8080/ch15/student/lookMessage.jsp">查看学生信息</s:a> </td> <td width="25%"> <s:a href="http://localhost:8080/ch15/student/addMessage.jsp">添加学生信息</s:a> </td> <td width="25%"> <s:a href="http://localhost:8080/ch15/student/findMessage.jsp">修改学生信息</s:a> </td> <td width="25%"> 删除学生信息 </td> </tr> </table> <br/> <hr color="red"/> <br/><br/><br/> <font size="5">删除学生信息</font> </s:div> <s:form action="deleteMessageAction" method="post"> <table align="center" width="40%" border="5"> <tr> <td> 请选择要删除学生的学号: </td> <td> <select name="id"> <% ArrayList list=(ArrayList)session.getAttribute("allInfo"); if(list.isEmpty()){ %> <option value="null">null</option> <% }else{ for(int i=0;i<list.size();i++){ Stuinfo info=(Stuinfo)list.get(i); %> <option value="<%=info.getId()%>"><%=info.getId()%></option> <% } } %> </select> </td> <td> <s:submit value="确定"></s:submit> </td> </tr> </table> </s:form> </body> </html>
<%@page import="java.util.ArrayList"%> <%@page import="PO.Stuinfo"%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><s:text name="学生信息管理系统-修改"/></title> </head> <body bgcolor="pink"> <s:div align="center"> <hr color="red"/> <br/> <table align="center" width="80%"> <tr> <td width="25%"> <s:a href="http://localhost:8080/ch15/student/lookMessage.jsp">查看学生信息</s:a> </td> <td width="25%"> <s:a href="http://localhost:8080/ch15/student/addMessage.jsp">添加学生信息</s:a> </td> <td width="25%"> 修改学生信息 </td> <td width="25%"> <s:a href="http://localhost:8080/ch15/student/deleteMessage.jsp">删除学生信息</s:a> </td> </tr> </table> <br/> <hr color="red"/> <br/><br/><br/> <font size="5">修改学生信息</font> </s:div> <s:form action="findMessageAction" method="post"> <table align="center" width="40%" border="5"> <tr> <td> 请选择要修改学生的学号: </td> <td> <select name="id"> <% ArrayList list=(ArrayList)session.getAttribute("allInfo"); if(list.isEmpty()){ %> <option value="null">null</option> <% }else{ for(int i=0;i<list.size();i++){ Stuinfo info=(Stuinfo)list.get(i); %> <option value="<%=info.getId()%>"><%=info.getId()%></option> <% } } %> </select> </td> <td> <s:submit value="确定"></s:submit> </td> </tr> </table> </s:form> </body> </html>
<%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><s:text name="基于SH的学生信息管理-起始页"/></title> </head> <body bgcolor="#CCCCFF"> <s:div align="center"> <br/><br/><br/><br/><br/> <font color="black" size="6">基于Struts2+Hibernate的学生信息管理系统实例,可对学生信息进行增、删、改、查!</font> <br/><br/><br/> <s:a href="lookMessageAction"><font color="blue" size="6">点此进入</font></s:a> </s:div> </body> </html>
<%@page contentType="text/html" pageEncoding="UTF-8" import="java.util.ArrayList,PO.Stuinfo"%> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>学生信息管理系统-查看</title> </head> <body bgcolor="pink"> <s:div align="center"> <hr color="red"/> <br/> <table align="center" width="80%"> <tr> <td width="25%"> 查看学生信息 </td> <td width="25%"> <s:a href="http://localhost:8080/ch15/student/addMessage.jsp">添加学生信息</s:a> </td> <td width="25%"> <s:a href="http://localhost:8080/ch15/student/findMessage.jsp">修改学生信息</s:a> </td> <td width="25%"> <s:a href="http://localhost:8080/ch15/student/deleteMessage.jsp">删除学生信息</s:a> </td> </tr> </table> <br/> <hr color="red"/> <br/><br/><br/> <span>你要查询的数据表中共有<%=request.getSession().getAttribute("count")%>人</span> </s:div> <table align="center" width="80%" border="5"> <tr> <th>记录条数</th> <th>学号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>体重</th> </tr> <% ArrayList list=(ArrayList)session.getAttribute("allInfo"); if(list.isEmpty()){ %> <tr> <td align="center"> <span>暂无学生信息!</span> </td> </tr> <% }else{ for(int i=0;i<list.size();i++){ Stuinfo info=(Stuinfo)list.get(i); %> <tr> <td align="center"><%=i+1%></td> <td><%=info.getId()%></td> <td><%=info.getName()%></td> <td><%=info.getSex()%></td> <td><%=info.getAge()%></td> <td><%=info.getWeight()%></td> </tr> <% } } %> </table> </body> </html>
<%@page import="PO.Stuinfo"%> <%@page import="java.util.ArrayList"%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>学生信息管理系统-修改</title> </head> <body bgcolor="pink"> <s:div align="center"> <hr color="red"/> <br/> <table align="center" width="80%"> <tr> <td width="25%"> <s:a href="http://localhost:8080/ch15/student/lookMessage.jsp">查看学生信息</s:a> </td> <td width="25%"> <s:a href="http://localhost:8080/ch15/student/addMessage.jsp">添加学生信息</s:a> </td> <td width="25%"> 修改学生信息 </td> <td width="25%"> <s:a href="http://localhost:8080/ch15/student/deleteMessage.jsp">删除学生信息</s:a> </td> </tr> </table> <br/> <hr color="red"/> <br/><br/><br/> <font size="5">修改学生信息</font> </s:div> <s:form action="updateMessageAction" method="post"> <table align="center" width="30%" bgcolor="gray" border="5"> <% ArrayList list=(ArrayList)session.getAttribute("oneInfo"); Stuinfo info=(Stuinfo)list.get(0); %> <tr> <td> 学号 </td> <td> <input name="id" value="<%=info.getId()%>" readonly="readonly"/> </td> </tr> <tr> <td> 姓名 </td> <td> <input name="name" value="<%=info.getName()%>"/> </td> </tr> <tr> <td> 性别 </td> <td> <input name="sex" value="<%=info.getSex()%>"/> </td> </tr> <tr> <td> 年龄 </td> <td> <input name="age" value="<%=info.getAge()%>"/> </td> </tr> <tr> <td> 体重 </td> <td> <input name="weight" value="<%=info.getWeight()%>"/> </td> </tr> <tr> <td colspan="2"> <s:submit value="提交"></s:submit> </td> </tr> <tr> <td align="center" colspan="2"> <s:a href="http://localhost:8080/ch15/student/findMessage.jsp">返回</s:a> </td> </tr> </table> </s:form> </body> </html>
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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_3_0.xsd"> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>