带斜杠的@RequestMapping无法返回视图

时间:2013-08-05 19:01:53

标签: spring-mvc

我有一个愚蠢的问题我不知道为什么会发生这种情况 - 如果我的映射中有斜杠,则视图解析失败;我有这个控制器:

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

@Controller
public class PartialsController {

  @RequestMapping ("/views/partials/{view}") // Doesn't work!
  public String partial (@PathVariable ("view") String view) {
    System.out.println ("\n\nVIEW=\"" + view + "\"\n\n");
    return "partials/" + view;
  }

  @RequestMapping ("/partial-{view}-view") // Works!!!
  public String test (@PathVariable ("view") String view) {
    return partial (view);
  }

  @RequestMapping ("/views/partials/{view}/show.html") // Doesn't work!
  public String test2 (@PathVariable ("view") String view) {
    return partial (view);
  }
}

完整堆栈跟踪在这里:http://pastebin.com/CXwYd9i3这里是它的顶部(我在每种情况下都看到了我的system.out):

[DEBUG] : Could not complete request
java.lang.NullPointerException
at java.net.URLEncoder.encode(URLEncoder.java:205)
at java.net.URLEncoder.encode(URLEncoder.java:171)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:474)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:378)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:669)
    ...

我真的很想使用第一种方法,它对我正在做的事情更有意义;非常感谢您的任何帮助!

P.S。忘记添加,这是我的Java配置:

@Override
public void onStartup (ServletContext servletContext) throws ServletException {
  AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext ();
  mvcContext.register (MvcConfiguration.class);
  Dynamic dispatcher = servletContext.addServlet ("dispatcher", new DispatcherServlet (mvcContext));
  dispatcher.setLoadOnStartup (1);
  dispatcher.addMapping ("/");
}

2 个答案:

答案 0 :(得分:0)

试试这个:

 @Override
public void onStartup (ServletContext servletContext) throws ServletException {
  AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext ();
  mvcContext.register (MvcConfiguration.class);
  Dynamic dispatcher = servletContext.addServlet ("dispatcher", new DispatcherServlet (mvcContext));
  dispatcher.setLoadOnStartup (1);
  dispatcher.addMapping ("/*"); //<- It will dispatch all URLs, not only those which starts with /
}

答案 1 :(得分:0)

我实际上已经弄明白了,输入一个回复让我觉得我设置的JSP视图解析器出了问题,确实有:

@Bean (name = "jspViewResolver")
public ViewResolver jspViewResolver () {
  return new InternalResourceViewResolver () {
    {
      setPrefix ("/META-INF/resources/mev/views/");
      setSuffix (".jsp");
      setOrder (2);
      setExposeContextBeansAsAttributes (true);
    }
  };
}

我在META-INF之前没有领先的斜杠。是的,我在一个奇怪的地方有我的看法。无论如何,谢谢!