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";
? ? }
}
對于配置,創(chuàng)建 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;
? ? }
}
添加回答
舉報