方式一:
jsp:
<font color="red">${ msg }</font>
<form action="/personal/requestLogin" method="post">
姓名:<input type="text" name="username"/><br/>
密码:<input type="password" name="password"/><br/>
<input type="submit" value="登录"/>
</form>
web.xml
<servlet>
<servlet-name>requestLogin</servlet-name>
<servlet-class>com.pers.request.service.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>requestLogin</servlet-name>
<url-pattern>/requestLogin</url-pattern>
</servlet-mapping>
LoginServlet.java
public class LoginServlet extends HttpServlet {
// 登录校验代码
}
方式二:注解 (前提是@WebServlet("/LoginServlet")必须和类名LoginServlet一致)
jsp:
<font color="red">${ msg }</font>
<form action="/personal/LoginServlet" method="post">
姓名:<input type="text" name="username"/><br/>
密码:<input type="password" name="password"/><br/>
<input type="submit" value="登录"/>
</form>
LoginServlet.java
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
// 登录校验代码
}
以下是详细代码:
==================================================傲娇的分割线==================================================
login.jsp
<%@ 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=UTF-8">
<title>登录测试</title>
</head>
<body>
<h3>登录页面</h3>
<form action="/personal/requestLogin" method="post">
姓名:<input type="text" name="username"/><br/>
密码:<input type="password" name="password"/><br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>personal</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>requestLogin</servlet-name>
<servlet-class>com.pers.request.service.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>requestLogin</servlet-name>
<url-pattern>/requestLogin</url-pattern>
</servlet-mapping>
</web-app>
LoginServlet.java
package com.pers.request.service; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.pers.request.domain.User; /**
* Servlet implementation class RequestLogin
*
* 登录测试
*/
//@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取从前台表单传过来的值
String username = request.getParameter("username");
String password = request.getParameter("password"); // 从数据库中查询
UserService userService = new UserService();
User user = userService.login(username, password); // 获取项目名称
String projectName = request.getContextPath(); // 判断user是否存在
if (user!=null) {
// 登录成功,跳转到登录成功页面(重定向)
// (重定向的地址的写法:包含项目名称的,包含项目名称的,包含项目名称的,包含项目名称的)
response.sendRedirect(projectName + "/jsp/request/success.jsp");
} else {
// 登录失败,提示信息并跳转到登录页面(转发)
request.setAttribute("msg", "用户名或密码错误,请重新输入!");
request.getRequestDispatcher("/jsp/request/login.jsp").forward(request, response);
} } /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }
UserService.java
package com.pers.request.service; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import com.pers.jdbc.utils.JdbcUtils;
import com.pers.request.domain.User; /**
* @author liangyadong
* @date 2016年10月25日 下午4:16:00
* @version 1.0
*/
public class UserService { /**
* 根据用户名和密码查询
* @param username
* @param password
* @return
*/
public User login(String username, String password){ /**
* 步骤
* 1.加载驱动获取连接
* 2.编写sql
* 3.预编译sql
* 4.设置参数
* 5.执行sql
* 6.遍历结果集,判断用户是否存在
*/
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
// 获取连接
conn = JdbcUtils.getConnection();
// 编写sql
String sql = "select * from t_user where username = ? and password = ?";
try {
// 预编译sql
stmt = conn.prepareStatement(sql);
// 设置参数
stmt.setString(1,username);
stmt.setString(2, password);
// 执行sql
rs = stmt.executeQuery();
// 遍历结果集
while (rs.next()) {
User user = new User();
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
return user;
} } catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JdbcUtils.release(conn, stmt, rs);
} return null;
} }
User.java
package com.pers.request.domain;
/**
* @author liangyadong
* @date 2016年10月25日 下午2:46:03
* @version 1.0
*/
public class User { private String username;
private String password; public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
} @Override
public String toString() {
return "User [username=" + username + ", password=" + password + "]";
} }
JdbcUtils.java
package com.pers.jdbc.utils; import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties; /**
* @author liangyadong
* @date 2016年10月13日 下午3:23:22
* @version 1.0
*/
public class JdbcUtils { public static final String DRIVERCLASS;
public static final String URL;
public static final String USERNAME;
public static final String PASSWORD; /**
* 静态代码块
*
* 步骤
* 1.创建properties对象
* 2.获取db配置文件的输入流
* 3.properties对象加载配置文件
* 4.properties对象通过key获取值
*/
static{
// 读取配置文件,将值赋给常量
// 创建properties对象
Properties pro = new Properties(); // 获取db.properties文件的输入流
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("com/pers/jdbc/utils/db.properties"); // 加载配置文件
try {
pro.load(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 通过key获取值
DRIVERCLASS = pro.getProperty("driverClass");
URL = pro.getProperty("url");
USERNAME = pro.getProperty("username");
PASSWORD = pro.getProperty("password"); } /**
* 加载驱动
*/
public static void loadDriver(){
try {
Class.forName(DRIVERCLASS);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} /**
* 获取连接
* @return
*/
public static Connection getConnection() {
// TODO Auto-generated method stub
// 加载驱动
loadDriver();
try {
// 获取连接
return DriverManager.getConnection(URL,USERNAME,PASSWORD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return null;
} /**
* 释放资源
*
* 查询的释放资源方法
* @param conn
* @param sta
* @param rs
*/
public static void release(Connection conn,Statement sta,ResultSet rs){
if (rs!=null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rs = null;
}
if (sta!=null) {
try {
sta.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sta = null;
}
if (conn!=null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn = null;
}
} /**
* 释放资源
*
* 增删改的释放资源方法
* @param conn
* @param sta
*/
public static void release(Connection conn,Statement sta){
if (sta!=null) {
try {
sta.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sta = null;
}
if (conn!=null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn = null;
}
} }
db.properties
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql:///myTest
username=root
password=root