Search code examples
javaspringspring-mvcweb.xmlurl-pattern

Spring MVC - URL pattern not working


I have the following files:

web.xml:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com xml/ns/javaee/web-app_3_0.xsd"
     version="3.0">



<display-name>To do List</display-name>

<servlet>
 <servlet-name>dispatcher</servlet-name>
 <servlet-class>
    org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/tk-servlet.xml</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
 <servlet-name>dispatcher</servlet-name>
 <url-pattern>/spring-mvc/*</url-pattern>
</servlet-mapping>
</web-app>

LoginController:

package de.yellowsub.tk.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {

    @RequestMapping(value = "/login")
    @ResponseBody
    public String sayHello() {
        return "Hello World!";
    }
}

Now if I put in localhost:8080/login in the URL I can see "Hello World" in the Browser but not if I write localhost:8080/spring-mvc/login

Any ideas?

Also here is the tk-servlet.xml if it's any use:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/bean/spring-beans.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="de.yellowsub" /> //I also tried "de.yellowsub.*"

    <mvc:annotation-driven />

</beans>

Solution

  • Based on your comment you have generated a Spring Boot application. That is quite different from a Spring MVC application, you do not need web.xml or tk-servlet.xml to configure it. You can delete both.

    You can add server.contextPath=/spring-mvc to your application.properties (create it in src/main/resources) to set the context path.

    Also please find a different tutorial, because pure Spring based MVC application is totally different from Spring Boot web application.