Coder Social home page Coder Social logo

servlet-url-mapper's Introduction

Release CircleCI

Servlet Url Mapper

This small and non-invasive library is intended to be used in servlet-only environments where for some reasons developers are forced to use Servlet API directly (like in Atlassian plugin SDK).

In such servlet-only environments, this library helps to handle nested URL structures in one servlet.

Non-invasive: You don't need to use servlet url mapper in every servlet, you can use only in some of them.

Assume you have a ProductsServlet with /products, /products/* URL mapping. Then you would handle request like follows:

Traditional way

doGet method gets messy.

URL Method Handling Method
/products GET ProductsServlet#doGet
/products/13 GET ProductsServlet#doGet
/products/13/campaigns GET ProductsServlet#doGet
/products POST ProductsServlet#doPost

Servlet URL Mapper way

You can use different methods for different URLs in the same servlet. You can even use another Class' method to handle requests.

URL Method Handling Method
/products GET ProductsServlet#list
/products/13 GET ProductsServlet#show
/products/13/campaigns GET CampaignsHelper#show
/products POST ProductsServlet#create

Quick start

  1. Add the dependency

You should use jitpack to add this library as a dependency for Maven or Gradle (or others).

<repositories>
  <repository>
      <id>jitpack.io</id>
      <url>https://jitpack.io</url>
  </repository>
</repositories>
<dependency>
    <groupId>com.github.kodgemisi</groupId>
    <artifactId>servlet-url-mapper</artifactId>
    <version>1.2.0</version>
</dependency>

See https://jitpack.io/#kodgemisi/servlet-url-mapper

  1. Extend your servlet from MappingServlet
public class MyServlet extends MappingServlet {
	//...
}
  1. Register your url mappings via protected urlMappingRegistrar field from MappingServlet. You can do this either in constructor or in init method.
@WebServlet(urlPatterns = {"/products", "/products/"})
public class MyServlet extends MappingServlet {
  public MyServlet() {
      this.urlMappingRegistrar
      
             // matches GET request to "host/context-root/products"
             .get("/", this::list)

             // matches GET request to "host/context-root/products/all"
             .get("/all", this::list) // note that the same method can be used for multiple url mappings

             // matches GET request to "host/context-root/products/{id}"
             .get("/{id}", this::show)

             // matches POST request to "host/context-root/products"
             .post("/", this::create)

             // matches POST request to "host/context-root/products/{id}/address"
             .post("/{id}/address", AddressHelper::addAddress);
      // and so on...
  }

  // any access modifier can be used
  private void list(HttpServletRequest request, HttpServletResponse response, ServletUrl servletUrl) throws ServletException, IOException {
      // your code...
  }

  private void show(HttpServletRequest request, HttpServletResponse response, ServletUrl servletUrl) throws ServletException, IOException {
      Integer id = servletUrl.variable("id"); // this is parsed from url: /{id}
      // your code...
  }

  // and rest of your methods...
}

Java 8 usage remainder: Note that (assuming you have an AddressHelper class in your project) AddressHelper::addAddress usage implies that addAddress is a static method. You can use non-static methods by providing an object instead of Class name like addressHelper::addAddress assuming addressHelper is an object of AddressHelper class.

License and Copyright

© 2017 - 2020 Kod Gemisi Ltd.

All material in this library's repository is copyrighted by Kod Gemisi Ltd unless stated otherwise.

This library is subject to the terms of the Mozilla Public License, v. 2.0. You can find full license in license.txt file or at http://mozilla.org/MPL/2.0/ adress.

There is also an easy to understand version of the license.

servlet-url-mapper's People

Contributors

destan avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

tvn24van

servlet-url-mapper's Issues

docs improvement

add query parameter handling to the docs

this lib has nothing to do with query parameters. they're expected to be handled as usual. also state that there is no mapping according to query params.

add limitations

thread safety when dynamically adding new patterns.

removing patterns

name in ServletUrl should be optional

there should be this API as well: ServletUrl(String urlPattern, Class<?>[] types)

in that case name should be generated from urlPattern.

overload this method com.kodgemisi.servlet_url_mapping.ServletUrlPattern#register(java.lang.String, java.lang.String, com.kodgemisi.servlet_url_mapping.ServletRequestHandler, java.lang.Class<?>...)

path variable ignores '.'

instead of return "(\\w+)"; use return "([^/]+)";

	private String getRegexGroupByType(Class<?> clazz) {
		if (String.class.equals(clazz)) {
			return "(\\w+)";
		}
		if (Number.class.isAssignableFrom(clazz)) {
			return "(\\d+)";
		}
		if (Boolean.class.equals(clazz)) {
			return "(true|false|True|False|TRUE|FALSE)";
		}
		throw new IllegalArgumentException("Unsupported Type " + clazz.getName());
	}

Mapping documentation

URL //path didn't match any registered urls!
does it because of a missing mapping of /servlet-mapping/*

style improvements

if (invokeHandler && urlMappings.get(servletUrl) != null) {
    urlMappings.get(servletUrl).handleRequest(request, response, result);
}

above part doesn't belong to parseInternal. classical solid violation!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.