• javaWeb的HttpServletRequest和HttpServletResponse


    HttpServletRequest

    HttpServletRequest对象是封装了用户的请求信息,包括请求参数去,请求头等信息,service()f方法中的两个HttpServletRequest和HttpServletResponse的形参是由Tomcat将创建好的实例对象传进来,不需要我们关心。(如果感兴趣的话,可以看看Tomcat的底层实现,如果有时间的话,我们可以再详细讨论一下这个原理)。

    HttpservletRequest的常用方法

    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class Servlet01 extends HttpServlet{
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                String url=req.getRequestURL().toString();
                System.out.println("url--->"+url);
                
                String uri=req.getRequestURI();
                System.out.println("uri--->"+uri);
                
                String qs=req.getQueryString();
                System.out.println("请求参数:"+qs);
                
                String method=req.getMethod();
                System.out.println("请求参数"+method);
                
                String protocol=req.getProtocol();
                System.out.println("请求协议:"+protocol);
                
                String context=req.getContextPath();
                System.out.println("请求站点名:"+context);    
                
        }
    }
    获取请求头

    import java.io.IOException;
    import java.util.Enumeration;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class Servlet02 extends HttpServlet{
            @Override
            protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                String header=req.getHeader("host");
                System.out.println(header);
                
                
                System.out.println("++++++++++++++++");
                Enumeration<String> enu=req.getHeaderNames();
                while(enu.hasMoreElements()){
                    System.out.println(enu.nextElement());
                }
            }
    }
    获取客户端请求参数

    import java.io.IOException;
    import java.util.Enumeration;
    import java.util.Map;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    
    public class Servlet03 extends HttpServlet {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String name=req.getParameter("uname");
            System.out.println(name);
            
            
            String [] hobby=req.getParameterValues("hobby");
            for(String temp:hobby){
                System.out.println(temp);
            }
            
            Enumeration<String> es=req.getParameterNames();
            while(es.hasMoreElements()){
                es.nextElement();
            }
            
            Map<String, String[]> map =req.getParameterMap();
            for(String key:map.keySet()){
                System.out.println(key);
                for(String str:map.get(key)){
                    System.out.println(str);
                }
            }
        }
    }
    乱码问题的解决方式

    由于现在的 request 属于接收客户端的参数,所以必然有其默认的语言编码,主要是由于在解析过程中默认使用的编码方式为 ISO-8859-1(此编码不支持中文),所以解析时一定会出现乱码。要想解决这种乱码问题,需要设置 request 中的编码方式,告诉服务器以何种方式来解析数据。或者在接收到乱码数据以后,再通过相应的编码格式还原。

    方式一:req.setCharacterEncoding("UTF-8");

    该方法值针对post有效,对get是无效的,但是Tomcat8 起,以后的 GET方式请求是不会出现乱码的,所以使用Tomcat8及以上的Tomcat版本,只需要设置该post的编码即可

    方式二:

     String str=req.getParameter("uname");
    String str1=new String(str.getBytes("ISO-8859-1"),"UTF-8");

    该方式借助了 String 对象的方法,该种方式对任何请求有效,是通用的,但只能针对单个参数进行编码转换来达到解决乱码的问题

    请求转发

    请求转发,是一种服务器的行为,当客户端请求到达后,服务器进行转发,此时会将请求对象进行保存,地址栏中的 URL 地址不会改变,得到响应后,服务器端再将响应发送给客户端,从始至终只有一个请求发出。实现方式如下,达到多个资源协同响应的效果。

                servlet01.java
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class servlet01 extends HttpServlet {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String name= req.getParameter("uname");
            req.setAttribute("uname", name);
            
            //转发到servlet02
            req.getRequestDispatcher("s02").forward(req,resp);
        }
    }
    
    
           servlet02.java 
    import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class servlet02 extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println(req.getAttribute("uname")); //转发到index.jsp页面 ,请求转发的过程中,用的是同一个request和response req.getRequestDispatcher("index.jsp").forward(req,resp); } } index.jsp页面 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 欢迎${uname }来到首页 </body> </html>

    HttpServletResponse 

    Web 服务器收到客户端的 http 请求,会针对每一次请求,分别创建一个用于 代表请求的 request 对象和 代表响应的 response 对象。request 和 response 对象代表请求和响应:获取客户端数据,需要通过request 对象; 向客户端输出数据,需要通过 response 对象。HttpServletResponse 的主要功能用于服务器对客户端的请求进行响应,将Web 服务器处理后的结果返回给客户端。service()方法中形参接收的是HttpServletResponse 接口的实例化对象,这个对象中封装了向客户端发送数据、发送响应头,发送响应状态码的方法。

    常用方法

    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class Servlet04 extends HttpServlet{
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("UTF-8");
            String str=req.getParameter("uname");
        String str1=new String(str.getBytes("ISO-8859-1"),"UTF-8");
            System.out.println(str1);
            
            
            resp.addHeader("name", "zhangsan");
            resp.setHeader("name", "lisi");
            
            resp.setHeader("refresh", "3;url=http://www.shsxt.com");
            resp.sendError(404);
    
        }
    }
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class Servlet04 extends HttpServlet{
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {    
        resp.setContentType("text/html;charset=UTF-8");
            resp.getOutputStream().write("<h3> hello world</h3> ".getBytes());

    将图片显示在网页上

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    
    public class Servlet05 extends HttpServlet {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.setContentType("image/jpg;charset=UTF-8");
            String realpath=req.getServletContext().getRealPath("/");
            System.out.println(realpath);
            
            String filepath=realpath+"1.jpg";
            File file=new File(filepath);
            if(file.exists()&& file.isFile()){
                InputStream is=new FileInputStream(file);
                byte[] bs=new byte[1024];
                int len=0;
                while((len=is.read(bs))!=-1){
                        resp.getOutputStream().write(bs,0,len);
                }
                resp.getOutputStream().close();
                is.close();
            }
            else{
                resp.setContentType("text/html;charset=UTF-8");
                resp.getWriter().write("<h1>文件不存在!</h1>");
            }
            
        }
    }

    重定向

    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class Servlet06 extends HttpServlet{
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                resp.sendRedirect("s05");
                
        }
        
    }
  • 相关阅读:
    《感想都是碎片》
    我容易么我……
    elvish Template Library
    可以直接在C++里面写类似RSL的shader了
    全身和鞘内注射依那西普抑制糖尿病小鼠的触觉异常痛敏
    针对英夫利昔单抗或阿达木单抗的抗体存在与否决定转用依那西普的疗效
    全基因组关联研究发现TNF抑制剂治疗RA与7个位点的多态性有关
    依那西普治疗幼年型特发性关节炎的疗效
    强直性脊柱炎中的髋关节受累:流行病学和髋关节置换术的相关危险因素
    长期使用依那西普对幼年型特发性关节炎患儿生长的影响
  • 原文地址:https://www.cnblogs.com/liu1459310172/p/9551722.html
Copyright © 2020-2023  润新知