在这里,我们将创建一个使用servlet创建登录表单的简单示例,在这个示例中使用MySQL作为数据库。
实现的主要功能:
- 显示登录表单输入框(用户名,密码)。
- 在表单中填写用户名,密码并提交。
- 在Servlet中接收提交的用户名和密码,与数据库表中的数据进行比较。
- 匹配用户名和密码,则提示成功;不匹配则提示失败。
需要创建一个用户表:servlet_user
。 此外,它必须包含一些数据。表结构及数据记录如下:
DROP TABLE IF EXISTS `servlet_user`;
CREATE TABLE `servlet_user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL DEFAULT '',
`passwd` varchar(32) NOT NULL DEFAULT '',
`email` varchar(32) DEFAULT NULL,
`city` varchar(24) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of servlet_user
-- ----------------------------
INSERT INTO `servlet_user` VALUES ('1', 'maxsu', '123456', 'maxsu@yiibai.com', '广州');
INSERT INTO `servlet_user` VALUES ('2', 'minsu', '233123', 'minsu@gmail.com', '海口');
INSERT INTO `servlet_user` VALUES ('3', 'avguser', 'fdsa123', 'avguser@qq.com', '广州');
INSERT INTO `servlet_user` VALUES ('4', 'sumuser', 'fdsj124', 'sumuser@qq.com', '北京');
打开Eclipse,创建一个动态Web项目:ServletLogin,其完整的目录结构如下所示 -
以下是这个项目中的几个主要的代码文件。
- index.html
- LoginServlet.java
- LoginDao.java
- WelcomeServlet.java
- web.xml
以下是各个文件中的实现代码。
文件:index.html -
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户登录示例</title>
</head>
<body>
<div style="margin: auto; text-align: center;">
<form action="login" method="post">
用户名:<input type="text" name="username" /> 密 码:<input
type="password" name="passwd" /> <input type="submit"
value="登 录" />
</form>
</div>
</body>
</html>
文件:LoginServlet.java -
package com.yiibai.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.yiibai.dao.LoginDao;
public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String passwd = request.getParameter("passwd");
if (LoginDao.doLogin(username, passwd)) {
HttpSession session = request.getSession();
session.setAttribute("username", username);
RequestDispatcher rd = request.getRequestDispatcher("welcome");
rd.forward(request, response);
} else {
out.print("用户名或密码错误~!");
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);
}
out.close();
}
}
文件:LoginDao.java -
package com.yiibai.dao;
import java.sql.*;
public class LoginDao {
public static boolean doLogin(String username, String passwd) {
System.out.println("UserName : "+username+", Passwd:"+passwd);
boolean status = false;
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/testdb?useSSL=false&characterEncoding=utf8", "root", "123456");
// 用户名及密码是否正确?
PreparedStatement ps = con.prepareStatement("SELECT * FROM servlet_user WHERE name=? AND passwd=?");
ps.setString(1, username);
ps.setString(2, passwd);
ResultSet rs = ps.executeQuery();
status = rs.next();
} catch (Exception e) {
System.out.println(e);
}
return status;
}
}
文件:WelcomeServlet.java -
package com.yiibai.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String username = (String) session.getAttribute("username");
out.print("登录成功~!<br/>");
out.print("欢迎您," + username);
out.close();
}
}
文件:web.xml -
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>ServletLogin</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.yiibai.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>WelcomeServ</servlet-name>
<servlet-class>com.yiibai.servlet.WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WelcomeServ</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
在编写上面代码后,部署此Web应用程序(在项目名称上点击右键->”Run On Server…”),打开浏览器访问URL: http://localhost:8080/ServletLogin/ ,如果没有错误,应该会看到以下结果 -
登录成功后的界面,如下所示 -