第1关:编写用户登录页面。
本关我们要实现的是登陆功能的第一步:编写登陆表单,在jsp
中编写表单,设置用户名字段userName
和用户密码字段password
,并设置请求的servlet
路径为login
。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form class="form" action="login" method="post">
<div>
username:<input type="text" name="userName"><br>
password:<input type="password" name="password"><br>
<span><input type="submit" value="提交"></span>
</div>
</form>
</body>
</html>
第2关:登录验证
借助JDBC
在库名university
中完成对数据表student
数据的查询,来验证前台传过来的用户名称字段userName
和密码字段password
是否匹配;127.0.0.1:3306
是mysql
服务器地址及端口 数据库编码格式设置为utf-8
,MySQL
的用户名为root
,密码为123123
,我们需要根据这些属性来连接数据库。
package chapter9;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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 LoginServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/********* Begin *********/
String username=req.getParameter("userName");
String password=req.getParameter("password");
StudentBean stu=new StudentBean();
stu.setUserName(username);
stu.setPassword(password);
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://127.0.0.1:3306/university?characterEncoding=UTF-8";
String sqlusername="root";
String sqlpassword="123123";
con=DriverManager.getConnection(url,sqlusername,sqlpassword);
}catch(ClassNotFoundException | SQLException e){
e.printStackTrace();
}
PreparedStatement pstmt = null;
ResultSet rs = null;
int judge=0;
try {
String sql = "select * from student where USER_NAME='"+username+"'"+"and PASSWORD='"+password+"'";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();//
while(rs.next()) {
judge=1;
stu.setStudentId(rs.getInt(1));
stu.setSex(rs.getString(4));
stu.setAge(rs.getInt(5));
stu.setDept(rs.getString(6));
}
}catch(Exception e){
e.printStackTrace();
}
if(judge==1){
req.getSession().setAttribute("account", stu);
resp.sendRedirect("success.jsp");
}
if(judge==0){
req.getSession().setAttribute("account", stu);
resp.sendRedirect("fail.jsp");
}
judge=0;
/********* End *********/
}
}