1.post请求
request.setCharacterEncoding("utf-8");
2.get请求
Tomcat8以后,附带Http默认编码方式为UTF-8
//返回String request.getParameter("name"); //返回数组,用于checkbox或List... request.getParameterValues("参数");
//返回String request.getHeader(""); //Enumeration<String> 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*/); }
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*/);
使用重定向
response.setContentType("text/html;charset=UTF-8");
response.setContentType("text/html;charset=UTF-8"); PrintWriter out=response.getWriter(); out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title></title>"); out.println("</head>"); out.println("<body>"); out.println("</body>"); out.println("</html>");
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");