由于需要对Hibernate作个了解,所以写了个简单的实现
以上是大概目录
1.新建Hibernate.cfg.xml配置文件
<?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"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="connection.username">root</property> <property name="connection.url"> jdbc:mysql://localhost:3306/hiber?characterEncoding=utf8 </property> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="myeclipse.connection.profile"> mysqlJdbcDriver </property> <property name="connection.password">123456</property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping resource="/entity/User.hbm.xml"/> </session-factory> </hibernate-configuration>
2.修改web.xml 路径映射
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>tHIbe</display-name> <servlet> <servlet-name>userServlet</servlet-name> <servlet-class>servlet.userServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>userServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
3.路径跳转的servlet类
package servlet; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.sun.org.apache.bcel.internal.generic.Select; import entity.User; import service.UserService; import service.impl.UserServiceImpl; public class userServlet extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; UserService userService=new UserServiceImpl(); public void execute(HttpServletRequest request, HttpServletResponse response ) throws IOException{ 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 void regUser(HttpServletRequest req,HttpServletResponse resp){ System.out.println("进行注册"); String name=req.getParameter("name"); String pwd=req.getParameter("pwd"); User user=new User(); user.setName(name); user.setPwd(pwd); userService.addUser(user); req.setAttribute("user", user); } public void select(HttpServletRequest req,HttpServletResponse resp){ System.out.println("查询中"); List<User> list=new ArrayList<>(); list=userService.select(); req.setAttribute("list", list); } public void delete(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); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("haha "); execute(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doGet(req, resp); } }
4.新建Hibernate工具类(主要用来在dao的实现类里面创建session、关闭session等)
package util; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { Configuration config = new Configuration().configure("hibernate.cfg.xml"); sessionFactory = config.buildSessionFactory(); } catch(Throwable e) { throw new ExceptionInInitializerError(e); } } public static final ThreadLocal session = new ThreadLocal(); public static Session currentSession() throws HibernateException { 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); } return s; } public static void closeSession() throws HibernateException { Session s = (Session)session.get(); session.set(null); if(s != null) s.close(); } }
5.dao层实现类代码参考
package dao.impl; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import dao.UserDao; import entity.User; import util.HibernateUtil; public class UserDaoImpl implements UserDao { @Override public void addUser(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(); } } @Override public List<User> select() { Session session = HibernateUtil.currentSession(); //Transaction tx=session.beginTransaction(); List<User> list=null; try { String hql="from User";//使用命名参数,推荐使用,易读。 Query query=session.createQuery(hql); list=query.list(); //tx.commit();//提交到数据库 session.close(); return list; } catch (Exception e) { e.printStackTrace(); } return list; } @Override public int delete(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; } }
6.User实体类的映射文件User.hbm.xml,和数据的关联文件(需要在Hibernate.cfg.xml配置文件中引入)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="entity"> <class name="User" table="user"> <id name="id" column="id"> <generator class="identity"></generator> </id> <property name="name" column="name" unique="true"></property> <property name="pwd" column="pwd"></property> </class> </hibernate-mapping>
7.User实体类(注意要实现 implements Serializable)
package entity; import java.io.Serializable; /** * 持久化user类 * @author Administrator * */ public class User implements Serializable{ private int id; private String name; private String pwd; public User(int id, String name, String pwd) { super(); this.id = id; this.name = name; this.pwd = pwd; } public User() { } 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 getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }
8.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>主页</title> <script type="text/javascript"> function dianji(){ window.location.href='select.do' }; function kill(){ window.location.href='delete.do?name=${list.get(1).id}' } function ok(){ var name=document.getElementById("newName").value; window.location.href='update.do?name='+name } </script> </head> <body> 欢迎你:${suser.name},你将走向最强王者之路<br/> 点击下方按钮:<br/> <input type="button" value="查询最强王者" onclick="dianji()"/><br/> 最强王者是:${list.get(1).name}<br/> 看我的<br/> <input type="button" value="kill you!" onclick="kill()"/> <p>${msg}</p> 你已成为最强王者请修改你的名称:<input type="text" name="name" id="newName" placeholder="请输入你的新昵称" /><input type="button" value="确定" onclick="ok()"/> </body> </html>
在项目遇到的问题有:
1.启动tomcat时 报无法启动的错误,错误可能在xml配置文件
2.xml配置的路径跳转不能跳转,同样的代码,重新建项目后又可以了,不知道什么原因