java重定向不起作用,使用servlet和“setHeader”重定向请求方法不起作用

I am new to servlet development, and I was reading an ebook, and found that I can redirect to a different web page using

setHeader("Location", "http://www.google.com")

But this is not working, as I have written this code as:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class ModHelloWorld extends HttpServlet{

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

// response.addHeader("Location", "http://www.google.com");

response.setHeader("Location", "http://www.google.com");

response.setContentType("text/html");

PrintWriter pw = response.getWriter();

pw.println("

Modified Hello World");

pw.println("

");

//getInitParameter function reads the contents ot init-param elements.

pw.println(getInitParameter("message"));

pw.println("");

pw.println("");

pw.close();

}

}

i have checked the headers using my program to get the headers of the webpage which is as under:

import java.net.*;

import java.io.*;

class getHeaders{

public static void main(String args[]){

URL url = null;

URLConnection urc = null;

try {

url = new URL(args[0]);

urc = url.openConnection();

for(int i=0 ; ; i++) {

String name = urc.getHeaderFieldKey(i);

String value = urc.getHeaderField(i);

if(name == null && value == null)//both null so end of header

break;

else if(name == null){//first line of header{

System.out.println("Server HTTP version, Response code: ");

System.out.println(value);

System.out.println("ENd of first header field");

} else {

System.out.println("name of header is: " + name + " and its value is : " + value);

}

}

} catch(MalformedURLException e){

System.out.println("Malformed URL " + e.getMessage());

} catch(IOException e){

e.printStackTrace();

}

}

}

And i am getting the output as:

Server HTTP version, Response code:

HTTP/1.1 200 OK

ENd of first header field

name of header is: Server and its value is : Apache-Coyote/1.1

name of header is: Location and its value is : http://www.google.com

name of header is: Content-Type and its value is : text/html

name of header is: Content-Length and its value is : 101

name of header is: Date and its value is : Sat, 05 Mar 2011 15:27:29 GMT

But I was not redirected to google's page from my browser.

Thanks in advance:)

解决方案

As you can see, the response is still HTTP/1.1 200 OK. To indicate a redirect, you need to send back a 302 status code:

response.setStatus(HttpServletResponse.SC_FOUND); // SC_FOUND = 302

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值