Spring Boot应用程序运行,但我在Web浏览器中收到404错误,对于前端我使用了jsp。该应用程序是在 spring mvc 中开发的,然后我将其转换为 spring boot。转换后按预期运行,但我在浏览器中看不到数据。 “此应用程序没有/error 的显式映射,因此您将其视为后备。 2020 年 5 月 28 日星期四 18:07:37 GMT-06:00 出现意外错误(类型=未找到,状态=404)。 无可用消息”
我有一个 WebMvcConfigurer 类,它包含我的 View 解析器,我需要它吗? Thymeleaf 不需要 View Reslover,jps 也一样吗? 这是我的类(class):
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import thursday.com.todolist.util.ViewNames;
public class WebConfig implements WebMvcConfigurer {
private static final String RESOLVER_PREFIX = "/templates/WEB-INF/view/";
private static final String RESOLVER_SUFFIX = ".jsp";
@Bean
public ViewResolver viewResolver(){
UrlBasedViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix(RESOLVER_PREFIX);
viewResolver.setSuffix(RESOLVER_SUFFIX);
return viewResolver;
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName(ViewNames.HOME);
}
}
最佳答案
是的,您确实需要 View 解析器的后缀和前缀,因为内部 View 解析器使用前缀和后缀为您的 View 进行逻辑映射,但您也可以在 application.properties
文件如下:
spring.mvc.view.prefix = /WEB-INF/classes/templates
spring.mvc.view.suffix = .jsp
另外,嵌入式Tomcat包(在springboot中用于创建可执行jar)默认不包含JSP,我们必须添加模块“org.apache.tomcat.embed:tomcat-embed-jasper
”作为依赖项。我们在 springboot 中添加 tomcat-embed-jasper 作为依赖项的原因是我们可以在 jsp 中使用 jSTL 标签。jsp 文件需要转换为 html。
- 此外,由于您从 spring mvc 迁移到 spring-boot,请确保您
从您的项目中删除了注释
@EnableWebMvc
,因为这将 禁用所有 spring-boot 自动配置。除非您自己明确提供它来手动处理所有配置,就像在 spring-mvc 中一样。 - 此外,spring-boot 和 JSP 无法与
jar
作为打包一起使用,因此如果您使用 jsp 作为 View 模板,请尝试使用war
打包。如果您将打包保留为war
,则仅会在构建期间自动占用 webapp 文件夹的内容。
关于java - spring boot 应用程序运行,但我在网络浏览器中收到错误 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62076662/