0
votes

I am configuring a basic Spring MVC project and I don't understand why a URL is not getting caught by my controller.

This is in the web.xml

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

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

This is the servlet context:

<annotation-driven />

<resources mapping="/resources/**" location="/resources/" />

<beans:bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.lh.mvcex" />

And this is the HomeController

@Controller
public class HomeController {

    @RequestMapping(value = { "/", "home", "/home.jsp" }, method = RequestMethod.GET)
    public String home_jsp(Locale locale, Model model) {
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
                DateFormat.LONG, locale);

        String formattedDate = dateFormat.format(date);

        model.addAttribute("serverTime", formattedDate);

        return "home";
    }
}

The URLs / and /home are correctly mapped to my home.jsp resource, but not the third (home.jsp), which gives me 404.

Question 1: why?

Furthermore, I would like to map a request (let's say /customhome) that does not leverage the view resolver to return a page, but rather I want it to return plain html. Question 2: how can I return plain html?

Finally, I would like to map a request (let's say /statichome) that returns a resource home.html in the resources folder. Question 3: how can I return the static page?

1

1 Answers

1
votes

This servlet mapping pattern

<url-pattern>/</url-pattern>

is a default url pattern. It will match any request that wasn't matched by any other url-pattern. Presumably your Servlet container has a servlet-mapping of

<url-pattern>*.jsp</url-pattern>

for its JSP handling servlet. This takes precedence over your DispatcherServlet if the requested URL has a .jsp extension.

You can use @ResponseBody and return a String containing the HTML. I do not recommend doing this. Separate your Java from your HTML.

Again with @ResponseBody, you can return a Resource object identifying the resource you want serialized to the response body.