Java Servlet get request url information - getRequestURL() and getQueryString()

A servlet container breaks up the requesting URL into convenient components for the servlet. Here is sample code to get all the information you may need from Request URL


Requesting URL and sample java code

http://localhost:8080/URLRewrite/HelloWorld?as400samplecode
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;

public class HelloWorld extends HttpServlet {
 private static final long serialVersionUID = 1L;

 public HelloWorld() {
  super();
 }

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out.println("<html>");
  out.println("<head>");
  out.println("<title>Hello World!</title>");
  out.println("</head>");
  out.println("<body>");
  out.println("<h1>Hello World!</h1>");
  out.println("<h3>URL = "+request.getRequestURL()+"</h3>");
  out.println("<h3>URI = "+request.getRequestURI()+"</h3>");
  out.println("<h3>Scheme = "+request.getScheme()+"</h3>");
  out.println("<h3>Server Name = "+request.getServerName()+"</h3>");
  out.println("<h3>Server Port = "+request.getServerPort()+"</h3>");
  out.println("<h3>Context Path = "+request.getContextPath()+"</h3>");
  out.println("<h3>Servlet Path = "+request.getServletPath()+"</h3>");
  out.println("<h3>Query String = "+request.getQueryString()+"</h3>");
  out.println("</body>");
  out.println("</html>");
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doGet(request, response);
 }

}

Output of the above program

Hello World!

URL = http://localhost:8080/URLRewrite/HelloWorld

URI = /URLRewrite/HelloWorld

Scheme = http

Server Name = localhost

Server Port = 8080

Context Path = /URLRewrite

Servlet Path = /HelloWorld

Query String = as400samplecode

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.