这是一个适合学完Servlet+JSP+JDBC的练手例子,动手之前可以先回顾一下本文需要用到的知识 ~>
Servlet回顾:传送门
JSP回顾: 传送门
JDBC使用步骤回顾 ~>
1、加载驱动
2、获取连接对象
3、通过连接对象获取sql执行对象
4、编写sql语句
5、使用sql执行对象执行sql语句(为语句中的变量赋值)
6、sql执行对象调用执行方法
如果是查询调用executeQuery();
如果是增删改调用executeUpdate()。
7、释放资源
Start ~>
导入mysql连接:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
在数据库中创建名为test的数据库,执行以下sql创建user表:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
public class User {
private Integer id;
private String username;
private String password;
public User() {
}
public User(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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;
}
}
将JDBC中的一些步骤编写成工具类,减少重复代码。
public class JDBCUtil {
static Connection connection = null;
static PreparedStatement preparedStatement = null;
static ResultSet resultSet = null;
//加载驱动
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取数据库连接
public static Connection getConnection(){
//数据库连接路径
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";
//数据库账号
String username = "root";
//数据库密码
String password = "root";
try {
connection = DriverManager.getConnection(url,username,password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return connection;
}
//释放资源
public static void release(Connection connection,PreparedStatement preparedStatement){
if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (preparedStatement != null){
try {
preparedStatement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void release(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){
release(connection,preparedStatement);
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void main(String[] args) {
Connection connection = JDBCUtil.getConnection();
System.out.println(connection);
}
}
public class UserRepository {
public void register(String username,String password){
Connection connection = JDBCUtil.getConnection();
PreparedStatement preparedStatement = null;
String sql = "insert into user(username,password) values(?,?)";
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,username);
preparedStatement.setString(2,password);
preparedStatement.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBCUtil.release(connection,preparedStatement);
}
}
public User login(String username,String password){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
User user = null;
String sql = "select * from user where username = ? and password = ?";
try {
connection = JDBCUtil.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,username);
preparedStatement.setString(2,password);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
String pwd = resultSet.getString(3);
user = new User(id,name,pwd);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBCUtil.release(connection,preparedStatement,resultSet);
}
return user;
}
}
访问Servlet程序的映射可以在web.xml中配置,也可以使用注解@WebServlet替代,更为方便。
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
//访问:http://localhost:8080/login进入get方法,跳转到登录页面
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("index.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
UserRepository userRepository = new UserRepository();
User user = userRepository.login(username, password);
if (user != null){
req.getRequestDispatcher("homePage.jsp").forward(req,resp);
}
req.setAttribute("msg","用户名或密码错误!");
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
}
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
//访问:http://localhost:8080/register进入get方法,跳转到注册页面
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("register.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
UserRepository userRepository = new UserRepository();
userRepository.register(username,password);
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
}
登录页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<h1>LOGIN</h1>
<form action="/login" method="post">
<div>
<input type="text" name="username" placeholder="UserName">
</div>
<div>
<input type="password" name="password" placeholder="UserPassword">
</div>
<input type="submit" value="Sign in">
<a href="/register">Register</a>
</form>
<%
String msg = (String)request.getAttribute("msg");
%>
<%
if (msg != null){
response.getWriter().write(msg);
}
%>
</body>
</html>
注册页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册</title>
</head>
<body>
<h1>register</h1>
<form action="/register" method="post">
<div>
<input type="text" name="username" placeholder="Enter UserName">
</div>
<div>
<input type="password" name="password" placeholder="Enter UserPassword">
</div>
<input type="submit" value="Register">
</form>
</body>
</html>
主页
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主页</title>
</head>
<body>
<h1>Welcome!!!</h1>
</body>
</html>
在注册的时候如果输入中文,在数据库中可以看到是乱码的,这时候可以使用过滤器来解决编码问题。
创建一个类实现Filter接口,在doFilter方法中设置编码为UTF-8:
注解@WebFilter("/*")表示过滤所有请求,如果你只想过滤部分请求,那么在斜杆之后加上请求的url即可,例如过滤注册请求:@WebFilter("/register")。
@WebFilter("/*")
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("UTF-8");
filterChain.doFilter(servletRequest,servletResponse);
}
}