request实现请求重定向和request的一些细节

package cn.itcast.response;


import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


//实现请求重定向
/*
 * 重定向的特点:
 *   1.浏览器会向服务器发送2次,意味着就有2个request、response
 *   2.用重定向技术,浏览器地址会发生变化
 *   
 *   用户登陆和显示购物车时,通常会用到重定向
 */
public class ResponseDemo7 extends HttpServlet {


//同时调用getOutputStream和getWriter方法会抛java.lang.IllegalStateException: getOutputStream() has already been called for this response
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


//要对http协议很熟悉
// response.setStatus(302);
// response.setHeader("location", "/day06/index.jsp");

//response.sendRedirect("/day06/index.jsp");
response.getOutputStream();
this.getServletContext().getRequestDispatcher("/ResponseDemo8").forward(request, response);
}



public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


doGet(request, response);
}


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
服务器可以通过HTTP协议中的重定向和代理来实现重定向和转发请求重定向是指服务器返回一个HTTP响应,其中包含一个重定向的URL地址,客户端浏览器会自动向该URL重新发起请求。常见的重定向状态码有301和302。 转发请求是指服务器代理客户端浏览器向其他服务器发起请求,并将响应返回给客户端浏览器。常见的代理服务器有Nginx和Apache。 以下是一个基于Node.js的HTTP服务器示例,实现重定向和转发请求: ```javascript const http = require('http'); const url = require('url'); const request = require('request'); const server = http.createServer((req, res) => { const reqUrl = url.parse(req.url, true); if (reqUrl.pathname === '/redirect') { res.writeHead(302, { 'Location': 'https://www.baidu.com/' }); res.end(); } else if (reqUrl.pathname === '/proxy') { const proxyUrl = 'https://www.baidu.com' + reqUrl.path; request(proxyUrl).pipe(res); } else { res.writeHead(404); res.end(); } }); server.listen(8080, () => { console.log('Server running at http://localhost:8080/'); }); ``` 当客户端浏览器访问`http://localhost:8080/redirect`时,服务器会返回302状态码和重定向的URL地址`https://www.baidu.com/`,客户端浏览器会自动向该URL重新发起请求。 当客户端浏览器访问`http://localhost:8080/proxy`时,服务器会代理客户端浏览器向`https://www.baidu.com`发起请求,并将响应返回给客户端浏览器。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值