请求request
在java中获取到前端的数据
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.BufferedReader;
import java.io.IOException;
@WebServlet("/test2")
public class a02Servlet_Test extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求行
//获取请求方式
System.out.println("--------------------------");
System.out.println("请求方式:" + req.getMethod());
//获取虚拟目录(项目访问路径)
System.out.println("获取虚拟目录(项目访问路径):" + req.getContextPath());
//获取URL(统一资源定位符)
System.out.println("获取URL(统一资源定位符):" + req.getRequestURL());
//获取URI(统一资源标识符)
System.out.println("获取URI(统一资源标识符):" + req.getRequestURI());
//获取请求参数
System.out.println("获取请求参数:" + req.getQueryString());
System.out.println("--------------------------");
//获取请求头
System.out.println("user-agent:" + req.getHeader("user-agent"));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求体
//获取字符输入流
System.out.println("---------------------------");
BufferedReader reader = req.getReader();
String s = reader.readLine();
System.out.println(s);
}
}
request对象提供的方法:
- 获取所有参数Map集合
Map<String,String[]> getParameterMap()
- 根据名称获取参数值(数组)
String[] getParameterValues(String name)
- 根据名称获取参数值(单个值)
String getParameter(String name)
//请求方式POST,解决request中文乱码
req.setCharacterEncoding("UTF-8");
//请求方式POST,GET通用解决中文乱码方式
username = new String(username.getBytes(StandardCharsets.ISO_8859_1));
请求转发:一种在服务器内部资源跳转方式
req.getRequestDispatcher("资源B路径").forward(req,resp);