How to get a trivial case of Spring MVC view (JSP)

2019-07-22 19:44发布

My app uses Spring MVC (latest; 3.2.2) to create a RESTful API returning JSON, and so far I haven't needed a view layer at all. But now, besides the API, I need a simple utility page (plain dynamic HTML) and wanted to use JSP for that.

I want requests to http://localhost:8080/foo/<id> to go through a controller (Java) and end up in a JSP. Should be simple, right? But I'm getting 404; something is not right in resolving the view.

HTTP ERROR 404
Problem accessing /jsp/foo.jsp. Reason:

    Not Found

Controller:

 @RequestMapping(value = "/foo/{id}")
 public String testing(@PathVariable String id, ModelMap model) {
    model.addAttribute("id", id);
    return "foo";
 }

Defining controllers and mapping requests works; this method gets called just fine.

Spring config:

<mvc:annotation-driven/>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/jsp/" p:suffix=".jsp"/>

The problem is probably here. I've experimented with slightly different prefixes and putting the JSPs under WEB-INF, as well as stuff like <mvc:view-controller path="/*" /> but no luck yet.

(Do I even need to specify InternalResourceViewResolver, or should default view resolvers take care of this?)

JSP files. Under src/main/webapp/jsp (the project uses Maven conventions) I obviously have the JSPs.

Is there something wrong with this location?

web.xml:

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

I have browsed through Spring MVC documentation, but my problem is probably too trivial and obvious to easily find help there. :-P

Can anyone enlighten me on what I'm doing wrong?

1条回答
叼着烟拽天下
2楼-- · 2019-07-22 20:23

I think what you need to do is changing

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

to

<servlet-mapping>
  <servlet-name>mvc-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

/* won't match if there is another folder in the path, like /jsp/foo.jsp. On the other hand / will match everything.

查看更多
登录 后发表回答