jsonview注解、RequestBody 、拦截
2021-04-24 05:28
标签:art 密码 springmvc isp for etc uil set dir 测试 参考import javax.validation.constraints 过滤器Filter 使用@Component 不使用@Component 拦截器Interceptor 会拦截所有请求,包括spring本身的处理 可以拿到方法但没法拿到参数值 切片Aspect jsonview注解、RequestBody 、拦截 标签:art 密码 springmvc isp for etc uil set dir 原文地址:https://www.cnblogs.com/fly-book/p/12236069.html@JsonView使用
public interface UserDetailView extends UserSimpleView {
}
public interface UserSimpleView {}
public class User {
private String username;
private String password;
private int age;
public User() {
}
public User(String username, String password, int age) {
this.username = username;
this.password = password;
this.age = age;
}
@JsonView(UserSimpleView.class)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@JsonView(UserDetailView.class)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
@RestController
@SpringBootApplication
public class UserController {
@JsonView(UserDetailView.class)
@GetMapping("/userdetail")
public User userDetail(){
return new User("tom","123",22);
}
@JsonView(UserSimpleView.class)
@GetMapping("/user")
public User user(){
return new User("tom","123",22);
}
public static void main(String[] args) {
SpringApplication.run(UserController.class);
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(classes = UserController.class)
public class UserTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setUp(){
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void test() throws Exception {
String res = mockMvc.perform(get("/userdetail")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
System.out.println(res);
}
@Test
public void test2() throws Exception {
String res = mockMvc.perform(get("/user")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
System.out.println(res);
}
}
@RequestBody 映射请求体到java方法的参数
@PostMapping
public void create(@RequestBody User user){
System.out.println(user.toString());
}
@Test
public void test3() throws Exception {
String user = "{\"username\":\"tom\",\"password\":\"null\"}";
mockMvc.perform(post("/user").contentType(MediaType.APPLICATION_JSON_UTF8).content(user))
.andExpect(status().isOk());
}
@Valid注解和BindingResult验证请求参数的合法性并处理校验结果
public class User {
private String username;
@NotNull(message = "密码不能为空")
private String password;
@PostMapping
public void create(@Valid @RequestBody User user, BindingResult errors){
if (errors.hasErrors()){
errors.getAllErrors().forEach(e->{
FieldError fieldError = (FieldError) e;
String msg = fieldError.getField() + " " + fieldError.getDefaultMessage();
System.out.println(msg);
});
}else {
System.out.println(user.toString());
}
}
拦截
@Component
public class TimeFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("TimeFilter init");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("TimeFilter start");
long start = new Date().getTime();
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("耗时:"+(new Date().getTime()-start));
System.out.println("TimeFilter end");
}
@Override
public void destroy() {
System.out.println("TimeFilter destroy");
}
}
@Configuration
public class WebConfig {
@Bean
public FilterRegistrationBean timeFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
TimeFilter timeFilter = new TimeFilter();
registrationBean.setFilter(timeFilter);
List
@Component
public class TimeInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("TimeInterceptor preHandle");
request.setAttribute("time",new Date().getTime());
HandlerMethod handlerMethod = (HandlerMethod)handler;
System.out.println(handlerMethod.getBean().getClass().getName());
System.out.println(handlerMethod.getMethod().getName());
return true;
}
//成功后执行
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("TimeInterceptor postHandle");
System.out.println("耗时:"+(new Date().getTime()-(Long) request.getAttribute("time")));
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("TimeInterceptor afterCompletion");
System.out.println("耗时:"+(new Date().getTime()-(Long) request.getAttribute("time")));
System.out.println("ex:"+ex);
}
}
@Configuration
public class WebConfig2 extends WebMvcConfigurationSupport {
@SuppressWarnings("unused")
@Autowired
private TimeInterceptor interceptor;
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(interceptor);
}
}
@Aspect
@Component
public class TimeAspect {
@Pointcut("execution(* com.app.controller..*(..))")
private void controller(){}
//在类名模式串中,“.”表示包下的所有类,而“..”表示包、子孙包下的所有类
@Around("controller()")
public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("TimeAspect start");
Object[] args = pjp.getArgs();
for (Object arg : args) {
System.out.println(arg);
}
long start = new Date().getTime();
Object proceed = pjp.proceed();
System.out.println("耗时:"+(new Date().getTime()-start));
System.out.println("TimeAspect end");
return proceed;
}
}
文件上传下载
@PostMapping("/upload")
public String fileUpload(MultipartFile file, HttpServletRequest request) throws Exception {
try {
String dir = request.getServletContext().getRealPath("/files");
File fileDir = new File(dir);
if (!fileDir.exists())
fileDir.mkdirs();
System.out.println(file.getName());
System.out.println(file.getOriginalFilename());
System.out.println(file.getSize());
String fileSuffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
File localFile = new File(fileDir, new Date().getTime() + fileSuffix);
file.transferTo(localFile);
return localFile.getAbsolutePath();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
@GetMapping("{id}")
public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
String dir = ResourceUtils.getURL("").getPath()+"springmvcDemo/src/main/webapp/files";
System.out.println(dir);
try (
InputStream inputStream = new FileInputStream(new File(dir, id + ".txt"));
OutputStream outputStream = response.getOutputStream()
) {
response.setContentType("application/x-download");
response.addHeader("Content-Disposition", "attachment;filename=test.txt");
IOUtils.copy(inputStream, outputStream);
outputStream.flush();
}
}
@Test
public void uploadSuccess() throws Exception {
String result = mockMvc.perform(fileUpload("/upload")
.file(new MockMultipartFile("file", "test.txt", "multipart/form-data", "hello upload".getBytes(StandardCharsets.UTF_8))))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}