Day2-servlet登录跳转
Java方向(SSM+SpringBoot)项目实训
Day2(2020.7.21)
servlet登录跳转
1.File→New Project→Java Enterprise →Web Application(4.0)
Application Server:Tomcat 8.0.50
勾选 Create web.xml
→Next→编辑好Project Name和Project Location→Finish
2.在WEB-INF目录下新建一个Directory,命名为lib,存放导入所需的jar包;
复制粘贴,导入所需的jar包,右键jar包 Add as Library;
File→Project Structure→Artifacts(检查是否有缺失的jar包)
如果有,点击Fix…→Add all missing dependencies of ‘servlet.test’ to the artifact
点击Apply→jar包导入成功!
3.在src目录下创建如下 Package,及Class,开始编写代码;
dao层:存放和数据库直接打交道的代码,如数据的增删查改操作;
model层:定义各种各样的实体类,如User对象,包含ID、用户名、密码等各种属性;
service层:核心,处理业务逻辑,如servlet会拦截用户从前端页面发送请求,执行对应的方法,实现具体的功能,比如调用dao层中的数据库方法;
3.1 Util下创建DBUtil;
DBUtil:
package com.roger0123.util;
import java.sql.*;
public class DBUtil {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/project_learn?useSSL-false","root","123456");
return connection;
}
public static void closeAll(ResultSet rs, Statement stmt,Connection conn) throws SQLException{
if(rs!=null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
}
}
3.2 model下创建User 实体类;
User:
package com.roger0123.model;
public class User {
private int id;
private String name;
private String password;
private String age;
//Alt+Insert
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
", age='" + age + '\'' +
'}';
}
}
3.3 dao下创建UserDao ;
UserDao:
package com.roger0123.dao;
import com.roger0123.model.User;
import com.roger0123.util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class UserDao {
public User selectByName(String name){
ResultSet rs = null;
Connection conn = null;
PreparedStatement pstmt = null;
DBUtil util = new DBUtil();
User user = new User();
try {
conn = util.getConnection();
pstmt = conn.prepareStatement("select * from user where name = ?");//传入SQL语句
pstmt.setString(1,name);
rs = pstmt.executeQuery();
while (rs.next()){
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setPassword(rs.getString(3));
user.setAge(rs.getString(4));
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
util.closeAll(rs, pstmt, conn);
}catch (Exception e){
e.printStackTrace();
}
}
return user;
}
}
3.4 dao下创建UserService ;
UserService:
package com.roger0123.service;
import com.roger0123.dao.UserDao;
import com.roger0123.model.User;
public class UserService {
UserDao userDao = new UserDao();
//调用UserDao中的方法
public User selectByName(String name){
return userDao.selectByName(name);
}
}
3.5 servlet下创建LoginServlet ;
LoginServlet
package com.roger0123.servlet;
import com.roger0123.model.User;
import com.roger0123.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginServlet extends HttpServlet {
UserService userService = new UserService();
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
String password = req.getParameter("password");
System.out.println("name:"+name);
User user = userService.selectByName(name);
System.out.println(password);
System.out.println(user.getPassword());
if(password.equals(user.getPassword())){
resp.getWriter().write("success");
System.out.println("success");
}else{
resp.getWriter().write("failed");
System.out.println("failed");
}
}
}
3.6 页面,改写index.jsp;
index.jsp:
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/7/21
Time: 9:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Servlet.test</title>
</head>
<body>
<h1>登录页面</h1>
<form action="/login" method="post">
name:<input name="name" type="text">
password:<input name="password" type="password">
<input type="submit" value="登录">
</form>
</body>
</html>
3.7 配置web.xml文件;
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>com.roger0123.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
#Test
数据库中事先插入测试数据:
报错及解决
Error:
解决:
找到占用8080端口的task,利用任务管理器关闭。
test:
运行程序成功,自动打开默认浏览器界面:
点击登录出现报错
Error:
空指针异常(NullPointerException)
com.roger0123.servlet.LoginServlet.doPost(LoginServlet.java:22)
解决:
测试发现,从数据库中getPassword()成功,而获取页面输入的password失败,为空值导致报错;
检查index.jsp;
修改前:
修改后:
程序运行成功!
success:
如果密码匹配:
failed:
如果密码不匹配:
如果用户尚未注册,在数据库中无数据: