1.jsp页面
<div id="loginFormDiv">
<div id="loginHeader"><p>欢 迎 您 !</p></div>
<form action="login" method="post" id="loginForm">
<input type="text" name="userName" id="userName" placeholder="请输入用户名"/>
<input type="password" name="passWord" id="passWord" placeholder="请输入密码"/><br/>
<input type="button" value="登录" οnclick="login()"/>
</form>
</div>
script中提交form
function login() {
var loginFormObj = document.getElementById("loginForm");
loginFormObj.submit();
}
2.servlet中接收数据
request.setCharacterEncoding("UTF-8");
String userName = request.getParameter("userName");
String passWord = request.getParameter("passWord");
3.连接数据库
//1.加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
//2.得到connection对象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo", "root", "123456");
//3.得到PreparedStatement对象
stmt = conn.prepareStatement("SELECT * FROM user WHERE user_name = ?");
stmt.setString(1, userName);
//4.得到数据并处理
rs = stmt.executeQuery();
if (rs.next()) {
int userId = rs.getInt("Id");
String userNameDB = rs.getString("user_name");
String passWordDB = rs.getString("password");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally { //注意打开连接数据库,最后要关闭连接
try {
if (rs != null) {
rs.close();
}
if (rs != null) {
stmt.close();
}
if (rs != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
4.跳转页面
request.getRequestDispatcher().forward(request, response);
response.sendRedirect()