Mohammad Karmi
Mohammad Karmi

Reputation: 1465

URL pattern servlet mapping

I created hello world example using Spring MVC, but there is one thing I didn't understand in servlet URL mapping, I did the following in web.xml:

<servlet>
    <servlet-name>HelloWeb</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>HelloWeb</servlet-name>
    <url-pattern>/test/*</url-pattern>
</servlet-mapping>

now if I want to call the following controller:

@Controller
@RequestMapping("/hello")
public class HelloWorld {
    @RequestMapping(method = RequestMethod.GET)
    public String printWelcome(ModelMap model){
        model.addAttribute("message","hello world");
        return "index";
    }
}

it will work using the following link: http://localhost:8080/test/hello

but when I change the servlet url-pattern to "/*" and try: http://localhost:8080/hello

it doesn't work, shouldn't it match my servlet ? as * matches everything

Upvotes: 0

Views: 2363

Answers (2)

ScanQR
ScanQR

Reputation: 3820

When you register a servlet with "/*" then it will override all the servlet mappings if there are any. Hence it should be avoided. This overrides default servlet mapping as well hence all default url handling also overridden and hence any specific url matching fails. In your case it is /hello.

With your case, initially you registered with /test/* this registered all your URL's with /test and hence they got identified.

Upvotes: 0

Rohit Gaikwad
Rohit Gaikwad

Reputation: 3914

It doesn't work for /* because, you have not registered/created a controller for that pattern.

It worked for http://localhost:8080/hello because, you have controller @RequestMapping("/hello")

Just change the RequestMapping to @RequestMapping("/") for url-pattern /*

Upvotes: 0

Related Questions