Reading Headers
A servlet can read HTTP headers sent by a client request using HttpServletRequest interface. This interface has two methods for this.String getHeader(String headerName)
int getintHeader(String headerName)
Both these methods are similar except getIntHeader() method is used to return value of headers with int type values. Below code shows how value of "User-Agent" header is read from the user request. (HttpServlet.doGet() method is used in the example).
import javax.servlet.http.*;
import java.io.*;
public class MyServlet extends HttpServlet {
public void doGet(re, res) throws IOException{
String contentType = request.getHeader("Content-type");
....
}
}
Creating/Writing Headers
A servlet can create a header and send back to the client using HttpServletResponse interface; using the following setter methods.void setHeader(String headerName, String headerValue)
int setintHeader(String headerName, int headerValue)
Below code shows how a new header named "My_Header" is created and set on response.
import javax.servlet.http.*;
import java.io.*;
public class MyServlet extends HttpServlet {
public void doGet(re, res) throws IOException{
response.setHeader("My_Header", "new Header value");
....
}
}
Now the client (generally the browser) will receive this new header.
thanks for sharing info
ReplyDeleteThanks for the notes
ReplyDeleteThis's good, useful for SCWCD.
ReplyDeleteCan you add some more of this type quick notes on Servlet?
Great Post. I have not been visiting the site recently. Took a visit again and there were some great comments on the site. Excellent post. Keep up the good work.
ReplyDelete