问题的背景
首先要理解的是:呈现jsp文件的不是弹簧。它是JspServlet(org.apache.jasper.servlet.JspServlet)来做到这一点的。这个servlet附带了Tomcat(jasper编译器),而不是弹簧。这个JspServlet知道如何编译jsp页面以及如何将其作为html文本返回给客户端。默认情况下,tomcat 中的 JspServlet 仅处理符合两种模式的请求:*.jsp 和 *.jspx。
现在,当春天用(或)渲染视图时,有三件事确实发生了:InternalResourceView
JstlView
- 从模型中获取所有模型参数(由控制器处理程序方法返回,即
"public ModelAndView doSomething() { return new ModelAndView("home") }"
)
- 将这些模型参数公开为请求属性(以便 JspServlet 可以读取它)
- 将请求转发到 JspServlet。 知道每个 *.jsp 请求都应该转发到 JspServlet(因为这是默认 tomcat 的配置)
RequestDispatcher
当您简单地将视图名称更改为home时.html tomcat将不知道如何处理该请求。这是因为没有 servlet 处理 *.html 请求。
溶液
如何解决这个问题。有三种最明显的解决方案:
- 将 html 公开为资源文件
- 指示 JspServlet 同时处理 *.html 请求
- 编写你自己的 servlet(或将另一个现有的 servlet 请求传递给 *.html)。
初始配置(仅处理 jsp)
首先,假设我们配置spring没有xml文件(仅基于@Configuration注释和spring的WebApplicationInitializer接口)。
基本配置将遵循
public class MyWebApplicationContext extends AnnotationConfigWebApplicationContext {
private static final String CONFIG_FILES_LOCATION = "my.application.root.config";
public MyWebApplicationContext() {
super();
setConfigLocation(CONFIG_FILES_LOCATION);
}
}
public class AppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = new MyWebApplicationContext();
servletContext.addListener(new ContextLoaderListener(context));
addSpringDispatcherServlet(servletContext, context);
}
private void addSpringDispatcherServlet(ServletContext servletContext, WebApplicationContext context) {
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet",
new DispatcherServlet(context));
dispatcher.setLoadOnStartup(2);
dispatcher.addMapping("/");
dispatcher.setInitParameter("throwExceptionIfNoHandlerFound", "true");
}
}
package my.application.root.config
// (...)
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Autowired
@Qualifier("jstlViewResolver")
private ViewResolver jstlViewResolver;
@Bean
@DependsOn({ "jstlViewResolver" })
public ViewResolver viewResolver() {
return jstlViewResolver;
}
@Bean(name = "jstlViewResolver")
public ViewResolver jstlViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/internal/");
resolver.setViewClass(JstlView.class);
resolver.setSuffix(".jsp");
return resolver;
}
}
在上面的例子中,我使用UrlBasedViewResolver和后备视图类JstlViewView,但你可以使用InneralResourceViewResolver,因为在你的例子中,这并不重要。
上面的示例将应用程序配置为只有一个视图解析器,该解析器处理以 结尾的 jsp 文件。注意:如前所述,JstlView实际上使用tomcat的RequestDispatcher将请求转发给JspSevlet,以将jsp编译为html。.jsp
解决方案 1 上的实现 - 将 html 公开为资源文件:
我们修改 WebConfig 类以添加新的资源匹配。此外,我们需要修改 jstlViewResolver,以便它既不带前缀也不带后缀:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Autowired
@Qualifier("jstlViewResolver")
private ViewResolver jstlViewResolver;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/someurl/resources/**").addResourceLocations("/resources/");
}
@Bean
@DependsOn({ "jstlViewResolver" })
public ViewResolver viewResolver() {
return jstlViewResolver;
}
@Bean(name = "jstlViewResolver")
public ViewResolver jstlViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix(""); // NOTE: no prefix here
resolver.setViewClass(JstlView.class);
resolver.setSuffix(""); // NOTE: no suffix here
return resolver;
}
// NOTE: you can use InternalResourceViewResolver it does not matter
// @Bean(name = "internalResolver")
// public ViewResolver internalViewResolver() {
// InternalResourceViewResolver resolver = new InternalResourceViewResolver();
// resolver.setPrefix("");
// resolver.setSuffix("");
// return resolver;
// }
}
通过添加此内容,我们说每个 http://my.server/someurl/resources/ 请求都映射到Web目录下的资源目录。因此,如果您将主页.html放在资源目录中,并将浏览器指向 http://my.server/someurl/resources/home.html 该文件将被提供。要由控制器处理此问题,请返回资源的完整路径:
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home(Locale locale, Model model) {
// (...)
return new ModelAndView("/someurl/resources/home.html"); // NOTE here there is /someurl/resources
}
}
如果将一些 jsp 文件(不仅是 *.html 文件)放在同一目录中,home_dynamic.jsp在同一资源目录中,则可以以类似的方式访问它,但您需要使用服务器上的实际路径。该路径不以 /someurl/ 开头,因为这是仅以 .html) 结尾的 html 资源的映射。在这种情况下,jsp是动态资源,最终由JspServlet使用磁盘上的实际路径进行访问。因此,访问jsp的正确方法是:
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home(Locale locale, Model model) {
// (...)
return new ModelAndView("/resources/home_dynamic.jsp"); // NOTE here there is /resources (there is no /someurl/ because "someurl" is only for static resources
}
要在基于 xml 的配置中实现此目的,您需要使用:
<mvc:resources mapping="/someurl/resources/**" location="/resources/" />
并修改您的 jstl 视图解析器:
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- Please NOTE that it does not matter if you use InternalResourceViewResolver or UrlBasedViewResolver as in annotations example -->
<beans:property name="prefix" value="" />
<beans:property name="suffix" value="" />
</beans:bean>
解决方案 2 上的实现:
在此选项中,我们使用tomcat的JspServlet来处理静态文件。因此,您可以在html文件中使用jsp标签:)当然,无论你是否这样做,这都是你的选择。最有可能的是,你想使用纯html,所以干脆不使用jsp标签,内容将像静态html一样提供。
首先,我们删除视图解析器的前缀和后缀,如上一个示例所示:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Autowired
@Qualifier("jstlViewResolver")
private ViewResolver jstlViewResolver;
@Bean
@DependsOn({ "jstlViewResolver" })
public ViewResolver viewResolver() {
return jstlViewResolver;
}
@Bean(name = "jstlViewResolver")
public ViewResolver jstlViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver(); // NOTE: this time I'm using InternalResourceViewResolver and again it does not matter :)
resolver.setPrefix("");
resolver.setSuffix("");
return resolver;
}
}
现在我们添加 JspServlet 来处理 *.html 文件:
public class AppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = new MyWebApplicationContext();
servletContext.addListener(new ContextLoaderListener(context));
addStaticHtmlFilesHandlingServlet(servletContext);
addSpringDispatcherServlet(servletContext, context);
}
// (...)
private void addStaticHtmlFilesHandlingServlet(ServletContext servletContext) {
ServletRegistration.Dynamic servlet = servletContext.addServlet("HtmlsServlet", new JspServlet()); // org.apache.jasper.servlet.JspServlet
servlet.setLoadOnStartup(1);
servlet.addMapping("*.html");
}
}
重要的是,要使这个类可用,你需要从tomcat的安装中添加jasper.jar只是为了编译时间。如果你有 maven 应用程序,通过使用为 jar 提供的 scope=,这实际上很容易。maven 中的依赖项将如下所示:
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>${tomcat.libs.version}</version>
<scope>provided</scope> <!--- NOTE: scope provided! -->
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jsp-api</artifactId>
<version>${tomcat.libs.version}</version>
<scope>provided</scope>
</dependency>
如果你想以xml的方式做到这一点。您需要注册 jsp servlet 来处理 *.html 请求,因此您需要将以下条目添加到 Web 中.xml
<servlet>
<servlet-name>htmlServlet</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>htmlServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
现在,在控制器中,您可以访问 html 和 jsp 文件,就像在前面的示例中一样。优点是没有解决方案 1 中需要的“/someurl/”额外映射。您的控制器将如下所示:
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home(Locale locale, Model model) {
// (...)
return new ModelAndView("/resources/home.html");
}
要指向您的jsp,您正在执行完全相同的操作:
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home(Locale locale, Model model) {
// (...)
return new ModelAndView("/resources/home_dynamic.jsp");
}
解决方案 3 的实施:
第三种解决方案在某种程度上是解决方案1和解决方案2的组合。因此,在这里,我们希望将所有请求传递给 *.html 其他 servlet。你可以自己写,或者寻找一些已经存在的servlet的好候选者。
如上所述,我们首先清理视图解析器的前缀和后缀:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Autowired
@Qualifier("jstlViewResolver")
private ViewResolver jstlViewResolver;
@Bean
@DependsOn({ "jstlViewResolver" })
public ViewResolver viewResolver() {
return jstlViewResolver;
}
@Bean(name = "jstlViewResolver")
public ViewResolver jstlViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver(); // NOTE: this time I'm using InternalResourceViewResolver and again it does not matter :)
resolver.setPrefix("");
resolver.setSuffix("");
return resolver;
}
}
现在,我们不再使用tomcat的JspServlet,而是编写自己的servlet(或重用一些现有的):
public class StaticFilesServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
String resourcePath = request.getRequestURI();
if (resourcePath != null) {
FileReader reader = null;
try {
URL fileResourceUrl = request.getServletContext().getResource(resourcePath);
String filePath = fileResourceUrl.getPath();
if (!new File(filePath).exists()) {
throw new IllegalArgumentException("Resource can not be found: " + filePath);
}
reader = new FileReader(filePath);
int c = 0;
while (c != -1) {
c = reader.read();
if (c != -1) {
response.getWriter().write(c);
}
}
} finally {
if (reader != null) {
reader.close();
}
}
}
}
}
我们现在指示弹簧将所有请求传递给*.html到我们的servlet
public class AppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = new MyWebApplicationContext();
servletContext.addListener(new ContextLoaderListener(context));
addStaticHtmlFilesHandlingServlet(servletContext);
addSpringDispatcherServlet(servletContext, context);
}
// (...)
private void addStaticHtmlFilesHandlingServlet(ServletContext servletContext) {
ServletRegistration.Dynamic servlet = servletContext.addServlet("HtmlsServlet", new StaticFilesServlet());
servlet.setLoadOnStartup(1);
servlet.addMapping("*.html");
}
}
优点(或缺点,取决于你想要什么)是jsp标签显然不会被处理。控制器看起来像往常一样:
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home(Locale locale, Model model) {
// (...)
return new ModelAndView("/resources/home.html");
}
对于 jsp:
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home(Locale locale, Model model) {
// (...)
return new ModelAndView("/resources/home_dynamic.jsp");
}