Java Web高级应用
基于MVC模式的用户登陆
第1关:编写用户登录页面
- 任务描述
本次实训我们要实现一个MVC的登陆功能:
本关我们要实现的是登陆功能的第一步:编写登陆表单,在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>登录</title>
</head>
<body>
<form action="login" method="get">
<table>
<tr>
<td>username:</td>
<td><input type="text" name="userName"></td>
</tr>
<tr>
<td>password:</td>
<td><input type="password" name="password"></td>
</tr>
</table>
</body>
</html>
第2关:登录验证
package chapter9;
import java.io.IOException;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet {
/**
* 数据库相关
*/
private static final String url = "jdbc:mysql://127.0.0.1:3306/university?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true";
private static final String db_user = "root";
private static final String db_password = "123123";
private static Connection conn = null;
private static PreparedStatement stmt = null;
private static ResultSet rs = null;
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");
try{
// 加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 连接数据库
conn = DriverManager.getConnection(url, db_user, db_password);
String sql = "select * from student where user_name=? and password=?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, userName);
stmt.setString(2, password);
rs = stmt.executeQuery();
HttpSession session = req.getSession();
if(rs.next()){
StudentBean student = new StudentBean();
student.setUserName(rs.getString("user_name"));
student.setPassword(rs.getString("password"));
student.setStudentId(rs.getInt("student_id"));
student.setSex(rs.getString("sex"));
student.setAge(rs.getInt("age"));
student.setDept(rs.getString("dept"));
session.setAttribute("account", student);
resp.sendRedirect("success.jsp");
}else{
StudentBean student = new StudentBean();
student.setUserName(userName);
student.setPassword(password);
session.setAttribute("account", student);
resp.sendRedirect("fail.jsp");
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}
/********* End *********/
}
}

浙公网安备 33010602011771号