3 回答
TA贡献1805条经验 获得超10个赞
从 application.properties 文件中删除这两行
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
并从资源包中删除模板文件夹。
然后将此类添加到您的 com.example.demo 包中。
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages= {"com.example"})
public class WebConfig implements WebMvcConfigurer {
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp().prefix("/WEB-INF/views/").suffix(".jsp");
}
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
在控制器中使用:
@Controller not @RestController
喜欢:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class TestController {
@RequestMapping(value = "/showHome", method = RequestMethod.GET)
public String homePage() {
return "index";
}
}
TA贡献1836条经验 获得超5个赞
必须更改我的 pom.xml 文件依赖项,将 tomcat-embed 和 javax.servelet 导入到
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>8.5.20</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
TA贡献2037条经验 获得超6个赞
如果你想返回jsp文件,你应该使用@Controller。@RestController 返回一个字符串
@Controller
public class HomeController {
@RequestMapping("/showHome")
public String homePage(){
return "index";
}
}
对于配置,创建 WebConfig.java 文件并写入以下内容:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {
"com.example.demo"
})
public class WebConfig implements WebMvcConfigurer {
@Bean
public InternalResourceViewResolver getInternalResourceViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
添加回答
举报