当前位置:网站首页>Request object and response object analysis
Request object and response object analysis
2022-07-06 11:14:00 【Call me uncle】
Catalog
②: Response to the garbled problem
request object
When the client sends a request to the server , The server created for this request request object , And in the call Servlet Of service When the method is used , Pass the object to service Method .Request Object encapsulates all the request data sent by the client .

explain :
We use... In browsers , Any operation constitutes a request for information , Send to reuqest object , And send it to Servlet Under the interface service, Down to HttpServlet.
One doGet Small projects :
RegisServlet.java
package com.qcby.servlet;
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 org.apache.catalina.User;
@WebServlet("/regist")
public class RegisServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username + " " + password);
}
}rigist.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/JiuYueServices/regist" method="get">
user name :<input type="text" name="username"/>
password :<input type="text" name="password"/>
<input type="submit" value=" register ">
</form>
</body>
</html><form action="/JiuYueServices/regist" method="get"> Inside JiuYueServices yes Project name
success :

The code problem :
because request Is to receive requests from users , The server converts the request according to the encoding format . The default encoding format on the server side is ISO-8859-1( This encoding does not support Chinese ), Our user browser defaults to utf-8 The encoding format of , So it often produces garbled code . To solve the problem of garbled code , Need to set up request The encoding format , Tell the server how to parse the data . Or after receiving the garbled code , What encoding format is used to restore

resolvent :
Mode one :( all )
request.setCharacterEncoding("UTF-8");Mode two :( With the help of String Object method , This method is valid for any request , It's all universal )
new String(request.getParameter(name).getBytes("ISO-8859-1"),"UTF-8"))Request forwarding
Request forwarding is a server behavior , When the client request arrives , The server forwards , The request object is saved , In the address bar url The address will not change , After getting the corresponding , The server will send the request to the client , From beginning to end, only one request was made .
request.getRequestDispatcher(url).forward(request, response);Two servlet:
/**
*
* @author lenovo
* Request forwarding jump
* You can make the server jump to the client ( Or designated (Servlet)
* characteristic :
* 1. Server side behavior
* 2. The address bar doesn't change
* 3. It's a request from beginning to end
* 4.request The data in servlet Share in program
*/
@WebServlet(value="/s01")
public class Servlet01 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("s01="+username + " " + password);
// Request to jump to Servlet02
//req.getRequestDispatcher("s02").forward(req, resp);
// Request to html page
req.getRequestDispatcher("RegistServlet.html").forward(req, resp);
}
}@WebServlet(value="/s02")
public class Servlet02 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
req.setCharacterEncoding("UTF-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("s02=" + username + " " + password);
}
}Running, we found s01 and s02 Metropolitan output , And only once


request Scope
request Express a request , Just make a request and create a request object , His scope : Only valid in the current request .
use : It is often used to pass parameters between different pages of the same request between servers , It is often used for control value transmission of forms .
Common methods
| request.setAttribute(String name,Object value) | Set domain object content | |
| request.getAttribute(String name) | Get domain object content | |
| request.removeAttribute(String name) | Delete domain object content |
Two servlet
@WebServlet("/s03")
public class Servlet03 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println(" I am a 03");
req.setAttribute("user", "qcby");
req.setAttribute("age", 18);
req.getRequestDispatcher("s04").forward(req, resp);
}
}@WebServlet("/s04")
public class Servlet04 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println(" I am a 04");
System.out.println(req.getAttribute("user"));
System.out.println(req.getAttribute("age"));
}
}
visit :http://localhost:8080/SecondServlet/s03

response object


①:response Main methods
| getWriter() | Get character stream ( Only corresponding string data ) |
| getOutputStream() | Obtain byte stream ( Can correspond to all data ) |
getWriter()
@WebServlet("/regist")
public class RegistServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter printWriter = resp.getWriter();
printWriter.print("success");
}
}getOutputStream()
@WebServlet("/regist")
public class RegistServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
// PrintWriter writer = resp.getWriter();
// writer.print("success");
ServletOutputStream stream = resp.getOutputStream();
stream.write("Success".getBytes());
}
}html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/SecondServlet/regist" method="post">
user name :<input type="text" name="username"/>
password :<input type="text" name="password"/>
<input type="submit" value=" register ">
</form>
</body>
</html>②: Response to the garbled problem
response.setCharacterEncoding("UTF-8");
response.setHeader("content-type", "text/html;charset=UTF-8");边栏推荐
- Base de données Advanced Learning Notes - - SQL statements
- PyCharm中无法调用numpy,报错ModuleNotFoundError: No module named ‘numpy‘
- MySQL master-slave replication, read-write separation
- Django运行报错:Error loading MySQLdb module解决方法
- The virtual machine Ping is connected to the host, and the host Ping is not connected to the virtual machine
- Asp access Shaoxing tourism graduation design website
- Rhcsa certification exam exercise (configured on the first host)
- Invalid global search in idea/pychar, etc. (win10)
- 解决安装Failed building wheel for pillow
- 02-项目实战之后台员工信息管理
猜你喜欢

基于apache-jena的知识问答

【博主推荐】SSM框架的后台管理系统(附源码)

Dotnet replaces asp Net core's underlying communication is the IPC Library of named pipes

Basic use of redis
![[C language foundation] 04 judgment and circulation](/img/59/4100971f15a1a9bf3527cbe181d868.jpg)
[C language foundation] 04 judgment and circulation

机器学习--人口普查数据分析
![[recommended by bloggers] C WinForm regularly sends email (with source code)](/img/5d/57f8599a4f02c569c6c3f4bcb8b739.png)
[recommended by bloggers] C WinForm regularly sends email (with source code)

软件测试与质量学习笔记3--白盒测试

When you open the browser, you will also open mango TV, Tiktok and other websites outside the home page

Did you forget to register or load this tag
随机推荐
Kubernetes - problems and Solutions
Some problems in the development of unity3d upgraded 2020 VR
Remember a company interview question: merge ordered arrays
npm一个错误 npm ERR code ENOENT npm ERR syscall open
csdn-Markdown编辑器
Kubesphere - deploy the actual combat with the deployment file (3)
QT creator create button
项目实战-后台员工信息管理(增删改查登录与退出)
[ahoi2009]chess Chinese chess - combination number optimization shape pressure DP
Armv8-a programming guide MMU (2)
软件测试与质量学习笔记3--白盒测试
Attention apply personal understanding to images
解决扫描不到xml、yml、properties文件配置
Ansible practical series I_ introduction
PyCharm中无法调用numpy,报错ModuleNotFoundError: No module named ‘numpy‘
SSM integrated notes easy to understand version
[recommended by bloggers] asp Net WebService background data API JSON (with source code)
Tcp/ip protocol (UDP)
记一次某公司面试题:合并有序数组
一键提取pdf中的表格