Hibernate实现登录注册小例子

1.在MySQL里面新建一个数据库,里面新建一个表,加入相应的字段,新建一个Dynamic Web Project项目,整体的框架如图所示:



2.LoginRegisterInfo.java里面的代码:

package com.imooc.dao;

import java.util.List;

import javax.swing.JOptionPane;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.imooc.entity.User;
import com.imooc.util.HibernateSessionFactory;

public class LoginRegisterInfo {

	private Session session;
	private Transaction transaction;
	private Query query;
	private HibernateSessionFactory getSession;

	public LoginRegisterInfo() {

	}

	public String saveInfo(User user) {
		String mess = "error";
		getSession = new HibernateSessionFactory();
		session = HibernateSessionFactory.getSession();
		try {
			transaction = session.beginTransaction();
			session.save(user);
			transaction.commit();
			mess = "success";
			return mess;
		} catch (Exception e) {
			message("RegisterInfo error:" + e);
			e.printStackTrace();
			return null;
		}
	}

	public List<User> queryInfo(String type, Object value) {
		getSession = new HibernateSessionFactory();
		session = HibernateSessionFactory.getSession();
		try {
			String hqlsql = "from com.imooc.entity.User as u where u.username=?";
			query = session.createQuery(hqlsql);
			query.setParameter(0, value);
			List<User> list = query.list();
			transaction = session.beginTransaction();
			transaction.commit();
			return list;
		} catch (Exception e) {
			message("LoginRegisterInfo error:" + e);
			e.printStackTrace();
			return null;
		}
	}

	private void message(String mess) {
		int type = JOptionPane.YES_NO_OPTION;
		String title = "提示信息";
		JOptionPane.showMessageDialog(null, mess, title, type);
	}

}

3.User.java里面的代码:

package com.imooc.entity;

import java.io.Serializable;

public class User implements Serializable {

	private Integer uid;
	private String username;
	private String password;
	private String nickname;
	private String email;
	private Integer state;
	private String code;

	public User() {
	}

	public User(String username, String password, String nickname, String email, Integer state, String code) {
		this.username = username;
		this.password = password;
		this.nickname = nickname;
		this.email = email;
		this.state = state;
		this.code = code;
	}

	public Integer getUid() {
		return this.uid;
	}

	public void setUid(Integer uid) {
		this.uid = uid;
	}

	public String getUsername() {
		return this.username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return this.password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getNickname() {
		return this.nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public String getEmail() {
		return this.email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Integer getState() {
		return this.state;
	}

	public void setState(Integer state) {
		this.state = state;
	}

	public String getCode() {
		return this.code;
	}

	public void setCode(String code) {
		this.code = code;
	}

}

4.User.hbm.xml里面的代码:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="com.imooc.entity.User" table="user" catalog="hibernate">
		<id name="uid" type="java.lang.Integer">
			<column name="uid" />
			<generator class="increment" />
		</id>
		<property name="username" type="java.lang.String">
			<column name="username" length="30" />
		</property>
		<property name="password" type="java.lang.String">
			<column name="password" length="30" />
		</property>
		<property name="nickname" type="java.lang.String">
			<column name="nickname" length="30" />
		</property>
		<property name="email" type="java.lang.String">
			<column name="email" length="30" />
		</property>
		<property name="state" type="java.lang.Integer">
			<column name="state" />
		</property>
		<property name="code" type="java.lang.String">
			<column name="code" length="50" />
		</property>
	</class>
</hibernate-mapping>

5.LoginServlet.java代码:

package com.imooc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.imooc.dao.LoginRegisterInfo;
import com.imooc.entity.User;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User user = new User();
		LoginRegisterInfo info = new LoginRegisterInfo();
		if (username == null || username.length() == 0) {
			out.print("<script language='javascript'>alert('用户名不能为空!');"
					+ "window.location.href='JSP/login.jsp';</script>");
		} else {
			List<User> list = info.queryInfo("username", username);
			for (int i = 0; i < list.size(); i++) {
				user = list.get(i);
				if (user.getUsername().equals(username)) {
					if (user.getPassword().equals(password)) {
						out.print("登录成功!");
						return;
					} else {
						out.print("<script language='javascript'>alert('密码错误!');"
								+ "window.location.href='JSP/login.jsp';</script>");
					}
				}
			}
			out.print("<script language='javascript'>alert('用户名错误!');"
					+ "window.location.href='JSP/login.jsp';</script>");
		}
	}

}

6.RegitServlet.java里面的代码;
package com.imooc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.imooc.dao.LoginRegisterInfo;
import com.imooc.entity.User;

@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String repassword = request.getParameter("repassword");
		User user = new User();
		LoginRegisterInfo info = new LoginRegisterInfo();
		if (username == null || username.length() == 0) {
			out.print("<script language='javascript'>alert('用户名不能为空!');"
					+ "window.location.href='JSP/regist.jsp';</script>");
		} else {
			List<User> list = info.queryInfo("username", username);
			for (int i = 0; i < list.size(); i++) {
				user = list.get(i);
				if (user.getUsername().equals(username)) {
					out.print("<script language='javascript'>alert('用户名已存在!');"
							+ "window.location.href='JSP/regist.jsp';</script>");
				}
			}
		}
		if (password == null || password.length() == 0) {
			out.print("<script language='javascript'>alert('密码不能为空!');"
					+ "window.location.href='JSP/regist.jsp';</script>");
		} else if (!password.equals(repassword)) {
			out.print("<script language='javascript'>alert('两次输入的密码不一致!');"
					+ "window.location.href='JSP/regist.jsp';</script>");
		}
		user.setUsername(username);
		user.setPassword(password);
		info.saveInfo(user);
		out.print("注册成功!");
	}

}

7.HibernateSessionFactory.java里面的代码:
package com.imooc.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateSessionFactory {

	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	private static org.hibernate.SessionFactory sessionFactory;

	private static Configuration configuration = new Configuration();
	private static ServiceRegistry serviceRegistry;

	static {
		try {
			configuration.configure();
			serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
			try {
				sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
			} catch (Exception e) {
				StandardServiceRegistryBuilder.destroy(serviceRegistry);
				e.printStackTrace();
			}
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	public HibernateSessionFactory() {
	}

	public static Session getSession() throws HibernateException {
		Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession() : null;
			threadLocal.set(session);
		}

		return session;
	}

	public static void rebuildSessionFactory() {
		try {
			configuration.configure();
			serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
			try {
				sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
			} catch (Exception e) {
				StandardServiceRegistryBuilder.destroy(serviceRegistry);
				e.printStackTrace();
			}
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	public static void closeSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		threadLocal.set(null);

		if (session != null) {
			session.close();
		}
	}

	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static Configuration getConfiguration() {
		return configuration;
	}

}

8.hibernate.cfg.xml里面的代码:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>

	<session-factory>
		<property name="hbm2ddl.auto">update</property>
		<property name="myeclipse.connection.profile">MySQL</property>
		<property name="dialect">
			org.hibernate.dialect.MySQLDialect
		</property>
		<property name="connection.password">root</property>
		<property name="connection.username">root</property>
		<property name="connection.url">
			jdbc:mysql://localhost:3306/hibernate
		</property>
		<property name="connection.driver_class">
			com.mysql.jdbc.Driver
		</property>
		<property name="show_sql">true</property>
		<property name="format_sql">true</property>
		<mapping resource="com/imooc/entity/User.hbm.xml" />

	</session-factory>

</hibernate-configuration>

9.login.jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>

<body>
	<h1>登            录</h1>
	<hr>
	<form action="LoginServlet" method="post">
		<table class="centertable">
			<tr>
				<td class="td1">用 户 名:</td>
				<td class="td2"><input class="text1" type="text"
					name="username"/></td>
			</tr>
			<tr>
				<td class="td1">密    码:</td>
				<td class="td2"><input class="text1" type="password"
					name="password" /></td>
			</tr>
			<tr>
				<td colspan="2">
					<input class="button" type="submit" value="登录"  οnchange="checkpwd()"/>
					<input class="button" type="button" οnclick="javascript:history.back(-1);" value="返回"/>
				</td>
			</tr>
		</table>
	</form>
</body>
</html>

10.regist.java代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>

<body>
	<h1>注            册</h1>
	<hr>
	<form action="RegistServlet" method="post">
		<table class="centertable">
			<tr>
				<td class="td1">用 户 名:</td>
				<td class="td2"><input class="text1" type="text"
					name="username" /></td>
			</tr>
			<tr>
				<td class="td1">密    码:</td>
				<td class="td2"><input class="text1" type="password"
					name="password" /></td>
			</tr>
			<tr>
				<td class="td1">确认密码:</td>
				<td class="td2"><input class="text1" type="password"
					name="repassword" /></td>
			</tr>
			<tr>
				<td colspan="2"><input class="button" type="submit" value="注册"
					οnchange="checkpwd()" /> <input class="button" type="button"
					οnclick="javascript:history.back(-1);" value="返回" /></td>
			</tr>
		</table>
	</form>
</body>
</html>

11.在浏览器里面输入http://localhost:8080/Demo/JSP/regist.jsp运行,可以实现登录和注册功能。

  • 3
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值