我是 Spring 的初学者,我正在尝试了解 Controller 的工作原理。
我有几个用 @RequestMapping
注释的方法,一切正常,但我不知道如何处理简单的页面请求。
假设我必须从一个页面重定向到另一页面,而不进行服务器逻辑。如果我创建重定向到 PageA.jsp
的 url,似乎我总是需要定义在 Controller 中捕获请求的方法,声明一个实际上为空的方法,如下所示:
@RequestMapping(value="/PageA.jsp")
public String redirectToPageA(){
return "PageA";
}
如果我不遵循这种方法,我会收到 404 错误,因为 Controller 找不到映射。我不太喜欢这种方法,因为它用无用的空方法填充我的 Controller 。
建议的方法是什么?
最佳答案
我建议使用view resolver .
了解更多信息 here - 17.5.1 Resolving views with the ViewResolver interface from 17. Web MVC framework .
在该部分您有
As an example with JSP as a view technology, you can use the UrlBasedViewResolver. This view resolver translates a view name to a URL and hands the request over to the RequestDispatcher to render the view
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean>
When returning test as a logical view name, this view resolver forwards the request to the RequestDispatcher that will send the request to /WEB-INF/jsp/test.jsp. including the code.
和this answer具有基于注释的 View 解析器配置(除非您可以使用 UrlBasedViewResolver)。
关于java - Spring页面重定向好习惯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30933440/