【搭建JavaEE】(3)前后端交互,请求响应机制,JDBC数据库连接
前后端交互
Apache Tomat
B/S目前主流。
tomat包含2部分:
- apache
- 容器
再认识servlet
抽象出的开发模式
项目创建配置
maven +javaee+tomcat
忽略一些不用的文件
webapp文件夹
HiServlet
这里面出现了webinfo,这个别删因为这个呢,是这这个这个文件特别重要。
Url–>uri(抽象)
虚拟地址——web.xml
TOmat启动前
注解版–SuperHiSevlet
*请求-响应
MyRequestServlet
HttpServletRequest
获取前端数据
request.getParameter("前端参数")
- form表单中name属性
<input name='username' value='abc'>
- a标签
<a href='localhost:8099/deep?name=abc&pass=123'
获取多个数据
获取请求方法
获取头
HttpServletRequest.class
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);
}
}
<!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);
登录页面
过滤器
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
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
<!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
<!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
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 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
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
创建表
创建用户类
<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
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);
}
}
}
原文地址:https://blog.csdn.net/Wuweinan_190cm/article/details/145146523
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!