由于需要对Hibernate作个了解,所以写了个简单的实现
以上是大概目录
1.新建Hibernate.cfg.xml配置文件
/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 路径映射
tHIbe
userServlet
servlet.userServlet
userServlet
*.do
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
View Code
3.路径跳转的servlet类
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等)
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层实现类代码参考
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配置文件中引入)
/p>
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
View Code
7.User实体类(注意要实现 implements Serializable)
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页面
主页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配置的路径跳转不能跳转,同样的代码,重新建项目后又可以了,不知道什么原因