准备工作:
1、新建工程StudentMessageManagerSystem:File→New→WebProject→ProjectName→Finish
2、导入数据库驱动文件WebRoot下的WEB-INF下的lib,右键Import→FileSystem,然后选择驱动文件。
3、导入MyEclipse自带的Struts:工程名右键→MyEclipse→Add Struts Capabilities→Struts specification→Struts 2.1→Finish
4、导入MyEclipse自带的Hibernate架包:工程名右键→MyEclipse→Add Hibernate Capabilities→Hibernate specification→hibernate 4.1→Next→Next→
jdbc:mysql://localhost:3306/test
com.mysql.jdbc.Driver
root
0514
第一个test为数据库名;0514为我的数据库密码。
(这个配置在hibernate.cfg.xml中,后面还需要继续配置,我下面会贴出)
5、工程结构图如下:
具体代码:
addMessage.jsp
<%@ page contentType="text/html" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<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">
<s:include value="menu.jsp">
<s:param name="oper">2s:param>
s:include>
<center><font color="red" size="6">添加学生信息font>center>
s:div>
<s:form action="addMessage" method="post">
<table align="center" width="30%" bgcolor="gray" border="5">
<tr>
<td>
<s:textfield name="stuinfo.id" label="学号" maxLength="16">s:textfield>
td>
<td>
<s:textfield name="stuinfo.name" label="姓名" maxLength="16">s:textfield>
td>
<td>
<s:select name="stuinfo.sex" label="性别" list="{'男','女 '}">s:select>
td>
<td>
<s:textfield name="stuinfo.age" label="年龄">s:textfield>
td>
<td>
<s:textfield name="stuinfo.weight" label="体重">s:textfield>
td>
<td colspan="2">
<s:submit value="提交">s:submit>
<s:reset value="清除">s:reset>
td>
tr>
table>
s:form>
body>
html>
AddMessage.java代码如下:
package action;
import java.util.List;
import po.Stuinfo;
import com.opensymphony.xwork2.ActionSupport;
import dao.StudentDao;
import javax.persistence.Entity;
@Entity
public class AddMessage extends ActionSupport{
private Stuinfo stuinfo;
public Stuinfo getStuinfo() {
return stuinfo;
}
public void setStuinfo(Stuinfo stuinfo) {
this.stuinfo = stuinfo;
}
public void validate() {
if(stuinfo.getId()==null||stuinfo.getId().length()==0){
addFieldError("stuinfo.id", "id不能为空!");
}else{
StudentDao studentDao =new StudentDao();
List list = studentDao.findInfo("id",stuinfo.getId());
if(!list.isEmpty()){
addFieldError("stuinfo.id", "id不能重复");
}
}
if(stuinfo.getName()==null||stuinfo.getName().length()==0){
addFieldError("stuinfo.name", "姓名不能为空");
}
if(stuinfo.getAge()>130){
addFieldError("stuinfo.age", "年龄值非法");
}
if(stuinfo.getWeight()>500){
addFieldError("stuinfo.weight", "体重值非法");
}
}
public String execute()throws Exception {
StudentDao dao=new StudentDao();
String message="input";
boolean save=dao.saveInfo(stuinfo);
if(save){
message="success";
}
return message;
}
}
deleteMessage.jsp代码如下:
<%@ page language="java" import="java.util.*,po.Stuinfo" pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title><s:text name="学生信息管理系统-删除">s:text>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">
head>
<body bgcolor="pink">
<s:div align="center">
<s:include value="menu.jsp">
<s:param name="oper">2s:param>
s:include>
<center><font color="red" size="6">删除学生信息font>center>
s:div>
<s:form action="deleteMessage" method="post">
<table align="center" width="30%" bgcolor="gray" border="5">
<tr>
<td>
<select name="id">
<%
ArrayList list = (ArrayList)session.getAttribute("allInfo");
if(list.isEmpty()){
%>
<option value="null">nulloption>
<%
}else{
for(int i=0;iget (i);
%>
<option value="<%=info.getId() %>">
<%=info.getId() %>
option>
<%
}
}
%>
select>
td>
<td>
<s:submit value="确定">s:submit>
td>
tr>
table>
s:form>
body>
html>
DeleteMessage.java代码如下:
package action;
import javax.swing.JOptionPane;
import dao.StudentDao;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.finder.ClassFinder.Info;
public class DeleteMessage 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_CANCEL_OPTION;
String title="提示信息";
JOptionPane.showMessageDialog(null, mess, title, type);
}
}
findMessage.jsp代码如下:
<%@ page language="java" import="java.util.*,po.Stuinfo" pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title><s:text name="学生信息管理系统-修改">s:text>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">
head>
<body bgcolor="pink">
<s:div align="center">
<s:include value="menu.jsp">
<s:param name="oper">2s:param>
s:include>
<center><font color="red" size="6">修改学生信息font>center>
s:div>
<s:form action="findMessage" 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">nulloption>
<%
}else{
for(int i=0;iget (i);
%>
<option value="<%=info.getId()%>">
<%=info.getId() %>
option>
<%
}
}
%>
select>
td>
<td><s:submit value="确定">s:submit>td>
tr>
table>
s:form>
body>
html>
updateMessage.jsp代码如下:
<%@ page language="java" import="java.util.*,po.Stuinfo,java.util.ArrayList" pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title><s:text name="学生信息管理系统-修改">s:text>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">
head>
<body bgcolor="pink">
<s:div align="center">
<s:include value="menu.jsp">
<s:param name="oper">2s:param>
s:include>
<center><font color="red" size="6">修改学生信息font>center>
s:div>
<s:form action="updateMessage" 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>
table>
s:form>
body>
html>
lookMessage.jsp代码如下:
<%@ page language="java" import="java.util.*,po.Stuinfo" pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title><s:text name="学生管理系统-查看">s:text>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">
head>
<body bgcolor="pink">
<s:div align="center">
<s:include value="menu.jsp">
<s:param name="oper">2s:param>
s:include>
<center><font color="red" size="6">查看学生信息font>center>
<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;iget (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>
menu.jsp代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<a href="lookMessage.jsp">查看学生信息a>
<a href="addMessage.jsp">添加学生信息a>
<a href="findMessage.jsp">修改学生信息a>
<a href="deleteMessage.jsp">删除学生信息a>
FindMessage.java代码如下:
package action;
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 FindMessage 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 message) {
int type = JOptionPane.YES_NO_CANCEL_OPTION;
String title = "提示信息";
JOptionPane.showMessageDialog(null, message, title, type);
}
}
LookMessage.java代码如下:
package action;
import dao.StudentDao;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import po.Stuinfo;
public class LookMessage 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();
// System.out.println(list.size());
// System.out.println(list);
request.getSession().setAttribute("count", list.size());
request.getSession().setAttribute("allInfo", list);
message="success";
return message;
}
}
UpdateMessage.java代码如下:
package action;
import dao.StudentDao;
import po.Stuinfo;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.finder.ClassFinder.Info;
import javax.swing.JOptionPane;
public class UpdateMessage 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.setAge(this.getAge());
info.setId(this.getId());
info.setName(this.getName());
info.setWeight(this.getWeight());
info.setSex(this.getSex());
return info;
}
public void message(String mess) {
int type=JOptionPane.YES_NO_CANCEL_OPTION;
String title="提示信息";
JOptionPane.showMessageDialog(null, mess, title, type);
}
}
dao包中的StudentDao.java代码如下:
package dao;
import java.util.List;
import javax.swing.JOptionPane;
import po.Stuinfo;
import util.HibernateSessionFactory;
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 stuinfo) {
try{
session=HibernateSessionFactory.getSession();
transaction=session.beginTransaction();
session.save(stuinfo);
transaction.commit();
session.close();
return true;
}catch (Exception e){
message("saveInfo.error:"+e);
HibernateSessionFactory.closeSession();
e.printStackTrace();
return false;
}
}
public List findInfo(String string, Object value) {//待完成
session=HibernateSessionFactory.getSession();
try{
transaction=session.beginTransaction();
// HQL语句
String hql="from Stuinfo as model where model."+string+"=?";
//持久化类名Stuinfo,别名model
query=session.createQuery(hql);
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);
@SuppressWarnings("unchecked")
List list=query.list();
transaction.commit();
session.close();
return list;
} catch (Exception e) {
message("findInfo.error:"+e);
e.printStackTrace();
return null;
// TODO: handle exception
}
}
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;
// TODO: handle exception
}
}
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);
return false;
// TODO: handle exception
}
}
public void message(String mess){
int type = JOptionPane.YES_NO_CANCEL_OPTION;
String title = "提示信息";
JOptionPane.showMessageDialog(null, mess,title,type);
}
}
po包中的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 id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
System.out.println(name);
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;
}
}
数据库映射文件Stuinfo.hbm.xml代码如下:
<hibernate-mapping>
<class name="po.Stuinfo" table="stuinfo" catalog="student">
<id name="id" type="string">
<column name="id" length="20">column>
<generator class="assigned">generator>
id>
<property name="name" type="string">
<column name="name" length="20" not-null="true">column>
property>
<property name="sex" type="string">
<column name="sex" length="5" not-null="true">column>
property>
<property name="age" type="int">
<column name="age" not-null="true">column>
property>
<property name="weight" type="float">
<column name="weight" precision="10" scale="0" not-null="true">column>
property>
class>
hibernate-mapping>
util包中的HIbernateSessionFactory.java代码如下:
package util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateSessionFactory {
private static final ThreadLocal threadLocal = new ThreadLocal();
//使用ThreadLocal类管理对象session,***********threadLocal=session**********
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
//***************************cfg即configuration****************************
private static ServiceRegistry serviceRegistry;
static {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
public static Session getSession() throws HibernateException {
//getSession=getThreadLocalSession
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory() {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Configuration getConfiguration() {
return configuration;
}
}
hibernate配置文件hibernate.cfg.xml代码如下:
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">updateproperty>
<property name="dialect">org.hibernate.dialect.MySQLDialectproperty>
<property name="connection.url">jdbc:mysql://localhost:3306/testproperty>
<property name="connection.useUnicode">trueproperty>
<property name="connection.characterEncoding">utf-8property>
<property name="connection.username">rootproperty>
<property name="connection.password">0514property>
<property name="connection.driver_class">com.mysql.jdbc.Driverproperty>
<mapping resource="po/Stuinfo.hbm.xml"/>
session-factory>
hibernate-configuration>
Struts配置文件struts.xml代码如下:
<struts>
<package name="action" extends="struts-default">
<action name="lookMessage" class="action.LookMessage">
<result name="success">/lookMessage.jspresult>
<result name="input">/index.jspresult>
action>
<action name="addMessage" class="action.AddMessage">
<result name="success" type="chain">lookMessageresult>
<result name="input">/addMessage.jspresult>
action>
<action name="findMessage" class="action.FindMessage">
<result name="success">/updateMessage.jspresult>
<result name="input">/findMessage.jspresult>
action>
<action name="updateMessage" class="action.UpdateMessage">
<result name="success" type="chain">lookMessageresult>
<result name="input">/updateMessage.jspresult>
action>
<action name="deleteMessage" class="action.DeleteMessage">
<result name="success" type="chain">lookMessageresult>
<result name="input">/deleteMessage.jspresult>
action>
package>
struts>
Web配置文件web.xml代码如下:
<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">
<display-name>display-name>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
<filter>
<filter-name>struts2filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
filter-class>
filter>
<filter-mapping>
<filter-name>struts2filter-name>
<url-pattern>*.jspurl-pattern>
filter-mapping>
<filter-mapping>
<filter-name>struts2filter-name>
<url-pattern>/*url-pattern>
filter-mapping>web-app>