SpringBoot 集成jsp并通过controller访问时出现的问题

这里的前提是在src/main/目录下(跟src/main/resources同级)建好了webapp目录,并且在webapp下建好了WEB-INF。如图
在这里插入图片描述

问题一:Could not resolve view with name ‘xxx’ in servlet with name ‘dispatcherServlet’

出现这个的时候可能是因为没有进行MVC配置,在application.properties里面进行如下配置
在这里插入图片描述

spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp

重启运行,访问后还是不行的话,在springboot的启动类(xxxApplication)添加
在这里插入图片描述

	@Bean
	public InternalResourceViewResolver setupViewResolver (){
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setPrefix("/WEB-INF/view/");
		resolver.setSuffix(".jsp");
		return resolver;
	}

重启访问,如果出现 Path with “WEB-INF” or “META-INF”: [WEB-INF/view/userList.jsp]类似的问题,请看问题二。

参考:https://blog.csdn.net/qq_35872777/article/details/82871565

问题二、Path with “WEB-INF” or “META-INF”: [WEB-INF/view/userList.jsp]

出现这个问题是因为没有加jsp支持,在pom.xml那里添加支持就可以:
在这里插入图片描述

	<!--jsp页面使用jstl标签 -->
		<dependency>
		    <groupId>javax.servlet</groupId>
		    <artifactId>jstl</artifactId>
		</dependency>
		 
		<!--用于编译jsp -->
		<dependency>
		    <groupId>org.apache.tomcat.embed</groupId>
		    <artifactId>tomcat-embed-jasper</artifactId>
		    <scope>provided</scope>
		</dependency>

这里要提一下的是,建议使用jsp,如果使用html的话出现Path with “WEB-INF” or “META-INF”: [WEB-INF/view/userList.html]的时候加jsp支持也没用,网上说是对此拦截了,我觉得应该是spring并没有将其加载到容器里面导致的,具体不深究了。

这么配置了以后你的css、js等静态文件要放在src/main/resources/static下面才会访问得到,放在webapp下面发现并不能访问到。想要在webapp下面能访问到,请转到:https://blog.csdn.net/xiaoxiao48/article/details/107838687

补充一下:如果静态文件要放在src/main/resources/static下面也访问不到,解决:
新建一个加载配置的类,继承WebMvcConfigurationSupport,然后重写addResourceHandlers,这里我就直接在跨域配置的类里面进行设置:

@Configuration
public class CorsConfig extends WebMvcConfigurationSupport{
	/**
	 * 加载静态资源
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		//加载classpath等静态资源,用于访问swagger,以及webapp下的静态资源
		registry.addResourceHandler("/**")
				.addResourceLocations("classpath:/META-INF/resources/");
		//加上file:静态资源,用于访问本地图片
		//images/**和file:E://images/对应application.properties上面的配置
		registry.addResourceHandler("/images/**").addResourceLocations("file:E://PDF/");
		 
		super.addResourceHandlers(registry);
	}
	
	/**
	 * 允许跨域
	 */
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**")
				.allowedOrigins("*")
				.allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH")
				.allowCredentials(true).maxAge(3600);
	}
	
	
}

重点是registry.addResourceHandler("/**").addResourceLocations(“classpath:/META-INF/resources/”);
更够访问到resources里面的资源文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值