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

梦想的初衷 提交于 2020-01-04 05:26:09

问题


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:


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.



来源:https://stackoverflow.com/questions/16383091/how-to-get-a-trivial-case-of-spring-mvc-view-jsp-resolving-to-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!