struts+hibernate 请求数据库增删改查(小项目实例)
StudentAction.java
package com.action; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.omg.CORBA.Request; import com.dao.StudentDao; import com.dao.imp.StudentDaoImp; import com.entity.Student; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class StudentAction extends ActionSupport{ private StudentDao dao=new StudentDaoImp(); public StudentDao getDao() { return dao; } public void setDao(StudentDao dao) { this.dao = dao; } private int id; private String name; private String password; private String email; private String sex; private int age; private int page=1; private Student student=new Student(); 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; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } 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 int getPage() { return page; } public void setPage(int page) { this.page = page; } @Override public void validate() { // TODO Auto-generated method stub if(student.getName()==null||student.getName().trim().equals("")) { this.addFieldError("name", "姓名不能为空"); } if(student.getPassword()==null||student.getPassword().trim().equals("")) { this.addFieldError("password", "密码不能为空"); } } //重写validate()校验方法 public String findStudents(){ /*耦合方式 * HttpServletRequest request=ServletActionContext.getRequest(); HttpServletResponse response=ServletActionContext.getResponse(); */ ActionContext ctx=ActionContext.getContext(); Map request=(Map)ctx.get("request"); //可以直接拿到session ctx.getSession(); //ctx.getApplication(); List<Student> students=dao.getStudentsByPage("from Student",page); //存放到request 属性里面返回前台 //page已经在配置成属性 不用set前台也能获得到 request.put("students", students); //通过拦截器将其放到attribute里 /*耦合方式request.setAttribute("students", students);*/ //request.getSession().getServletContext();可以拿到session //servlet中的都可以拿得到 return "findStudents"; } public String saveStudent(){ student.setId(id); student.setAge(age); student.setName(name); student.setEmail(email); student.setPassword(password); student.setSex(sex); dao.saveStudent(student); return "saveStudent"; } public String deleteStudent(){ dao.deleteStudent(id); return "deleteStudent"; } }
student.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <constant name="struts.devMode" value="false" /> <package name="student" namespace="/student" extends="struts-default"> <action name="student_*" class="com.action.StudentAction" method="{1}"> <result name ="saveStudent" type="chain">student_findStudents</result> <!-- action之间的跳转 type="chain"--> <result name ="deleteStudent" type="chain">student_findStudents</result> <result name ="findStudents">/student.jsp</result> <result name="input">/student_add.jsp</result> <!-- 出现错误返回当前页面 --> </action> </package> </struts>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <include file ="config/student.xml"></include> </struts>
student.java
package com.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Student{ @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; private String name; private String password; private String email; private String sex; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getId() { return id; } public void setId(int id) { this.id = id; } private int age; public Student() { super(); } public Student(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
studentDao.java
package com.dao; import java.util.List; import com.entity.Student; public interface StudentDao { public void saveStudent(Student student); public void deleteStudent(int id); public List<Student> getStudents(String hql); public List<Student> getStudentsByPage(String hql,int page) ; }
StudentDaoImp.java
package com.dao.imp; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import com.dao.StudentDao; import com.entity.Student; import com.util.HibernateUtils; public class StudentDaoImp implements StudentDao { private int pageSize=10; @Override public void saveStudent(Student student) { // TODO Auto-generated method stub Session session=HibernateUtils.getSession(); Transaction tx=session.beginTransaction(); session.saveOrUpdate(student); tx.commit(); HibernateUtils.closeSession(session); } @Override public void deleteStudent(int id) { // TODO Auto-generated method stub Session session=HibernateUtils.getSession(); Transaction tx=session.beginTransaction(); // 1.sessionɾ�� Student stu=(Student)session.get(Student.class, id); session.delete(stu); //2.����query�ӿ�ɾ�� session.createQurey(delete from Student where id=??) //q.executeUpdate() tx.commit(); HibernateUtils.closeSession(session); } @Override public List<Student> getStudents(String hql) { // TODO Auto-generated method stub Session session=HibernateUtils.getSession(); Query q=session.createQuery(hql); return q.list(); } @Override public List<Student> getStudentsByPage(String hql,int page) { // TODO Auto-generated method stub Session session=HibernateUtils.getSession(); Query q=session.createQuery(hql); int begin=(page-1)*pageSize+1; q.setFirstResult(begin-1).setMaxResults(pageSize); return q.list(); } }
前台页面student.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <link href="${pageContext.request.contextPath}/css/bootstrap.css" type="text/css" rel="stylesheet"/> <script type="text/javascript" src="js/jquery-2.0.3.min.js"></script> <script type="text/javascript" src="js/bootstrap.js"></script> <style type="text/css"> h1,h3,table{ margin: 0 auto; text-align: center; } </style> </head> <body> <h1>学生信息表</h1> <table class="table table-striped table-bordered"> <tr><td>学号</td><td>姓名</td><td>年龄</td><td>操作</td> <c:forEach items="${requestScope.students}" var="student"> <tr><td>${student.id }</td><td>${student.name}</td><td>${student.age }</td> <td><a href="saveStudentServlet?id=${student.id }">更新</a> <a href="student_deleteStudent?id=${student.id }">删除</a></td> </tr> </c:forEach> </table> <h3><span><a href="student_findStudents.action?page=${page-1 }">上一页</a> <a href="student_findStudents.action?page=${page+1 }">下一页</a> 当前是第${page }页 <%-- a href="student_findStudents.action?page=${page-1 }" --%> <!-- student是action name findstudents是方法 也可以写绝对目录 /项目名称/namespace/actionname.action--> </span></h3> </body> </html>
student_add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <link href="${pageContext.request.contextPath}/css/bootstrap.css" type="text/css" rel="stylesheet"/> <script type="text/javascript" src="js/jquery-2.0.3.min.js"></script> <script type="text/javascript" src="js/bootstrap.js"></script> <style type="text/css"> h1,h3,table{ margin: 0 auto; text-align: center; } input{width:200px} </style> </head> <body> <div class="container" style="width:500px;height: 500px"> <h1>增加学生信息</h1> <form role="form" action="student/student_saveStudent" method="post"> <input type="hidden" value="${stu.id }" name="id"/> <div class="form-group"> <label for="email">邮箱</label> <input type="email" class="form-control" value="${stu.email }" name="email" id="email" placeholder="Enter email"> </div> <div class="form-group"> <label for="name">姓名</label> <input type="text" class="form-control" name="name" value="${stu.name }" id="name" placeholder="name"> </div> <div class="form-group"> <label for="password">密码</label> <input type="password" class="form-control" name="password" value="${stu.password }" id="password" placeholder="Password"> </div> <div class="form-group"> <label for="age">年龄</label> <input type="text" class="form-control" id="age" name="age" value="${stu.age }"> </div> <div class="radio"> <label> <input type="radio" class="form-control" id="sex" name="sex" value="male"/>男 <input type="radio" class="form-control" id="sex1" name="sex" value="female" checked="checked"/>女 </label> </div> <button type="submit" class="btn btn-default">保存</button> </form> </div> </body> </html>