本实验使用servlet+hibernate分层结构,目的是可以更好地进行ssh整合的准备,可以参考《登录系统-基于servlet+hibernate》和《登录系统-基于struts2的分层架构》两篇文章。
1.新建一个java web项目,在步骤4中选择Hibernate3.2.5选项(如果没有建好数据库连接,可以在此建立连接):
这时netbeans自动生成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">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/book</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
</session-factory>
</hibernate-configuration>
这个文件在系统中添加了连接数据库的驱动程序以及所连接的数据库、用户名和密码。
2.创建如图所示的包结构:
3.使用Hibernate逆向工程向导生成hibernate.reveng.xml文件,如图所示添加选中的数据表。
自动生成的文件:hibernate.reveng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd " >
<hibernate-reverse-engineering>
<schema-selection match-catalog="book"/>
<table-filter match-name="admin"/>
</hibernate-reverse-engineering>
这个文件在系统中注册了数据库“book”和数据表“admin”。
4. 使用Hibernate向导生成Hibernate映射文件和POJO(Plain Ordinary Java Object)文件:
生成的POJO文件是:
Admin.java
package javahibernate;
// Generated 2011-11-19 10:57:36 by Hibernate Tools 3.2.1.GA
/**
* Admin generated by hbm2java
*/
public class Admin implements java.io.Serializable {
private int UId;
private String UName;
private String UPass;
public Admin() {
}
public Admin(int UId) {
this.UId = UId;
}
public Admin(int UId, String UName, String UPass) {
this.UId = UId;
this.UName = UName;
this.UPass = UPass;
}
public int getUId() {
return this.UId;
}
public void setUId(int UId) {
this.UId = UId;
}
public String getUName() {
return this.UName;
}
public void setUName(String UName) {
this.UName = UName;
}
public String getUPass() {
return this.UPass;
}
public void setUPass(String UPass) {
this.UPass = UPass;
}
}
生成的Hibernate映射文件是:
Admin.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2011-11-19 10:57:36 by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="javahibernate.Admin" table="admin" catalog="book">
<id name="UId" type="int">
<column name="u_id" />
<generator class="assigned" />
</id>
<property name="UName" type="string">
<column name="u_Name" length="20" />
</property>
<property name="UPass" type="string">
<column name="u_Pass" length="20" />
</property>
</class>
</hibernate-mapping>
此时Hibernate配置文件hibernate.cfg.xml中,在<session-factory>标记内增加了映射信息:
<mapping resource="javahibernate/Admin.hbm.xml"/>
这两个文件构成了hibernate框架的核心基础:关系数据库到对象的映射,通过映射我们可以在项目中使用面向对象的编程技术。
到此为止,基于Hibernate的持久化工作已准备就绪。所有的工作基本上是自动完成的。
5.在“book.common”包放置工具类用于建立获取SessionFactory和管理Session,在此添加HibernateUtil.java文件:
package book.common;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static Configuration configuration = new Configuration();
private static SessionFactory sessionFactory = null;
static{
try{
configuration.configure();
sessionFactory = configuration.buildSessionFactory();
}catch(Exception e){
}
}
public Session getSession(){
Session session = null;
try{
session = sessionFactory.openSession();
}catch(Exception e){
}
return session;
}
public void closeSession(Session session){
try{
if(null != session)
session.close();
}catch(Exception e){
}
}
}
6.包“book.idao”放置数据访问接口,添加IUserDao接口文件:
package book.idao;
import book.model.User;
public interface IUserDao {
User fineOne(String userName,String userPassword);
}
7. 包“book.dao”放置数据访问类,添加UserDao.java文件,实现IUserDao接口,完成数据访问:
package book.dao;
import book.common.DB_Conn;
import book.model.User;
import book.idao.IUserDao;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDao implements IUserDao{
//创建公用数据库连接类对象
DB_Conn db_conn=new DB_Conn();
//通过用户名称获取用户信息
@Override
public User fineOne(String username, String password) {
db_conn.ConnectDB();
ResultSet rs = null;
try {
String sql = "select * from admin where u_Name ='"
+ username + "' and u_Pass='" + password + "'";
rs = db_conn.sm.executeQuery(sql); // 执行sql语句
User user = null;
if (rs.next()) {
user = new User();
user.setUsername(username);
user.setPassword(rs.getString("u_Pass"));
return user;
}
return user;
}catch (SQLException SqlE) {
return null;
}catch (Exception E) {
return null;
}finally {
// 关闭连接,释放数据库资源:
db_conn.CloseDB();
}
}
}
8.在包“book.iservice”中放置数据的逻辑访问接口,在此添加IUserService.java接口文件:
package book.iservice;
import book.model.User;
public interface IUserService {
User findUserByNameAndPassword(String userName,String userPassword);
}
9. 包“book.service”放置数据逻辑访问类,添加UserService.java文件,实现IUserService,调用UserDao类的功能,完成对数据逻辑访问:
package book.service;
import book.iservice.IUserService;
import book.model.User;
import book.idao.IUserDao;
import book.dao.UserDao;
public class UserService implements IUserService{
private IUserDao userDao=new UserDao();
@Override
public User findUserByNameAndPassword(String userName,String userPassword){
return userDao.fineOne(userName, userPassword);
}
}
10.添加一个servlet类:LoginServlet,在步骤3中选中“将信息添加到部署描述符”选项。如图:
在LoginServlet.java文件加入如下代码:
package book.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import book.iservice.IUserService;
import book.service.UserService;
import book.model.Admin;
public class LoginServlet extends HttpServlet {
private IUserService userService=new UserService();
Admin user=null;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String UserName = request.getParameter("logname");
String Password = request.getParameter("logpwd");
user=userService.findUserByNameAndPassword(UserName, Password);
if (user.getUName() != null) {
request.setAttribute("username", user.getUName());
try {
request.getRequestDispatcher("index.jsp").forward(request,response);
}catch (Throwable t) {
getServletContext().log(t.getMessage());
}
} else {
request.setAttribute("error", "用户名与密码不匹配,登录失败,请重试!");
try {
request.getRequestDispatcher("Login.jsp").forward(request, response);
}catch (Throwable t) {
getServletContext().log(t.getMessage());
}
}
}
11. 创建如下两个页面:
Login.jsp:
<%@ page pageEncoding="gb2312" %>
<%@ page contentType="text/html; charset=gb2312" %>
<% request.setCharacterEncoding("gb2312"); %>
<%@ page language="java" %>
<html>
<head><title>登录网页</title></head>
<body>
<form method="POST" action="UserAction.action">
<table >
<tr>
<td width="890" align="left" colspan="2">
<b><font size="5">系统登录</font></b>
<hr>
</td>
</tr>
<% if (request.getAttribute("error") != null){ %>
<tr>
<td width=100% align=center colspan=4 height=36>
<font color=red><b><%=request.getAttribute("error")%></b></font>
</td>
</tr>
<%
}
%>
<tr>
<td width="75" align="center">
<p align="right">账号:</p>
</td>
<td width="809" align="center">
<p align="left">
<input type="text" name="userName" size="20"></td>
</tr>
<tr>
<td width="75" align="center">
<p align="right">密码:</p>
</td>
<td width="809" align="center">
<p align="left">
<input type="password" name="userPassword" size="20">
<input type="submit" value="登录" name="loginButton"></td>
</tr>
</table>
</form>
</body>
</html>
在这个页面中,下面的form标记语句:
<form method="POST" action="UserAction.action">
表示该页面提交一个名为:"UserAction"的action,注意和struts.xml文件中的action的name相对应。
index.jsp:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>显示信息</title>
</head>
<body>
<h1>Hello World!</h1>
<div id="content">
<center>
<br/><%=request.getAttribute("msg")%>
</center>
</div>
</body>
</html>
该页面的标记语句:
<%=request.getAttribute("msg")%>
表示接收来自action的msg字符串。
12. 生成项目,并运行http://localhost:8080/login/login.jsp