Get servlet path in java

AVAJAVA Web Tutorials

How do I get the location of my web application context in the file system?

Web Tutorials :: Servlets :: 18. How do I get the location of my web application context in the file system?

  1. Ajax (1)
  2. Ant (16)
  3. Apache Web Server (8)
  4. Bioinformatics (10)
  5. Cascading Style Sheets (47)
  6. Classes and Objects (14)
  7. Database (13)
  8. Design Patterns (22)
  9. Eclipse (39)
  10. Files (62)
  11. General Java (69)
  12. JSPs (9)
  13. Java Basics (11)
  14. Linux (23)
  15. Logging (5)
  16. Maven (88)
  17. Search (12)
  18. Servlets (20)
  19. Struts (1)
  20. Text (19)
  21. Tomcat (8)
  22. Version Control (8)
  23. Windows (2)
  24. XML (1)

Description: This tutorial describes how to use the ServletContext to get the location of the web application context directory in the file system.

Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0) || Tomcat 5.5.20

A web application’s context path is the directory that contains the web application’s WEB-INF directory. It can be thought of as the ‘home’ of the web app. Often, when writing web applications, it can be important to get the actual location of this directory in the file system, since this allows you to do things such as read from files or write to files.

Читайте также:  Java api java util list

This location can be obtained via the ServletContext object’s getRealPath() method. This method can be passed a String parameter set to File.separator to get the path using the operating system’s file separator («/» for UNIX, «\» for Windows).

The TestServlet class below demonstrates getting and displaying this path in a servletW.

TestServlet.java

package test; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class TestServlet extends HttpServlet < private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException < ServletContext servletContext = getServletContext(); String contextPath = servletContext.getRealPath(File.separator); PrintWriter out = response.getWriter(); out.println("
File system context path (in TestServlet): "
+ contextPath); > >

The TestFilter class demonstrates getting and displaying the path in a filter.

TestFilter.java

package test; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class TestFilter implements Filter < FilterConfig filterConfig = null; public void init(FilterConfig filterConfig) throws ServletException < this.filterConfig = filterConfig; > public void destroy() < >public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException < HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; ServletContext servletContext = filterConfig.getServletContext(); String contextPath = servletContext.getRealPath(File.separator); PrintWriter out = response.getWriter(); out.println("File system context path (in TestFilter): " + contextPath); filterChain.doFilter(request, response); > >

If I fire up my web application and hit http://localhost:8080/tomcat-demo/test in a web browser, I see that both the filter and the servlet display the path to my context directory in the file system.

In case it is useful, the project above utilizes the following structure:

Here is my web.xmlW file. Both the servlet and the filter are mapped to «/test».

web.xml

 version="1.0" encoding="UTF-8"?>  id="tomcat-demo" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  TestFilter test.TestFilter   TestFilter /test   TestServlet test.TestServlet   TestServlet /test   

Web Tutorials :: Servlets :: 18. How do I get the location of my web application context in the file system?

Copyright © 2014 Code Strategies | Template: Free CSS Templates | Contact

Источник

Context Path vs. Servlet Path in Spring

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

1. Introduction

DispatcherServlet plays a significant role in Spring applications and provides a single entry point for the application. Whereas the context path defines the URL that the end-user will access the application.

In this tutorial, we’re going to learn about the differences between context path and servlet path.

2. Context Path

Simply put, the context path is a name with which a web application is accessed. It is the root of the application. By default, Spring Boot serves the content on the root context path (“/”).

So, any Boot application with default configuration can be accessed as:

However, in some cases, we may wish to change the context of our application. There are multiple ways to configure the context path, and application.properties is one of them. This file resides under the src/main/resources folder.

Let’s configure it using the application.properties file:

server.servlet.context-path=/demo

As a result, the application main page will be:

When we deploy this application to an external server, this modification helps us to avoid accessibility issues.

3. Servlet Path

The servlet path represents the path of the main DispatcherServlet. The DispatcherServlet is an actual Servlet, and it inherits from HttpSerlvet base class. The default value is similar to the context path, i.e. (“/”):

In the earlier versions of Boot, the property was in the ServerProperties class and known as server.servlet-path =/.

From 2.1.x, this property is moved to the WebMvcProperties class and renamed as spring.mvc.servlet.path =/.

Let’s modify the servlet path:

spring.mvc.servlet.path=/baeldung

Because a servlet belongs to a servlet context, changing the context path will affect the servlet path too. So, after modifications, the application servlet path will become http://localhost:8080/demo/baeldung.

In other words, if a style sheet was being served as http://localhost:8080/demo/style.css, now will serve as http://localhost:8080/demo/baeldung/style.css.

Usually, we don’t configure the DispatcherServlet by ourselves. But, if we really need to do it, we have to provide the path of our custom DispatcherServlet.

4. Conclusion

In this quick article, we looked at the semantics of context path and servlet path. We also saw what these terms represent and how they work together in a Spring application.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

How to get servlet path?

send pies

posted 2 years ago

  • Report post to moderator
  • I know that we get the servlet path using request.getServletPath(). But in my case, let’s say my request url is http://localhost:8080/feedback/questions/deletequestion/39 . I want to get the number 39 which is after the delete question. How can I get it using request.getServletPath().

    Saloon Keeper

    send pies

    posted 2 years ago

    • 1
  • Report post to moderator
  • getServletPath is likely not the right method to use (although that depends on your servlet mapping, about which we know nothing). Check out getRequestURI, possibly in conjunction with String.substring and String.lastIndexOf.

    Sheriff

    Chrome

    send pies

    posted 2 years ago

    • 1
  • Report post to moderator
  • The official way to get the part of the path after the servlet path is to use HttpServletRequest.getPathInfo(). It’s also mentioned on the article Tim linked to.

    SCJP 1.4 — SCJP 6 — SCWCD 5 — OCEEJBD 6 — OCEJPAD 6
    How To Ask Questions How To Answer Questions

    Saloon Keeper

    send pies

    posted 2 years ago

    • 1
  • Report post to moderator
  • In many cases, you can combine getServletPath() with getRequestURI(). Assuming you have a straightforward servlet URL mapping, the two strings will both have the same leading values, so you can just snip off the common part from the URI and the remainder should give you what you need.

    The secret of how to be miserable is to constantly expect things are going to happen the way that they are «supposed» to happen.

    You can have faith, which carries the understanding that you may be disappointed. Then there’s being a willfully-blind idiot, which virtually guarantees it.

    Источник

    getServletPath() Method Example

    This program uses getServletPath() of HttpServletRequest to retrieve the alias name (of ) tag. Client uses this alias name to call the Servlet.

    Following is the method signature. Method is defined in HttpServletRequest interface.

    public abstract java.lang.String getServletPath();

    Example on getServletPath()

    Client Program: ClientData.html

    web.xml entry for ClientInformation servlet

     efgh ClientInformation  efgh /jasmine  

    Let us go to the coding part.

    Server Program: ClientInformation.java

    import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class ClientInformation extends HttpServlet < public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException < res.setContentType("text/html"); PrintWriter out = res.getWriter(); String str = req.getServletPath(); out.println("req.getServletPath() : " + str); out.close(); >>

    Output screen of ClientData.html with text field filled up.

    getServletPath()

    The output screen when submit button is clicked.

    getServletPath()

    Observe, the getServletPath() prints just the alias name and not complete URL. To retrieve complete URL, use getRequestURL() method of HttpServletRequest.

    Pass your comments and suggestions on this tutorial «getServletPath() Method Example». It improves the quality of site.

    Leave a Comment Cancel Reply

    If you like our content, please show your love by liking our page on facebook

    Источник

    Оцените статью