码迷,mamicode.com
首页 > Web开发 > 详细

jsonview注解、RequestBody 、拦截

时间:2020-01-27 15:27:17      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:art   密码   springmvc   isp   for   etc   uil   set   dir   

@JsonView使用

  • 使用接口来声明多个视图
  • 在值对象的get方法上指定视图
  • 在Controller方法上指定视图
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验证请求参数的合法性并处理校验结果

参考import javax.validation.constraints

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());
        }
    }

拦截

  • 过滤器Filter

    使用@Component

    @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");
        }
    }
    

    不使用@Component

    @Configuration
    public class WebConfig {
        @Bean
        public FilterRegistrationBean timeFilter(){
            FilterRegistrationBean registrationBean = new FilterRegistrationBean();
            TimeFilter timeFilter = new TimeFilter();
            registrationBean.setFilter(timeFilter);
            List<String> urls = new ArrayList<>();
            urls.add("/*");//所有请求
            registrationBean.setUrlPatterns(urls);
            return registrationBean;
    
        }
    }
  • 拦截器Interceptor

    会拦截所有请求,包括spring本身的处理

    可以拿到方法但没法拿到参数值

    @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

    @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);
    }

jsonview注解、RequestBody 、拦截

标签:art   密码   springmvc   isp   for   etc   uil   set   dir   

原文地址:https://www.cnblogs.com/fly-book/p/12236069.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!