Servlet and path parameters like /xyz/{value}/test

2019-01-01 16:02发布

Does servlet support urls as follows:

/xyz/{value}/test

where value could be replaced by text or number.

How to map that in the web.xml?

6条回答
与君花间醉酒
2楼-- · 2019-01-01 16:20

You shouldn't be doing that in web.xml rather you can point every request to your filter (Patternfilter) and can check for URL

package com.inventwheel.filter;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

/**
 * Servlet Filter implementation class PatternFilter
 */
@WebFilter("/*")
public class PatternFilter implements Filter {

    /**
     * Default constructor. 
     */
    public PatternFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            String servletPath = ((HttpServletRequest)request).getServletPath();
            String requestURI = ((HttpServletRequest)request).getRequestURI();
            Pattern pattern = Pattern.compile(".*"+servletPath+"/(.*)");
            Matcher matcher = pattern.matcher(requestURI);
            if (matcher.matches())
            {
            String param = matcher.group(1);
            // do stuff with param here..
            }

        chain.doFilter(request, response);
    }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}
查看更多
姐姐魅力值爆表
3楼-- · 2019-01-01 16:25

As stated above, base servlets does not support patterns like you specified in your question. Spring MVC does support patterns. Here is a link to the pertinent section in the Spring Reference Document.

查看更多
旧人旧事旧时光
4楼-- · 2019-01-01 16:29

It does support mapping that url; but doesn't offer any validation.

In your web xml, you could do this....

/xyz/*

But that won't guarantee that the trailing test is present and that it is the last item. If you're looking for something more sophisticated, you should try urlrewritefilter.

http://code.google.com/p/urlrewritefilter/

查看更多
柔情千种
5楼-- · 2019-01-01 16:31

It's not supported by Servlet API to have the URL pattern wildcard * in middle of the mapping. It only allows the wildcard * in the end of the mapping like so /prefix/* or in the start of the mapping like so *.suffix.

With the standard allowed URL pattern syntax your best bet is to map it on /xyz/* and extract the path information using HttpServletRequest#getPathInfo().

So, given an <url-pattern>/xyz/*</url-pattern>, here's a basic kickoff example how to extract the path information, null checks and array index out of bounds checks omitted:

String pathInfo = request.getPathInfo(); // /{value}/test
String[] pathParts = pathInfo.split("/");
String part1 = pathParts[1]; // {value}
String part2 = pathParts[2]; // test
// ...

If you want more finer grained control like as possible with Apache HTTPD's mod_rewrite, then you could look at Tuckey's URL rewrite filter.

查看更多
笑指拈花
6楼-- · 2019-01-01 16:31

You can use this library: http://zerh.github.io/ServletIO/, so you can convert your servlets in MVC controllers and use pretty urls

查看更多
长期被迫恋爱
7楼-- · 2019-01-01 16:39

As others have indicated, the servlet specification does not allow such patterns; however, you might consider JAX-RS which does allow such patterns, if this is appropriate for your use case.

@Path("/xyz/{value}/test")
public class User { 

    public String doSomething(@PathParam("value") final String value) { ... }

}

Or:

@Path("/xyz/{value}")
public class User { 

    @Path("test")
    public String doTest(@PathParam("value") final String value) { ... }

}

(Related to: https://stackoverflow.com/a/8303767/843093.)

查看更多
登录 后发表回答