zoukankan      html  css  js  c++  java
  • Spring Security构建Rest服务-0200-搭建项目

    一、代码结构:

    二、使用Springmvc开发restful API

    传统url和rest区别:

    三、写代码

    1,编写RestfulAPI的测试用例:使用MockMvc伪造mvc

    package com.imooc.web.controller;
    
    import java.time.LocalDateTime;
    import java.time.ZoneId;
    import java.util.Date;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.http.MediaType;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
    import org.springframework.test.web.servlet.setup.MockMvcBuilders;
    import org.springframework.web.context.WebApplicationContext;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class UserControllerTest {
    
        @Autowired
        private WebApplicationContext webCtx;
        
        //伪造mvc
        private MockMvc mockMvc;
        
        @Before
        public void setup(){
            mockMvc = MockMvcBuilders.webAppContextSetup(webCtx).build();
        }
        
        /**
         * 查询
         */
        @Test
        public void whenQuerySuccess() throws Exception{
            String result = mockMvc.perform(MockMvcRequestBuilders.get("/user") //路径
                    .param("page", "10")   //参数
                    .param("size", "12")
                    .param("sort", "age,desc")
                    .param("username", "xiaoming") 
                    .param("age", "18")
                    .param("ageTo", "40")
                    .param("other", "otherProperty")
                    .contentType(MediaType.APPLICATION_JSON_UTF8))
                    .andExpect(MockMvcResultMatchers.status().isOk()) //状态码200
                    .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3))//长度为3,具体查看github的jsonPath项目    
                    .andReturn().getResponse().getContentAsString();
            System.err.println(result);
        }
        
        /**
         * 详情
         */
        @Test
        public void whenGetInfoSuccess() throws Exception{
            String result = mockMvc.perform(MockMvcRequestBuilders.get("/user/1")
                    .contentType(MediaType.APPLICATION_JSON_UTF8))
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    .andExpect(MockMvcResultMatchers.jsonPath("$.username").value("tom"))
                    .andReturn().getResponse().getContentAsString();
            System.err.println(result);
        }
        
        /**
         * 详情失败
         */
        @Test
        public void whenGetInfoFail() throws Exception{
            mockMvc.perform(MockMvcRequestBuilders.get("/user/a") //匹配正则
                    .contentType(MediaType.APPLICATION_JSON_UTF8))
                    .andExpect(MockMvcResultMatchers.status().is4xxClientError());
        }
        
        @Test
        public void whenCreateSuccess() throws Exception{
            long date = new Date().getTime();
            System.err.println(">>>>>>>>"+date);
            String content = "{"username":"tom","password":null,"birthday":"+date+"}";
             String result = mockMvc.perform(MockMvcRequestBuilders.post("/user")
                     .contentType(MediaType.APPLICATION_JSON_UTF8)
                     .content(content))
                      .andExpect(MockMvcResultMatchers.status().isOk())
                      .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1"))
                      .andReturn().getResponse().getContentAsString();
             System.err.println(result);
        }
        
        @Test
        public void whenUpdateSuccess() throws Exception{
            //jdk8新增,当前日期加一年,测试生日@past注解
            Date date = new Date(LocalDateTime.now().plusYears(1).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
            System.err.println(">>>>>>>>"+date);
            String content = "{"id":"1","username":"tom","password":null,"birthday":"+date.getTime()+"}";
             String result = mockMvc.perform(MockMvcRequestBuilders.put("/user/1") //put
                     .contentType(MediaType.APPLICATION_JSON_UTF8)
                     .content(content))
                      .andExpect(MockMvcResultMatchers.status().isOk())
                      .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1"))
                      .andReturn().getResponse().getContentAsString();
             System.err.println("update result>>>>> "+result);
        }
        
        @Test
        public void whenDeleteSuccess() throws Exception {
            mockMvc.perform(MockMvcRequestBuilders.delete("/user/1")
                    .contentType(MediaType.APPLICATION_JSON_UTF8))
                    .andExpect(MockMvcResultMatchers.status().isOk());
        }
        
    }

    Controller:使用注解声明RestfulAPI

    package com.imooc.web.controller;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.validation.Valid;
    
    import org.springframework.data.domain.Pageable;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.annotation.DeleteMapping;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.PutMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.fasterxml.jackson.annotation.JsonView;
    import com.imooc.dto.User;
    import com.imooc.dto.UserQueryCondition;
    
    @RestController
    @RequestMapping("/user")
    public class UserController {
        
        /**
         * @Description: 条件查询
         * @param @param condition
         * @param @param pageable
         * @param @return   
         * @return List<User>  
         * @throws
         * @author lihaoyang
         * @date 2018年2月24日
         */
        @GetMapping()
        @JsonView(User.UserSimpleView.class)
        public List<User> query(
                //@RequestParam(value="username",required=false,defaultValue="lhy") String username
                UserQueryCondition condition , Pageable pageable){
    //        System.err.println(username);
            System.err.println(condition.toString());
            System.err.println(pageable.toString());
            
            List<User> users = new ArrayList<User>();
            users.add(new User());
            users.add(new User());
            users.add(new User());
            return users;
        }
        
        /**
         * 详情
         * @Description: TODO
         * @param @param id
         * @param @return   
         * @return User  
         * @throws
         * @author lihaoyang
         * @date 2018年2月24日
         */
        @GetMapping("{id:\d+}") //{}里可以是正则,匹配数字
    //    @GetMapping("detail/{id}")
        @JsonView(User.UserDetailView.class)
        public User getInfo(@PathVariable(value="id",required=true) String id){
            System.err.println(id);
            User user = new User();
            user.setUsername("tom");
            user.setPassword("123456");
            user.setId("1");
            return user;
        }
        
        /**
         * 创建
         * @Description: 
         * //@RequestBody:json映射到java
         *     @Valid 和User类上的@NotBlank注解一起做校验
         *  BindingResult存储的是校验错误信息
         * @param @param user
         * @param @return   
         * @return User  
         * @throws
         * @author lihaoyang
         * @date 2018年2月24日
         */
        @PostMapping
        public User create(@Valid @RequestBody User user,BindingResult errors){
            
            if(errors.hasErrors()){
                errors.getAllErrors().stream()
                .forEach(error -> System.err.println(error.getDefaultMessage()));
            }
            
            user.setId("1");
            System.err.println(user);
            return user;
        }
        
        @PutMapping("/{id:\d+}")
        public User update(@Valid @RequestBody User user,BindingResult errors){
    
            if(errors.hasErrors()){
                errors.getAllErrors().stream()
                .forEach(error -> System.err.println(error.getDefaultMessage()));
            }
            System.err.println(user);
            return user;
        }
        
        @DeleteMapping("/{id:\d+}")
        public void delete(@PathVariable String id){
            System.err.println("delete method id is >>>>>>>"+id);
        }
    
    }

    到这里只是说了RestfulAPI增删改查的做法,使用查询使用@GetMapping()、新增使用@PostMapping、修改使用@PutMapping、删除使用@DeleteMapping。restful是根据响应的状态码确定接口调用是否成功的。

    完整代码放在了github:https://github.com/lhy1234/spring-security

  • 相关阅读:
    html5 返回当前地理位置的坐标点(经纬度)
    C#趣味程序---百鸡百钱
    Android开发:怎样隐藏自己的app应用
    Android Studio一些简单设置
    集群通信组件tribes之集群的消息接收通道
    Java基础实例
    如何用webbrowser获取ajax动态生成的网页的源码?
    phantomjs 下拉滚动条获取网页的全部源码
    Nodejs+定时截图+发送邮件
    关注网页的更新状况,了解最新的handsup 消息.
  • 原文地址:https://www.cnblogs.com/lihaoyang/p/8466647.html
Copyright © 2011-2022 走看看