我们在创建Servlet时会覆盖service()方法,或doGet()/doPost(),这些方法都有两个参数,一个为代表请求的request和代表响应response。

service方法中的response的类型是ServletResponse,而doGet/doPost方法的response的类型是HttpServletResponse,HttpServletResponse是ServletResponse的子接口,功能和方法更加强大。

TomCat下Servlet的请求和响应流程

JavaWeb——HttpServletResponse的使用,文件下载

设置HTTP响应

因为response代表响应,所以我们可以通过该对象分别设置Http响应的响应行,响 应头和响应体

JavaWeb——HttpServletResponse的使用,文件下载

一、设置响应行

response.setStatus(404);  // 设置响应状态码

示例:设置重定向

response.sendRedirect("http://www.baidu.com");

实际上执行的是下面的两行代码

response.setStatus(302);  // 设置302响应码
response.setHeader("Location","http://www.baidu.com")  // 设置响应头,重定向
 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Insert title here</title>
 6 </head>
 7 <body>
 8     恭喜你,注册成功,<span style="color:red" id="second">5</span>秒钟后跳转,如不跳转点击<a href="http://www.baidu.com">这里</a>!.
 9     <script type="text/javascript">
10         window.onload = function(){        <!--页面加载后执行-->
11             var time = 5;
12             var secondEle = document.getElementById("second");
13             var timer = setInterval(function(){
14                 secondEle.innerHTML = time;
15                 time--;
16                 if(time==0){
17                     clearInterval(timer);    <!--清除定时器-->
18                     location.href="http://www.baidu.com";    <!--页面跳转-->
19                 }
20                 
21             },1000);    <!--定时器-->
22         }
23 
24 
25     <!--定时器格式:  setInterval(每过指定的毫秒值,执行的函数)(毫秒值)-->
26     </script>
27 </body>
28 </html>
JS版跳转页面

相关文章:

  • 2021-12-17
  • 2022-01-16
  • 2021-10-30
  • 2021-11-19
  • 2021-10-18
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-18
  • 2022-12-23
  • 2021-07-25
  • 2022-12-23
  • 2022-02-12
  • 2021-12-30
  • 2021-12-15
相关资源
相似解决方案