使用 HttpServletResponse 对象,设置响应的内容类型和编码,设置响应码以及错误信息。
使用 HttpServletResponse 对象,设置响应的内容类型和编码,设置响应码以及错误信息。
@WebServlet("/demo01")
public class ServletDemo extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
// 设置响应的内容类型和编码
response.setContentType("text/html;charset=utf-8");
// 设置响应码以及错误信息
response.sendError(404,"找不到页面");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
运行结果如下图:
以上案例通过 HttpServletResponse 对象,设置响应信息。