Home Tutorial Servlet Java Servlet : Get URL Example

 
 

Java Servlet : Get URL Example
Posted on: October 4, 2012 at 12:00 AM
In this tutorial, You will learn how to get url of servlet.

Java Servlet : Get URL Example

In this tutorial, You will learn how to get url of servlet.

Servlet getRequestURL :

getRequestURL() method reconstruct the requested client URL. It returns the current URL which containing protocol, server name, port number and server path. It doesn't include query string parameters. It returns URL in StringBuffer in place of String so if required you can add query string parameters.

Example :  In this example we are using getRequestURL() method to get current URL.

GetURLExample.java

package net.roseindia;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class GetURLExample extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		out.println("Current URL : " + request.getRequestURL());
		
	}
}

web.xml -

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>ServletExample</display-name>

<!--GetURL servlet mapping-->

<servlet>
<servlet-name>GetURLExample</servlet-name>
<servlet-class>net.roseindia.GetURLExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetURLExample</servlet-name>
<url-pattern>/getURLExample</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>

</welcome-file-list>
</web-app>

Output :

Related Tags for Java Servlet : Get URL Example:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.