1.Spring MVC中接收请求参数
Spring MVC框架支持在设计URL时,使用{名称}格式的占位符,实际处理请求时,此占位符位置是任意值都可以匹配得到!
例如,将URL设计为:
@RequestMapping("/delete/{id}")
在处理请求的方法的参数列表中,用于接收占位符的参数,需要添加@PathVariable注解,例如:
public String delete(@PathVariable Long id) {
// 暂不关心方法内部的实现
}
如果{}占位符中的名称,与处理请求的方法的参数名称不匹配,则需要在@PathVariable注解上配置占位符中的名称,例如:
@RequestMapping("/delete/{albumId}")
public String delete(@PathVariable("albumId") Long id) {
// 暂不关心方法内部的实现
}
在配置占位符时,可以在占位符名称的右侧,可以添加冒号,再加上正则表达式,对占位符的值的格式进行限制,例如:
@RequestMapping("/delete/{id:[0-9]+}")
如果按照以上配置,仅当占位符位置的值是纯数字才可以匹配到此URL!
并且,多个不冲突有正则表达式的占位符配置的URL是可以共存的!例如:
@RequestMapping("/delete/{id:[a-z]+}")
以上表示的是“占位符的值是纯字母的”,是可以与以上“占位符的值是纯数字的”共存!
另外,某个URL的设计没有使用占位符,与使用了占位符的,是允许共存的!例如:
@RequestMapping("/delete/test")
Spring MVC会优先匹配没有使用占位符的URL,再尝试匹配使用了占位符的URL。
2.SpringMVC响应结果去空值
Spring MVC框架会将方法返回的JsonResult对象转换成JSON格式的字符串,通常,不需要在JSON结果中包含为null的属性,所以,可以在application.properties / application.yml中进行配置
application.properties配置示例
# JSON结果中将不包含为null的属性
spring.jackson.default-property-inclusion=non_nul
application.yml配置示例
# Spring相关配置
spring:
# Jackson框架相关配置
jackson:
# JSON结果中是否包含为null的属性的默认配置
default-property-inclusion: non_null
3.跨域访问
根包下创建config.WebMvcConfiguration类,实现WebMvcConfigurer接口,添加@Configuration注解,并重写方法配置允许跨域访问
package cn.tedu.csmall.product.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Spring MVC的配置类
*
* @author java@tedu.cn
* @version 0.0.1
*/
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
public WebMvcConfiguration() {
System.out.println("创建配置类:WebMvcConfiguration");
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}