hibernate+servlet+mysql 实现easypoi_记录-Hibernate+servlet实现简单的增、删、查、改

本文档介绍了一个使用Hibernate、Servlet和MySQL数据库实现的简单用户管理系统的搭建过程,包括Hibernate配置文件设置、Servlet路径映射、用户注册、查询、删除功能的实现。在开发过程中遇到了Tomcat启动报错和XML配置文件路径跳转问题,但通过调整解决了问题。
摘要由CSDN通过智能技术生成

由于需要对Hibernate作个了解,所以写了个简单的实现

7d8f11c42c3c9d770fc68653292cdb5c.png

以上是大概目录

1.新建Hibernate.cfg.xml配置文件

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

/p>

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

root

jdbc:mysql://localhost:3306/hiber?characterEncoding=utf8

org.hibernate.dialect.MySQLDialect

mysqlJdbcDriver

123456

com.mysql.jdbc.Driver

true

true

update

View Code

2.修改web.xml 路径映射

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

tHIbe

userServlet

servlet.userServlet

userServlet

*.do

index.html

index.htm

index.jsp

default.html

default.htm

default.jsp

View Code

3.路径跳转的servlet类

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packageservlet;importjava.io.IOException;importjava.util.ArrayList;importjava.util.List;importjavax.servlet.RequestDispatcher;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importcom.sun.org.apache.bcel.internal.generic.Select;importentity.User;importservice.UserService;importservice.impl.UserServiceImpl;public class userServlet extendsHttpServlet{/****/

private static final long serialVersionUID = 1L;

UserService userService=newUserServiceImpl();public void execute(HttpServletRequest request, HttpServletResponse response ) throwsIOException{

System.out.println("进入次类");

String path=request.getServletPath();

path= path.substring(0, path.indexOf("."));

request.setCharacterEncoding("utf8");

response.setContentType("text/html;charset=utf8");if (path.equals("/goReg")) {

RequestDispatcher dispatcher=request.getRequestDispatcher("/WEB-INF/jsp/reg.jsp");try{

dispatcher.forward(request, response);

}catch(ServletException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}else if(path.equals("/reg")){

regUser(request,response);try{

request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response);

}catch(ServletException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}else if(path.equals("/select")){

select(request,response);try{

request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response);

}catch(ServletException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}else if(path.equals("/delete")){

delete(request,response);try{

request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response);

}catch(Exception e) {

e.printStackTrace();

}

}

}public voidregUser(HttpServletRequest req,HttpServletResponse resp){

System.out.println("进行注册");

String name=req.getParameter("name");

String pwd=req.getParameter("pwd");

User user=newUser();

user.setName(name);

user.setPwd(pwd);

userService.addUser(user);

req.setAttribute("user", user);

}public voidselect(HttpServletRequest req,HttpServletResponse resp){

System.out.println("查询中");

List list=new ArrayList<>();

list=userService.select();

req.setAttribute("list", list);

}public voiddelete(HttpServletRequest req,HttpServletResponse resp){

Integer id=Integer.parseInt(req.getParameter("name"));int result=userService.delete(id);if(result==1){

req.setAttribute("msg", "成功kill");

}

System.out.println(result);

}

@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throwsServletException, IOException {

System.out.println("haha ");

execute(req,resp);

}

@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throwsServletException, IOException {//TODO Auto-generated method stub

doGet(req, resp);

}

}

View Code

4.新建Hibernate工具类(主要用来在dao的实现类里面创建session、关闭session等)

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packageutil;importorg.hibernate.HibernateException;importorg.hibernate.Session;importorg.hibernate.SessionFactory;importorg.hibernate.cfg.Configuration;public classHibernateUtil {private static finalSessionFactory sessionFactory;static{try{

Configuration config= new Configuration().configure("hibernate.cfg.xml");

sessionFactory=config.buildSessionFactory();

}catch(Throwable e)

{throw newExceptionInInitializerError(e);

}

}public static final ThreadLocal session = newThreadLocal();public static Session currentSession() throwsHibernateException

{

Session s=(Session)session.get();//Open a new Session,if this Thread has none yet

if(s == null || !s.isOpen())

{

s=sessionFactory.openSession();

session.set(s);

}returns;

}public static void closeSession() throwsHibernateException

{

Session s=(Session)session.get();

session.set(null);if(s != null)

s.close();

}

}

View Code

5.dao层实现类代码参考

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagedao.impl;importjava.util.List;importorg.hibernate.Query;importorg.hibernate.Session;importorg.hibernate.Transaction;importdao.UserDao;importentity.User;importutil.HibernateUtil;public class UserDaoImpl implementsUserDao {

@Overridepublic voidaddUser(User user) {//TODO Auto-generated method stub

Session session =HibernateUtil.currentSession();

Transaction tx=session.beginTransaction();try{

session.save(user);//保存次酒类对象

tx.commit();//提交到数据库

session.close();

}catch(Exception e) {

e.printStackTrace();

tx.rollback();

}

}

@Overridepublic Listselect() {

Session session=HibernateUtil.currentSession();//Transaction tx=session.beginTransaction();

List list=null;try{

String hql="from User";//使用命名参数,推荐使用,易读。

Query query=session.createQuery(hql);

list=query.list();//tx.commit();//提交到数据库

session.close();returnlist;

}catch(Exception e) {

e.printStackTrace();

}returnlist;

}

@Overridepublic intdelete(Integer id) {

Session session=HibernateUtil.currentSession();

Transaction tx=session.beginTransaction();try{

User user=(User)session.get(User.class, id);

session.delete(user);

tx.commit();

session.close();

}catch(Exception e) {

e.printStackTrace();

tx.rollback();return 0;

}return 1;

}

}

View Code

6.User实体类的映射文件User.hbm.xml,和数据的关联文件(需要在Hibernate.cfg.xml配置文件中引入)

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

/p>

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

View Code

7.User实体类(注意要实现 implements Serializable)

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packageentity;importjava.io.Serializable;/*** 持久化user类

*@authorAdministrator

**/

public class User implementsSerializable{private intid;privateString name;privateString pwd;public User(intid, String name, String pwd) {super();this.id =id;this.name =name;this.pwd =pwd;

}publicUser() {

}public intgetId() {returnid;

}public void setId(intid) {this.id =id;

}publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}publicString getPwd() {returnpwd;

}public voidsetPwd(String pwd) {this.pwd =pwd;

}

}

View Code

8.jsp页面

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

主页

functiondianji(){

window.location.href='select.do'};functionkill(){

window.location.href='delete.do?name=${list.get(1).id}'}functionok(){varname=document.getElementById("newName").value;

window.location.href='update.do?name='+name

}


点击下方按钮:


最强王者是:${list.get(1).name}
看我的

${msg}

你已成为最强王者请修改你的名称:

View Code

在项目遇到的问题有:

1.启动tomcat时 报无法启动的错误,错误可能在xml配置文件

2.xml配置的路径跳转不能跳转,同样的代码,重新建项目后又可以了,不知道什么原因

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值