【搭建JavaEE】(3)前后端交互,请求响应机制,JDBC数据库连接

前后端交互

Apache Tomat

B/S目前主流。

tomat包含2部分:

  1. apache
  2. 容器


再认识servlet

抽象出的开发模式

项目创建配置

maven +javaee+tomcat



忽略一些不用的文件



webapp文件夹

HiServlet


这里面出现了webinfo,这个别删因为这个呢,是这这个这个文件特别重要。


Url-->uri(抽象)

虚拟地址------web.xml



TOmat启动前




注解版--SuperHiSevlet

*请求-响应

MyRequestServlet

HttpServletRequest

获取前端数据

  request.getParameter("前端参数")
  • form表单中name属性

  • a标签

    <a href='localhost:8099/deep?name=abc&pass=123'

获取多个数据
获取请求方法
获取头

HttpServletRequest.class


java 复制代码
package com.ffyc.servlet;

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 java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;

@WebServlet(value = "/req")
public class MyRequestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        String name = request.getParameter("name");
        String username = request.getParameter("username");

        System.out.println(name + ":" + username);

        System.out.println("------------------------------------------");
        String methodName = request.getMethod();
        System.out.println("method名称:" + methodName);
        String[] hobbies = request.getParameterValues("hobby");//多个数据

        System.out.println("爱好:" + Arrays.toString(hobbies));


        Enumeration<String> headerNames = request.getHeaderNames();

        System.out.println("----请求头----------------------");
        while(headerNames.hasMoreElements()){
            System.out.println(headerNames.nextElement());
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
java 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试请求</title>
</head>
<body>

    <a href="http://localhost:8099/deep/req?name=abc">测试请求</a>

    <hr/>

    <form action="http://localhost:8099/deep/req" method="post">
        <input type="text" name="username" placeholder="请输入用户名">
        <input type="checkbox" name="hobby" value="basket-ball">basket-ball
        <input type="checkbox" name="hobby" value="TV">TV
        <input type="checkbox" name="hobby" value="GAME">GAME
        <input type="submit" value="提交">

请求乱码问题

 request.setCharacterEncoding("utf-8");

过滤器--切面

过滤器--不同的功能块

配置 .xml

插在servlet之前响应



后台响应

乱码问题(HttpServletResponse)

servletRequest.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=utf-8");
filterChain.doFilter(servletRequest, servletResponse);

登录页面


过滤器

java 复制代码
import javax.servlet.*;
import java.io.IOException;

public class CodingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

映射--index.html(LoginServlet.java)


《没有Web包》

代码

LoginServlet.java

java 复制代码
package com.ffyc.servlet;

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 java.io.IOException;

@WebServlet(value = "/login.do")
public class LoginServlet extends HttpServlet {

    final String USERNAME = "admin";
    final String PASSWORD = "123";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if (USERNAME.equals(username) && PASSWORD.equals(password)) {
            //success
            resp.sendRedirect("login-success.html");
        } else {
            //login
            resp.sendRedirect("index.html");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

index.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
</head>
<body>

<form action="http://localhost:8099/login.do" method="post">
    <fieldset>
        <legend>用户登录</legend>

        <div>
            <input type="text" name="username" placeholder="用户名">
        </div>
        <div>
            <input type="password" name="password" placeholder="密码">
        </div>

        <div>
            <input type="submit" value="登录">
            <input type="reset" value="取消">
        </div>

    </fieldset>
</form>

</body>
</html>

login-success.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录成功页面</title>
</head>
<body>

    <img src="https://img95.699pic.com/photo/40236/5997.jpg_wh300.jpg"/>
    <h1>登录成功</h1>

</body>
</html>

CodingFilter.java

java 复制代码
package com.ffyc.filter;


import javax.servlet.*;
import java.io.IOException;

public class CodingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

web.xml

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">

    <filter>
        <filter-name>charset</filter-name>
        <filter-class>com.ffyc.filter.CodingFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>charset</filter-name>
        <url-pattern>*.do</url-pattern>
    </filter-mapping>
</web-app>

JDBC

引入JDBC

xml 复制代码
       <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>

创建表

创建用户类

xml 复制代码
  <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.34</version>
        </dependency>
@Data
public class User {
    private Integer id;
    private String username;
    private String password;
    private String name;
}

1

    private final String USERNAME="root";
    private final String PASSWORD = "123456";
    private final String URL =
            "jdbc:mysql://localhost:3306/kingdom_db?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";

2

    try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

3

4

5

UserDaolmpl.java

java 复制代码
package com.ffyc.dao.impl;

import com.ffyc.dao.IUserDao;
import com.ffyc.entity.User;

import java.sql.*;

/**
 * 与数据库交互
 */
public class UserDaoImpl implements IUserDao {

    private final String USERNAME = "root";
    private final String PASSWORD = "123456";
    private final String URL =
            "jdbc:mysql://localhost:3306/stu_db?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";

    private Connection conn;
    private PreparedStatement pst;
    private ResultSet rs;

    public UserDaoImpl() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public User findUsernameAndPassword(String username, String password) {
        try {
            String sql = "Select * FROM user_tab WHERE user_username=? AND user_password=?";

            pst = conn.prepareStatement(sql);
            pst.setString(1,username);
            pst.setString(2, password);

            rs = pst.executeQuery();

            if(!rs.next()){
                return null;
            }else{
              Integer id =  rs.getInt("user_id");
              String u = rs.getString("user_username");
              String p = rs.getString("user_password");
              String name = rs.getString("user_name");
              User user = new User();
              user.setId(id);
              user.setUsername(u);
              user.setPassword(p);
              user.setName(name);
              return user;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }
}
相关推荐
API_technology3 小时前
api开发及运用小红书笔记详情api如何获取笔记详情信息
大数据·开发语言·数据库·数据仓库·笔记·爬虫
m0_748241704 小时前
C#数据库操作系列---SqlSugar完结篇
网络·数据库·c#
天天向上杰4 小时前
简识MySQL中ReadView、RC、RR的关系
数据库·mysql
久绊A4 小时前
理解CPU负载与使用率
服务器·网络·数据库·cpu
你疯了抱抱我4 小时前
Oracle知识点1:如何修改密码并登录sys/system账号
数据库·oracle
羊小猪~~7 小时前
MYSQL学习笔记(二):基本的SELECT语句使用(基本、条件、聚合函数查询)
数据库·笔记·sql·学习·mysql·考研·数据分析
然然阿然然7 小时前
2025.1.15——二、字符型注入
网络·数据库·sql·学习·网络安全
!!!5258 小时前
MyBatis-增删改查操作&一些细节
java·数据库·spring boot·mybatis
然然阿然然8 小时前
2025.1.15——六、SQL结构【❤sqlmap❤】
数据库·sql·学习·安全·web安全·网络安全