首页 > 其他分享 >request(请求)和response(响应)

request(请求)和response(响应)

时间:2022-11-17 23:33:08浏览次数:44  
标签:请求 request System 响应 println response out

request: 获取请求数据如网页上输入的信息

response:设置响应数据如设置网页显示的信息

 

 如上图,在deGet方法中使用了request来获取页面中的name值,使用response来输出

request获取请求数据(请求头、请求行、请求体)

 

 

 

get和post获取请求参数的方法是不一样的,get是上面的req.getQueryString(),而post是用req.getReader()的


 

但是这样写太麻烦了,Servlet提供了几个方法,直接使用下列的方法即可获取请求参数,不用区分是get请求还是post请求

 

例如获取username的值

String username = req.getParameter("username");
System.out.println(username);

解决post中文乱码问题:

request.CharacterEncoding("UTF-8");设置字符输入流的编码

解决get/post中文乱码问题:

new String(username.getBytes("ISO-8859-1"),"UTF-8");

response.setContextType("text/html;charset=utf-8");

 


 

Request请求转发

 

 

 

转发的方法:

@WebServlet("/testServlet")
public class testServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("---正---在---转---发---");
        request.getRequestDispatcher("/test1Servlet").forward(request,response);
 }
@WebServlet("/test1Servlet")
public class test1Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("转发成功...");
     Object msg = request.getAttribute("msg");
     System.out.println(msg);

 response重定向:

 

 

 

@WebServlet("/respServlet01")
public class respServlet01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //response.setStatus(302);
        System.out.println("重定向中...");
        //response.setHeader("location", "/tomcat-Demo/respServlet02");
     response.sendRedirect("/tomcat-Demo/respServlet02");

}
@WebServlet("/respServlet02")
public class respServlet02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("重定向成功...");
    }

 

动态获取虚拟目录:

String contextPath  = request.getContextPath();

response.sendRedirect(contextPath + "/xxx");

 

字符输出流:

      response.setContextType("text/html;charset=utf-8");     
     PrintWriter writer = response.getWriter();
        writer.write("<h1>abcdefg</h1>");

字节输出流请看黑马P108

 

标签:请求,request,System,响应,println,response,out
From: https://www.cnblogs.com/changeyi/p/16901097.html

相关文章