需要什么:
在Tomcat的address有一个简单的Web应用程序在运行http://localhost:8080/
。应该添加以下URL的处理程序:
GET http://localhost:8080/request/report/custom_report?from=2013-10-12&to=2014-10-12&download=true
它将简单地写入HttpServletResponse
一些数据,即不涉及视图。
做了什么:
根据Spring MVC的官方文档,以下映射DispatcherServlet
已添加到web.xml
<servlet>
<servlet-name>springDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcher</servlet-name>
<url-pattern>/request/*</url-pattern>
<!-- PLEASE NOTE that mapping to /* is not an option -->
</servlet-mapping>
现在,由于使用了最新版本,因此spring-webmvc-4.0.5.RELEASE
我想以最小的XML or Java
配置添加上述处理程序,因此我创建了控制器类:
package org.yura.servlet.spring;
@Controller
public class SpringRequestController {
@RequestMapping(value = "/report/custom_report",
method = GET,
produces = "application/pdf")
public void getCustomReport(
@RequestParam("from") @DateTimeFormat(pattern = "yyyy-MM-dd") final Date from,
@RequestParam("to") @DateTimeFormat(pattern = "yyyy-MM-dd") final Date to,
@RequestParam("download") final boolean download,
final HttpServletResponse response) throws IOException {
takeParamsAndWriteReportAsPdfToServletResponse(from, to, download, response.getOutputStream());
}
然后,为了使它在Controller
Spring之前被“拾取”,我将其放在具有以下配置的文件夹中的springDispatcher-servlet.xml
旁边(请告知是否可以进一步简化它):web.xml
WEB-INF
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="org.yura.servlet.spring" />
</beans>
问题
使用此配置,在启动Tomcat并导航到上述URL之后,出现Error 404。
问题1:请告知处理程序URL出了什么问题-我应该将它们指定为相对的还是什么?(因为按照日志,通常会创建DispatcherServlet)
问题2:是否可以将配置从springDispatcher-servlet.xml
我的Controller
类移到我的类中,以免将请求处理逻辑分散到多个文件中。
提前致谢...
您尚未启用MVC堆栈。添加
<mvc:annotation-driven />
到您springDispatcher-servlet.xml
(以及适当的名称空间)。
中的配置springDispatcher-servlet.xml
不仅仅是请求处理配置。它可以包含任何bean声明。如果有的话,可以将其移至Java配置,但不应将其包含在@Controller
源代码中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句