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<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*/);
}
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("<!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");