tParameter(paramName);
System.out.println(paramName+":"+paramValue);
}
// 放开拦截
return true;
}
@Override
public void postHandle(HttpServletRequest request,HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
log.info("BodyInterceptor:postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request,HttpServletResponse response,
Object handler, Exception e) throws Exception {
log.info("BodyInterceptor:afterCompletion");
}
}
2、拦截器配置
自定义拦截器之后,还需要添加到web工程的配置文件中,可以通过实现WebMvcConfigurer
接口,完成自定义的配置添加;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 添加自定义拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HeadInterceptor()).addPathPatterns("/**");
registry.addInterceptor(new BodyInterceptor()).addPathPatterns("/**");
}
}
五、测试工具
1、Swagger接口
添加上述的springdoc
依赖之后,还可以在配置文件中简单定义一些信息,访问IP:端口/swagger-ui/index.html
即可;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 接口文档配置
*/
@Bean
public OpenAPI openAPI() {
return new OpenAPI()
.info(new Info().title("【boot-web】").description("Rest接口文档-2023-07-11")
.version("1.0.0"));
}
}
2、Junit测试
在个人的习惯上,Swagger
接口文档更偏向在前后端对接的时候使用,而Junit
单元测试更符合开发的时候使用,这里是对RestWeb
中的接口进行测试;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class RestWebTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testGet () throws Exception {
// GET接口测试
MvcResult mvcResult = mockMvc
.perform(MockMvcRequestBuilders.get("/rest/get/1"))
.andReturn();
printMvcResult(mvcResult);
}
@Test
public void testPost () throws Exception {
// 参数模型
JsonMapper jsonMapper = new JsonMapper();
ParamBO param = new ParamBO(null,"单元测试",new Date()) ;
String paramJson = jsonMapper.writeva lueAsString(param) ;
// Post接口测试
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/rest/post")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON).content(paramJson)).andReturn();
printMvcResult(mvcResult);
}
@Test
public void testPut () throws Exception {
// 参数模型
JsonMapper jsonMapper = new JsonMapper();
ParamBO param = new ParamBO(7,"Junit组件",new Date()) ;
String paramJson = jsonMapper.writeva lueAsString(param) ;
// Put接口测试
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.put("/rest/put")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON).content(paramJson)).andReturn();
printMvcResult(mvcResult);
}
@Test
public void testDelete () throws Exception {
// Delete接口测试
MvcResult mvcResult = mockMvc
.perform(MockMvcRequestBuilders.delete("/rest/delete/2"))
.andReturn();
printMvcResult(mvcResult);
}
/**
* 打印【MvcResult】信息
*/
private void printMvcResult (MvcResult mvcResult) throws Exception {
System.out.println("请求-URI【"+mvcResult.getRequest().getRequestURI()+"】");
System.out.println("响应-status【"+mvcResult.getResponse().getStatus()+"】");
System.out.println("响应-content【