Get parameter sent via jquery ajax in Java Servlet [duplicate] - java

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 5 years ago.
I search this topic on web but I can't get a example that worked.
I will be gladed with someone could give me a help.
this is what I testing.
$.ajax({
url: 'GetJson',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: {id: 'idTest'},
success: function(data) {
console.log(data);
}
});
in Sevlet
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
String id2[] = request.getParameterValues("id");
String id3 = request.getHeader("id");
}
I'm getting null in everything.

I had the same issue with getParameter("foo") returning null in the servlet. Found a simple solution which might be useful to people here. Use the default value
contentType='application/x-www-form-urlencoded; charset=UTF-8'
or leave it out. This will automatically encode the request with the data in parameters.
Hope this helps...

The sort answer is that this data is hidden in the request InputStream.
The following servlet is a demo of how you can use this (I am running it on a JBoss 7.1.1):
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name="fooServlet", urlPatterns="/foo")
public class FooServlet extends HttpServlet
{
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = req.getInputStream();
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buf = new byte[32];
int r=0;
while( r >= 0 ) {
r = is.read(buf);
if( r >= 0 ) os.write(buf, 0, r);
}
String s = new String(os.toByteArray(), "UTF-8");
String decoded = URLDecoder.decode(s, "UTF-8");
System.err.println(">>>>>>>>>>>>> DECODED: " + decoded);
System.err.println("================================");
Enumeration<String> e = req.getParameterNames();
while( e.hasMoreElements() ) {
String ss = (String) e.nextElement();
System.err.println(" >>>>>>>>> " + ss);
}
System.err.println("================================");
Map<String,String> map = makeQueryMap(s);
System.err.println(map);
//////////////////////////////////////////////////////////////////
//// HERE YOU CAN DO map.get("id") AND THE SENT VALUE WILL BE ////
//// RETURNED AS EXPECTED WITH request.getParameter("id") ////
//////////////////////////////////////////////////////////////////
System.err.println("================================");
resp.setContentType("application/json; charset=UTF-8");
resp.getWriter().println("{'result':true}");
}
// Based on code from: http://www.coderanch.com/t/383310/java/java/parse-url-query-string-parameter
private static Map<String, String> makeQueryMap(String query) throws UnsupportedEncodingException {
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for( String param : params ) {
String[] split = param.split("=");
map.put(URLDecoder.decode(split[0], "UTF-8"), URLDecoder.decode(split[1], "UTF-8"));
}
return map;
}
}
With the request:
$.post("foo",{id:5,name:"Nikos",address:{city:"Athens"}})
The output is:
>>>>>>>>>>>>> DECODED: id=5&name=Nikos&address[city]=Athens
================================
================================
{address[city]=Athens, id=5, name=Nikos}
================================
(NOTE: req.getParameterNames() does not work. The map printed in the 4th line contains all the data normally accessible using request.getParameter(). Note also the nested object notation, {address:{city:"Athens"}} → address[city]=Athens)
Slightly unrelated to your question, but for the sake of completeness:
If you want to use a server-side JSON parser, you should use JSON.stringify for the data:
$.post("foo",JSON.stringify({id:5,name:"Nikos",address:{city:"Athens"}}))
In my opinion the best way to communicate JSON with the server is using JAX-RS (or the Spring equivalent). It is dead simple on modern servers and solves these problems.

Related

Error 500 response is not committed

I am trying to send a request to my jsp page i.e manufacturer details and get the attribute via session, but it throws a 500 error.
package com.osahub.disaster.controller;
import java.io.IOException;
import static com.osahub.disaster.controller.Ofymethodadmin.ofy;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import com.osahub.disaster.controller.SendMail;
#SuppressWarnings("serial")
public class admin extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
resp.setContentType("text/plain");
resp.getWriter().println("Data Saved!");
PrintWriter out = resp.getWriter();
String name= req.getParameter("name");
String address = req.getParameter("address");
String email = req.getParameter("email");
String website = req.getParameter("website");
String topex = req.getParameter("topex");
String topdes = req.getParameter("topdes");
String topmob = req.getParameter("topmob");
String year = req.getParameter("year");
String brand = req.getParameter("brand");
String factory = req.getParameter("factory");
String sector = req.getParameter("sector");
String contactpername = req.getParameter("contactpername");
String contactperdes = req.getParameter("contactperdes");
String contactpermob = req.getParameter("contactpermob");
HttpSession currentSession=req.getSession();
currentSession.setAttribute("name", name);
req.getRequestDispatcher("ManufacturerDetails.jsp").forward(req, resp);
SendMail mail = new SendMail();
mail.send(email, "send Test mail from gae" , "this is the mail body");
ManufacturerDetails ad = new ManufacturerDetails(name,address,email,website,topex,topdes,topmob,year,brand,factory,sector,contactpername,contactperdes,contactpermob);
ofy().save().entity(ad);
ofy().clear();
List<ManufacturerDetails> li = ofy().load().type(ManufacturerDetails.class).list();
Iterator<ManufacturerDetails> iter = li.iterator();
while(iter.hasNext())
{
ManufacturerDetails ad1 = iter.next();
System.out.println(ad1.getName());
System.out.println(ad1.getAddress());
System.out.println(ad1.getEmail());
System.out.println(ad1.getWebsite());
System.out.println(ad1.getTopex());
System.out.println(ad1.getTopdes());
System.out.println(ad1.getTopmob());
System.out.println(ad1.getYear());
System.out.println(ad1.getBrand());
System.out.println(ad1.getFactory());
System.out.println(ad1.getSector());
System.out.println(ad1.getContactpername());
System.out.println(ad1.getContactpermob());
System.out.println(ad1.getContactperdes());
}
resp.sendRedirect("about.jsp");
}
}
A response with HTTP status code 500 can be caused by any exception.
However, it looks like in your case the exception is thrown because you call resp.sendRedirect("about.jsp"); after req.getRequestDispatcher("ManufacturerDetails.jsp").forward(req, resp);.
You cannot do that, because once the call to forward() completes, the response is committed. However, it does not mean that doPost() method returns control, it keeps executing. Thus, resp.sendRedirect("about.jsp"); causes java.lang.IllegalStateException exception to be thrown, since the response is already closed.
You have to review your method, and introduce a conditional statement:
if (condition) {
// do something
req.getRequestDispatcher("ManufacturerDetails.jsp").forward(req, resp);
} else {
// do something
resp.sendRedirect("about.jsp");
}
Another option is to introduce an explicit return after req.getRequestDispatcher("ManufacturerDetails.jsp").forward(req, resp);.
500 exception occurs due to the server problem . It is cause because you can write both code - getRequestDispatcher and sendRedirect for execute . And this is not possible . You can not do this because after once send the request paramater it terminate . So you can write both code in if-else condition .

ArrayList issue in HTTP Servlet

I'm using Floodlight REST API in order to monitor a created virtual network in mininet. My goal is to display an arraylist of all the switches, hosts and statistics for the switches on a web browser using Apache Tomcat web server and HTTP Servlet. The application successfully displays all the switches and hosts, but fails when I'm adding the statistics for the switches.
When I'm mapping JSON string to java objects, the server returns the error in this line:
ArrayList<Switch> queues = mapper.readValue(queueJson, new TypeReference<ArrayList<Switch>>() {
});
The error is:
HTTP status 500 - can not deserialize instance of java.util.arraylist out of start_object token
I have testet it without the switch statistics (Queues) part (with only hosts and devices) and everything works fine, but when I'm adding the queues ArrayList, it returns the above mentioned error.
How can I solve this issue ?. My code is shown below. Thanks in advance
package core;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.restlet.data.MediaType;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;
import pojos.Device;
import pojos.Switch;
#WebServlet("/PrintInfo")
public class PrintInfo extends HttpServlet {
private static final long serialVersionUID = 1L;
public PrintInfo() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// create ClientResource object
// List at the switches in the network
ClientResource cResourceSwitches = new ClientResource("http://127.0.0.1:8080/wm/core/controller/switches/json");
StringWriter sWriterSwitches = new StringWriter();
// List all the devices (hosts) in the network
ClientResource cResourceDevices = new ClientResource("http://127.0.0.1:8080/wm/device/");
StringWriter sWriterDevices = new StringWriter();
// List the statistics of the switches in the network
ClientResource cResourceQueues = new ClientResource("http://127.0.0.1:8080/wm/core/switch/all/queue/json");
StringWriter sWriterQueues = new StringWriter();
// get JSON data about switches; the data is put in a string writer
try {
// Getting data from Floodlight as a JSON string
cResourceSwitches.get(MediaType.APPLICATION_JSON).write(sWriterSwitches);
cResourceDevices.get(MediaType.APPLICATION_JSON).write(sWriterDevices);
cResourceQueues.get(MediaType.APPLICATION_JSON).write(sWriterQueues);
} catch (ResourceException e) {
request.setAttribute("error", "Connection with FLoodLight failed!");
request.getRequestDispatcher("WEB-INF/connectionError.jsp").forward(request, response);
return;
}
// put data from string writer into a string object
String switchesJson = sWriterSwitches.toString();
String devicesJson = sWriterDevices.toString();
String queueJson = sWriterQueues.toString();
// map JSON data to Java objects
// ObjectMapper converts between JSON - Java
ObjectMapper mapper = new ObjectMapper();
ArrayList<Switch> switches = mapper.readValue(switchesJson, new TypeReference<ArrayList<Switch>>() {
});
ArrayList<Device> devices = mapper.readValue(devicesJson, new TypeReference<ArrayList<Device>>() {
});
ArrayList<Switch> queues = mapper.readValue(queueJson, new TypeReference<ArrayList<Switch>>() {
});
// put objects in the request so we can use them later in the JSP
request.setAttribute("switches", switches);
request.setAttribute("devices", devices);
request.setAttribute("queues", queues);
// redirect to the jsp
request.getRequestDispatcher("WEB-INF/showInfo.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
}
}
Solved. The Switch class in "ArrayList" can't be used for switch statistics. A new class has to be implemented, which returns the values in
http://127.0.0.1:8080/wm/core/switch/all/queue/json
URI.

Upload multiple files from Android to AppEngine in 1 request

I understand that I can upload 1 file at a time to AppEngine using multipart/form POST requests. AppEngine also supports uploading multiple files but you have to do some hokey JSP stuff for it to work.
I have an app that requires me to upload some form data, 2 images and 3 fields of text. Is this possible to do via AppEngine? I've been trying to find information on this but it's tough nothing works with the flexibility I need. I will be storing the data in the blob store/data store.
I need a Java solution.
This is the signature of my POST method:
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
public void post(
#Context HttpServletRequest request,
#Context HttpServletResponse response)
throws FileUploadException, IOException {}
Copy and paste of the Java Servlet if you really need it. Above is the question and relevant servlet snippets.
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.apache.commons.fileupload.FileItemHeaders;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileReadChannel;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
#Path("/upload")
public class FileUploadServlet {
private BlobstoreService blobstoreService = BlobstoreServiceFactory
.getBlobstoreService();
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
public void post(#Context HttpServletRequest request,
#Context HttpServletResponse response) throws FileUploadException,
IOException {
final ServletFileUpload upload = new ServletFileUpload();
final FileItemIterator fileIter = upload.getItemIterator(request);
while (fileIter.hasNext()) {
final FileItemStream item = fileIter.next();
String name = item.getName();
String fieldName = item.getFieldName();
String contentType = item.getContentType();
Log.d("Name = " + name);
Log.d("Field-Name = " + fieldName);
Log.d("Content-Type = " + contentType);
FileItemHeaders headers = item.getHeaders();
if(headers != null) {
Iterator<String> it = (Iterator<String>)headers.getHeaderNames();
while(it.hasNext()) {
String h = it.next();
Log.d(h + " = " + headers.getHeader(h));
}
}
if (item.isFormField()) {
// Nothing
} else {
RawImageData data = new RawImageData();
data.load(item.openStream());
// RawImageData reads the stream and stores it into a large byte[] called data.imageData
ByteBuffer bb = ByteBuffer.wrap(data.imageData);
FileService fs = FileServiceFactory.getFileService();
AppEngineFile file = fs.createNewBlobFile(contentType);
FileWriteChannel write = fs.openWriteChannel(file, true);
write.write(bb);
write.closeFinally();
String path = file.getFullPath();
Log.d(path);
// Later, read from the file using the file API
boolean lock = false; // Let other people read at the same time
FileReadChannel readChannel = fs.openReadChannel(file,
false);
// CRASHES WITH java.nio.charset.IllegalCharsetNameException: image/jpeg
// contentType = "image/jpeg"
// Again, different standard Java ways of reading from the
// channel.
BufferedReader reader = new BufferedReader(Channels.newReader(readChannel, contentType));
readChannel.close();
}
}
response.setContentType("text/html");
response.getOutputStream().write("success".getBytes());
}
}
Full Exception:
WARNING: /api/upload
java.nio.charset.IllegalCharsetNameException: image/jpeg
at java.nio.charset.Charset.checkName(Charset.java:284)
at java.nio.charset.Charset.lookup2(Charset.java:458)
at java.nio.charset.Charset.lookup(Charset.java:437)
at java.nio.charset.Charset.forName(Charset.java:502)
at java.nio.channels.Channels.newReader(Channels.java:381)
at com.futonredemption.starstarstar.FileUploadServlet.post(FileUploadServlet.java:96)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
blah blah blah
You can create you own multipart file upload handler, then save files via Blobstore FileService API.

InputStream from a URL

How do I get an InputStream from a URL?
for example, I want to take the file at the url wwww.somewebsite.com/a.txt and read it as an InputStream in Java, through a servlet.
I've tried
InputStream is = new FileInputStream("wwww.somewebsite.com/a.txt");
but what I got was an error:
java.io.FileNotFoundException
Use java.net.URL#openStream() with a proper URL (including the protocol!). E.g.
InputStream input = new URL("http://www.somewebsite.com/a.txt").openStream();
// ...
See also:
Using java.net.URLConnection to fire and handle HTTP requests
Try:
final InputStream is = new URL("http://wwww.somewebsite.com/a.txt").openStream();
(a) wwww.somewebsite.com/a.txt isn't a 'file URL'. It isn't a URL at all. If you put http:// on the front of it it would be an HTTP URL, which is clearly what you intend here.
(b) FileInputStream is for files, not URLs.
(c) The way to get an input stream from any URL is via URL.openStream(), or URL.getConnection().getInputStream(), which is equivalent but you might have other reasons to get the URLConnection and play with it first.
Your original code uses FileInputStream, which is for accessing file system hosted files.
The constructor you used will attempt to locate a file named a.txt in the www.somewebsite.com subfolder of the current working directory (the value of system property user.dir). The name you provide is resolved to a file using the File class.
URL objects are the generic way to solve this. You can use URLs to access local files but also network hosted resources. The URL class supports the file:// protocol besides http:// or https:// so you're good to go.
Pure Java:
urlToInputStream(url,httpHeaders);
With some success I use this method. It handles redirects and one can pass a variable number of HTTP headers asMap<String,String>. It also allows redirects from HTTP to HTTPS.
private InputStream urlToInputStream(URL url, Map<String, String> args) {
HttpURLConnection con = null;
InputStream inputStream = null;
try {
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(15000);
con.setReadTimeout(15000);
if (args != null) {
for (Entry<String, String> e : args.entrySet()) {
con.setRequestProperty(e.getKey(), e.getValue());
}
}
con.connect();
int responseCode = con.getResponseCode();
/* By default the connection will follow redirects. The following
* block is only entered if the implementation of HttpURLConnection
* does not perform the redirect. The exact behavior depends to
* the actual implementation (e.g. sun.net).
* !!! Attention: This block allows the connection to
* switch protocols (e.g. HTTP to HTTPS), which is <b>not</b>
* default behavior. See: https://stackoverflow.com/questions/1884230
* for more info!!!
*/
if (responseCode < 400 && responseCode > 299) {
String redirectUrl = con.getHeaderField("Location");
try {
URL newUrl = new URL(redirectUrl);
return urlToInputStream(newUrl, args);
} catch (MalformedURLException e) {
URL newUrl = new URL(url.getProtocol() + "://" + url.getHost() + redirectUrl);
return urlToInputStream(newUrl, args);
}
}
/*!!!!!*/
inputStream = con.getInputStream();
return inputStream;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Full example call
private InputStream getInputStreamFromUrl(URL url, String user, String passwd) throws IOException {
String encoded = Base64.getEncoder().encodeToString((user + ":" + passwd).getBytes(StandardCharsets.UTF_8));
Map<String,String> httpHeaders=new Map<>();
httpHeaders.put("Accept", "application/json");
httpHeaders.put("User-Agent", "myApplication");
httpHeaders.put("Authorization", "Basic " + encoded);
return urlToInputStream(url,httpHeaders);
}
Here is a full example which reads the contents of the given web page.
The web page is read from an HTML form. We use standard InputStream classes, but it could be done more easily with JSoup library.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.6</version>
</dependency>
These are the Maven dependencies. We use Apache Commons library to validate URL strings.
package com.zetcode.web;
import com.zetcode.service.WebPageReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name = "ReadWebPage", urlPatterns = {"/ReadWebPage"})
public class ReadWebpage extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain;charset=UTF-8");
String page = request.getParameter("webpage");
String content = new WebPageReader().setWebPageName(page).getWebPageContent();
ServletOutputStream os = response.getOutputStream();
os.write(content.getBytes(StandardCharsets.UTF_8));
}
}
The ReadWebPage servlet reads the contents of the given web page and sends it back to the client in plain text format. The task of reading the page is delegated to WebPageReader.
package com.zetcode.service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.apache.commons.validator.routines.UrlValidator;
public class WebPageReader {
private String webpage;
private String content;
public WebPageReader setWebPageName(String name) {
webpage = name;
return this;
}
public String getWebPageContent() {
try {
boolean valid = validateUrl(webpage);
if (!valid) {
content = "Invalid URL; use http(s)://www.example.com format";
return content;
}
URL url = new URL(webpage);
try (InputStream is = url.openStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is, StandardCharsets.UTF_8))) {
content = br.lines().collect(
Collectors.joining(System.lineSeparator()));
}
} catch (IOException ex) {
content = String.format("Cannot read webpage %s", ex);
Logger.getLogger(WebPageReader.class.getName()).log(Level.SEVERE, null, ex);
}
return content;
}
private boolean validateUrl(String webpage) {
UrlValidator urlValidator = new UrlValidator();
return urlValidator.isValid(webpage);
}
}
WebPageReader validates the URL and reads the contents of the web page.
It returns a string containing the HTML code of the page.
<!DOCTYPE html>
<html>
<head>
<title>Home page</title>
<meta charset="UTF-8">
</head>
<body>
<form action="ReadWebPage">
<label for="page">Enter a web page name:</label>
<input type="text" id="page" name="webpage">
<button type="submit">Submit</button>
</form>
</body>
</html>
Finally, this is the home page containing the HTML form.
This is taken from my tutorial about this topic.

Redirecting a request using servlets and the "setHeader" method not working

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("<html><head><title>Modified Hello World</title></head><body>");
pw.println("<h1>");
//getInitParameter function reads the contents ot init-param elements.
pw.println(getInitParameter("message"));
pw.println("</h1>");
pw.println("</body></html>");
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:)
Oh no no! That's not how you redirect. It's far more simpler:
public class ModHelloWorld extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
response.sendRedirect("http://www.google.com");
}
}
Also, it's a bad practice to write HTML code within a servlet. You should consider putting all that markup into a JSP and invoking the JSP using:
response.sendRedirect("/path/to/mynewpage.jsp");
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
Alternatively, you could try the following,
resp.setStatus(301);
resp.setHeader("Location", "index.jsp");
resp.setHeader("Connection", "close");
Another way of doing this if you want to redirect to any url source after the specified point of time
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<b><centre>Redirecting to Google<br>");
response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url after 5 seconds
pw.close();
}
}

Categories

Resources