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>&nbsp;&nbsp;<a href="student_deleteStudent?id=${student.id }">删除</a></td>
</tr>

</c:forEach>

</table>
<h3><span><a href="student_findStudents.action?page=${page-1 }">上一页</a>&nbsp;
<a href="student_findStudents.action?page=${page+1 }">下一页</a>&nbsp;
当前是第${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>
时间: 2024-10-07 21:49:01

struts+hibernate 请求数据库增删改查(小项目实例)的相关文章

Hibernate学习-------数据库增删改查操作(部分)

(1)增加和删除 <span style="white-space:pre"> </span>@Test public void test() { EStudent student=new EStudent(); student.setName("张三"); student.setSex("男"); Session session=sf.openSession(); session.beginTransaction();

Java+MyEclipse+Tomcat (六)详解Servlet和DAO数据库增删改查操作

此篇文章主要讲述DAO.Java Bean和Servlet实现操作数据库,把链接数据库.数据库操作.前端界面显示分模块化实现.其中包括数据的CRUD增删改查操作,并通过一个常用的JSP网站前端模板界面进行描述.参考前文: Java+MyEclipse+Tomcat (一)配置过程及jsp网站开发入门 Java+MyEclipse+Tomcat (二)配置Servlet及简单实现表单提交 Java+MyEclipse+Tomcat (三)配置MySQL及查询数据显示在JSP网页中 Java+MyE

Rhythmk 学习 Hibernate 01 - maven 创建Hibernate 项目之 增删改查入门

1.环境: Maven :3.1.1 开发工具:Spring Tool Suite 数据库 : Mysql  5.6 2.项目文件结构 文件代码: 2.1 .pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.ap

go——beego的数据库增删改查

一直都不理解使用go语言的时候,为什么还要自己去装beego,以为使用go便可以解决所有的问题,结果在朋友的点拨下,才意识到: go与beego的关系就好比是nodejs与thinkjs的关系,因此也就不怎么存在疑问为什么还要继续安装beego来完成项目运行了,beego其实就是一个快速开发Go应用的http框架,go 语言方面技术大牛,可以用来快速开发API.Web.后端服务等各种应用,是一个RESTFul的框架.再次附上beego的官网(http://beego.me/docs/intro/

Mybatis实现简单的数据库增删改查操作

Mybatis实现简单的数据库增删改查操作 框架:mybatis(3.5.2) 数据库:mysql 工具:idea 1.新建一个maven项目,在pom文件中添加mybatis依赖及MySQL依赖 <!-- mybatis核心依赖 --> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId&g

【Android】Sqlite数据库增删改查

Android系统内置一个Sqlite数据库,如果app需要使用Sqlite数据库数据库存储数据,Android会为此app生成一个.db文件.这个数据库在data/data/<package_name>/databases里面,其中<package_name>为该安卓app的工程包名,这个目录必须root后才能看到.在Windows,单机的应用程序,存储数据,基本放到一个文件里面,正如游戏的存档,基本就是把当前的游戏状态存到一个用户很难找到的文件里面.每次存档读档就是一个从这个存

(转)SQLite数据库增删改查操作

原文:http://www.cnblogs.com/linjiqin/archive/2011/05/26/2059182.html SQLite数据库增删改查操作 一.使用嵌入式关系型SQLite数据库存储数据 在Android平台上,集成了一个嵌入式关系型数据库--SQLite,SQLite3支持NULL.INTEGER.REAL(浮点数字).TEXT(字符串文本)和BLOB(二进制对象)数据类型,虽然它支持的类型只有五种,但实际上sqlite3也接受varchar(n).char(n).d

Yii2.0高级框架数据库增删改查的一些操作(转)

yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 ----------------------------------------------------------------------------------------------------- User::find()->all();    //返回所有用户数据:User::findOne($id);   //返回 主键 id=1  的一条数

Yii2.0高级框架数据库增删改查的一些操作

yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 ----------------------------------------------------------------------------------------------------- User::find()->all();    //返回所有用户数据:User::findOne($id);   //返回 主键 id=1  的一条数