第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 action="login">
username:<input type="text" name="userName" >
password:<input type="password" name="password" >
<input type="submit" value="提交">
</form>
</body>
</html>
第2关:登录验证
任务描述
借助JDBC
在库名university
中完成对数据表student
数据的查询,来验证前台传过来的用户名称字段userName
和密码字段password
是否匹配;127.0.0.1:3306
是mysql
服务器地址及端口 数据库编码格式设置为utf-8
,MySQL
的用户名为root
,密码为123123
,我们需要根据这些属性来连接数据库。
success.jsp
代码:
fail.jsp
代码:
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 *********/
Connection conn ;
PreparedStatement st ;
ResultSet rs=null;
String userName = req.getParameter("userName");
String password = req.getParameter("password");
try{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://127.0.0.1:3306/university?user=root&password=123123";
conn=DriverManager.getConnection(url);
String sql = "select * from student" + " where USER_NAME = ? and PASSWORD = ?";
//预编译
st= conn.prepareStatement(sql);
st.setString(1,userName);
st.setString(2,password);
rs = st.executeQuery();
}catch (Exception e){
e.printStackTrace();
}
StudentBean studentbean=new StudentBean();
studentbean.setUserName(userName);
studentbean.setPassword(password);
HttpSession session = req.getSession();
try {
if (rs.next()){
studentbean.setStudentId(rs.getInt(1));
studentbean.setSex(rs.getString(4));
studentbean.setAge(rs.getInt(5));
studentbean.setDept(rs.getString(6));
session.setAttribute("account",studentbean);
resp.sendRedirect("success.jsp");
}else{
session.setAttribute("account",studentbean);
resp.sendRedirect("fail.jsp");
}
} catch (Exception e) {
e.printStackTrace();
}
/********* End *********/
}
}