HttpServlet中有HttpServletRequest类、HttpServletResponse类
?其中HttpServletRequest类主要是get方法
?HttpServletResponse类中便主要是set方法
重用的方法如下🌱
方法 | 描述 |
setStatus | 为响应设置状态码 |
setHeaders | 设置header,如果name相同,则覆盖旧值 |
addHeaders | 设置header,就算name相同,也不覆盖旧值 |
setContetType | 设置响应内容类型 |
sendRedirect | 使用指定的重定向位置URL发送临时重定向响应 |
设置为200?
@WebServlet("/Status")
public class StatusServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setStatus(200);
}
}
?
设置为404?
@WebServlet("/Status")
public class StatusServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setStatus(404);
}
}
很明显,只是设置状态码为404的话,未找到状态的页面并不显示😯
因此我们需要使用setError?
@WebServlet("/Status")
public class StatusServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendError(404,"错误页面");
}
}
?利用setHeader方法进行刷新
@WebServlet("/refresh")
public class RefreshServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("refresh","1");
resp.getWriter().write("" + System.currentTimeMillis());
}
}
打开浏览器,得到下面效果?
?利用状态码302和setHeader,直接重定向到电子科技大学官网
@WebServlet("/redirect")
public class redirect extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setStatus(302);
resp.setHeader("Location","https://www.uestc.edu.cn");
}
}