SpringBoot静态资源访问、全局异常、跨域

本文介绍了如何在Spring Boot项目中将静态资源(如HTML文件)部署在static目录,并配置jsp支持,包括Multipart配置、视图解析器设置和跨域支持。展示了完整的POM配置及关键代码段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

静态资源访问

官方推荐尽量不要放在webapp中,尽量放在static中。
• 现在在resouces中新建一个文件夹static/html/test.html
• 然后写一个配置类,代码如下

@Configuration
@EnableWebMvc //有的版本需要去掉这个@EnableWebMvc注解
public class SpringWebMvcConfigurer implements WebMvcConfigurer {
	
	@Bean
	public CommonsMultipartResolver commonsMultipartResolver() {
		
		CommonsMultipartResolver c = new CommonsMultipartResolver();
		c.setMaxUploadSize(1024000000);
		c.setMaxInMemorySize(2048000);
		c.setDefaultEncoding("utf-8");
		return c;
	}
	
	@Bean
	public ViewResolver viewResolver() {
		//配置视图解析器
		InternalResourceViewResolver i = new InternalResourceViewResolver();
		i.setSuffix(".html");
		i.setPrefix("/static/");
		i.setExposeContextBeansAsAttributes(true);
		i.setCache(true);
		return i;
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry arg0) {
		// TODO Auto-generated method stub
		arg0.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");

	}
}
  • 再写一个action类
@RestController
public class HelloAction {

    @RequestMapping(value="test5", method= RequestMethod.GET)
    public ModelAndView test5(){
        ModelAndView mv = new ModelAndView("/html/test");
        return mv;
    }
}

运行起来即可访问。
然后给出pom的打包配置

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.2.6.RELEASE</version>
                <configuration>
                    <mainClass>com.work.server.Main</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
       <resources>
        </resources>
    </build>

这样就搞定了

springboot jsp配置

还是有一些古老的页面需要使用jsp,有时就是为了重构以往的代码,拷贝方便,这里给出springboot配置jsp的方案。

  • 先配置pom.xml
 <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>

        <!-- tomcat 依赖包 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <!--<scope>provided</scope>-->
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <!--<scope>provided</scope>-->
        </dependency>

        <!-- servlet 依赖包 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <!--<scope>provided</scope>-->
        </dependency>
        <!-- JSTL (JSP standard Tag Library) JSP 标准标签库 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>


    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.4.2.RELEASE</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/**</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/**</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/webapp</directory>
                <includes>
                    <include>**/**</include>
                </includes>
                <targetPath>META-INF/resources</targetPath>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
  • 配置yml
spring:
  mvc:
    view:
      prefix: /WEB-INF/jsp/
      suffix: .jsp
  • 然后新建一个action类
@Controller
public class IndexAction {

    @RequestMapping("/")
    public String index() {
        return "index";
    }
}

可以了!

全局异常处理

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonResult error(Exception e) {
        e.printStackTrace();
        return CommonResult.fail(e.getMessage());
    }
    
    @ExceptionHandler(CustomException.class)
    String handleCustomException(HttpServletRequest request, CustomException ex) {
        request.setAttribute(ErrorAttributes.ERROR_ATTRIBUTE, ex);
        return "errorView";
    }

}

跨越支持

@Configuration(proxyBeanMethods = false)
public class MyCorsConfiguration {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**");
            }

        };
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值