1. 新建一个web项目,在项目中添加两个包:JavaBean和Servlet。
2. 在JavaBean包中新建是三个java类:DB_Conn.java、DB_User.java和User.java。
DB_Conn.java文件用于数据库连接,加入如下代码:
package JavaBean;
import java.io.PrintWriter;
import java.sql.*;
public class DB_Conn {
private String driverName="com.mysql.jdbc.Driver"; //驱动程序名
private String userName="root"; //数据库用户名
private String userPwd="123456"; //密码
private String url="jdbc:mysql://localhost:3306/book"; //连接字符串
private Connection conn=null; //数据库连接对象
public Statement sm=null; //数据库语句对象
private PrintWriter out = null;
// 建立数据库连接
public void ConnectDB(){
try {
Class.forName(driverName).newInstance();
conn=DriverManager.getConnection(url,userName,userPwd); //获得数据库连接
sm=conn.createStatement();
} catch(Exception e) {
out.print("数据库连接失败!");
}
}
public void CloseDB(){
try {
if (sm != null) {
sm.close();
}
conn.close();
} catch (SQLException SqlE) {
out.print("数据库关闭失败!");
}
}
}
本实验使用的是mysql数据库,数据库名称:book,数据表名称:admin,字段名:u_id,u_Name,u_Pass。
DB_User.java文件用于数据库访问,结果保存到对象中,加入如下代码:
package JavaBean;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DB_User {
//创建公用数据库连接类对象
DB_Conn db_conn=new DB_Conn();
//通过用户名称获取用户信息
public User get(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();
}
}
}
User.java文件用于关系数据库到对象的映射,加入如下代码:
package JavaBean;
public class User {
private String username;
private String password;
public String getUsername() { //用户名称
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() { //登陆密码
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3. 在Servlet包中新建servlet类:LoginServlet.java,在步骤3中选中“将信息添加到部署描述符”选项。如图:
打开web.xml文件,可以看到如下关于servlet的部署设置:
<servlet>
<servlet-name>LogServlet</servlet-name>
<servlet-class>Servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
在LoginServlet.java中加入如下代码:
import JavaBean.DB_User;
import JavaBean.User;
/**
*
* @author skylzy
*/
public class LoginServlet extends HttpServlet {
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");
DB_User dbuser = new DB_User();
User user = dbuser.get(UserName, Password);
if (user != null) {
request.getSession(true).setAttribute("username", UserName);
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());
}
}
}
4.创建如下两个页面:
login.jsp
<%@ page pageEncoding="UTF-8" %>
<%@ page contentType="text/html; charset=gb2312" %>
<% request.setCharacterEncoding("gb2312"); %>
<%@ page language="java" %>
<html>
<head><title>登录网页</title></head>
<body>
<form method="POST" action="./LoginServlet">
<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="logname" 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="logpwd" size="20">
<input type="submit" value="登录" name="loginButton"></td>
</tr>
</table>
</form>
</body>
</html>
accesspage.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
<% if (request.getAttribute("username") != null){ %>
<font color=red>
<b>
<%=request.getAttribute("username")%>
</b>
</font>
<%
}
%>
!</h1>
</body>
</html>
5.生成项目,并运行http://localhost:8080/login/login.jsp