关于ServletRequest与ServeltResponse

Servelt

ServletRequest

1.设置中文

1.post请求

        request.setCharacterEncoding("utf-8");

2.get请求

Tomcat8以后,附带Http默认编码方式为UTF-8

2.常见方法

关于参数

        //返回String
        request.getParameter("name");
        //返回数组,用于checkbox或List...
        request.getParameterValues("参数");

关于标头

        //返回String
        request.getHeader("");
        //Enumeration getHeaders(String var1);
        request.getHeaders("");

关于读文件

        //返回ServletInputStream getInputStream() throws IOException;使用需为InputStream
        InputStream stream=request.getInputStream();
        //返回BufferedReader getReader() throws IOException;
        request.getReader();    

Servlet3.0之后的get Part()方法

//1.注解设置文件要写入磁盘位置
@MultipartConfig(location = "i:/")
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part part=request.getPart("photo");
        part.write(/*FileName*/);
    }

3.转发Servlet

a.取得RuquestDispatcher

        request.getRequestDispatcher("/*要转发的Servlet*/");

b.使用include()或forward()

        //将拎一个Servlet包含进来
        request.getRequestDispatcher(" ").include(request,response);
        //接下来的事情转发给另一个Servlet执行
        request.getRequestDispatcher(" ").forward(request,response);
        //Servlet之间需要共享的对象
        request.setAttribute(/*name*/,/*value*/);
        request.getAttribute(/*name*/);
    

使用重定向

ServeltResponse

1.设置中文

        response.setContentType("text/html;charset=UTF-8");

2.常用方法

关于输出字符

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out=response.getWriter();
        out.println("");
        out.println("");
        out.println("");
        out.println("");
        out.println("");
        out.println("");
        out.println("");
        out.println("");

关于输出文件给浏览器

        response.setContentType("application/pdf");
        try (InputStream in= getServletContext().getResourceAsStream("/WEB-INF/test.pdf");
             OutputStream stream=response.getOutputStream();){
            byte buffer[]=new byte[1024];
            int length=-1;
            while ((length=in.read(buffer))!=-1){
                stream.write(buffer,0,length);
            }
        }catch (IOException E){
            E.printStackTrace();
        }

关于重定向

        //转发到另一资源,会改变URI
        response.sendRedirect("index.html");

你可能感兴趣的:(java,servlet,tomcat)