GVKun编程网logo

Spring RESTful控制器方法改进建议(spring restcontroller)

24

本文将分享SpringRESTful控制器方法改进建议的详细内容,并且还将对springrestcontroller进行详尽解释,此外,我们还将为大家带来关于asp.net-mvc–具有不同Http方

本文将分享Spring RESTful控制器方法改进建议的详细内容,并且还将对spring restcontroller进行详尽解释,此外,我们还将为大家带来关于asp.net-mvc – 具有不同Http方法的RESTful控制器,但是相同的参数、java – 单元测试Spring RESTful控制器时“内容类型未设置”、java – 如何在Spring 3中使用注释配置RESTful控制器?、JavaWeb-RESTful(三)_使用SpringMVC开发RESTful_下的相关知识,希望对你有所帮助。

本文目录一览:

Spring RESTful控制器方法改进建议(spring restcontroller)

Spring RESTful控制器方法改进建议(spring restcontroller)

我是Spring,REST和Hibernate的新手。就是说,我试图将一种企业级控制器方法组合在一起,我打算将其用作未来开发的一种模式。

您如何看待可以改善这一点?我敢肯定有很多。

@RequestMapping(value = "/user", method = RequestMethod.GET)    public @ResponseBody User getUser(@RequestParam(value="id", required=true) int id) {        Session session = null;        User user = null;        try {            HibernateUtil.configureSessionFactory();            session = HibernateUtil.getSessionFactory().getCurrentSession();                        session.beginTransaction();                     user = (User) session.get(User.class, id);            session.getTransaction().commit();        } catch (HibernateException e) {                if (session != null) {                session.getTransaction().rollback();            }            e.printStackTrace();            throw new ServerErrorException();        }        if (user == null) {            throw new ResourceNotFoundException();        }        return user;    }

例外:

ServerErrorException uses Spring''s annotations to throw an HTTP 500, and the ResourceNotFoundException does the same with a 404.

谢谢,谢谢您的投入。

答案1

小编典典

建议的改进:

  • a)使用JPA代替普通的Hibernate
  • b)让Spring注入Hibernate Session / JPA实体管理器
  • c)让Spring做数据库处理(注解(@Transactional)或程序化(TransactionTemplate))

asp.net-mvc – 具有不同Http方法的RESTful控制器,但是相同的参数

asp.net-mvc – 具有不同Http方法的RESTful控制器,但是相同的参数

假设我有一个Controller来处理’Home’的CRUD场景. Get会看起来像这样:

[HttpGet]
    public ActionResult Index(int? homeId)
    {
        Home home = homeRepo.GetHome(homeId.Value);

        return Json(home,JsonRequestBehavior.AllowGet);
    }

到现在为止还挺好.然后我添加了一个用于添加新帖子的帖子操作.

[HttpPost]
    public ActionResult Index(Home home)
    {
        //add the new home to the db

        return Json(new { success = true });
    }

真棒.但是,当我使用相同的方案处理put(更新现有的家)时……

[HttpPut]
    public ActionResult Index(Home home)
    {
        //update existing home in the db

        return Json(new { success = true });
    }

我们遇到了一个问题. Post和Put的方法签名是相同的,当然C#不喜欢.我可以尝试一些方法,比如在签名中添加伪参数,或者更改方法名称以直接反映CRUD.但这些都是黑客或不受欢迎的.

在这里开始保存RESTful,CRUD样式控制器的最佳实践是什么?

解决方法

这是我所知道的最佳解决方案:

[HttpPut]
[ActionName("Index")]
public ActionResult IndexPut(Home home) 
{
     ...
}

基本上,ActionNameAttribute是为了处理这些场景而创建的.

java – 单元测试Spring RESTful控制器时“内容类型未设置”

java – 单元测试Spring RESTful控制器时“内容类型未设置”

我有一个类似于这个的Rest控制器:

@RestController
public class UserRestController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/user/activate",method = RequestMethod.POST)
    public ResponseEntityrequired = true) final String email,@RequestParam(required = true) final String key) {

        UserDTO userDTO = userService.activateAccount(email,key);
        return new ResponseEntity

当我使用Postman调用它并且我不发送’key’参数时,我收到此JSON消息:

{
    "timestamp": 1446211575193,"status": 400,"error": "Bad Request","exception": "org.springframework.web.bind.MissingServletRequestParameterException","message": "required String parameter 'key' is not present","path": "/user/activate"
}

另一方面,我正在使用JUnit和mockmvc Spring实用程序测试此方法.

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ApplicationConfig.class)
@WebAppConfiguration
public class UserRestControllerTest {

    private static mockmvc mockmvc;

    @Mock
    private UserService userService;

    @InjectMocks
    private UserRestController userRestController;

    @Before
    public void setup() {

        MockitoAnnotations.initMocks(this);
        mockmvc = mockmvcBuilders
                .standalonesetup(userRestController)
                .setMessageConverters(
                        new MappingJackson2HttpMessageConverter(),new Jaxb2RootElementHttpMessageConverter()).build();

    }

    @Test
    public void testActivaterequiredParams() throws Exception {

        mockmvc.perform(
                mockmvcRequestBuilders.post("/user/activate")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .accept(MediaType.APPLICATION_JSON))
                .andDo(mockmvcResultHandlers.print())
                .andExpect(mockmvcResultMatchers.status().isBadRequest())
                .andExpect(
                        mockmvcResultMatchers.content().contentType(
                                UtilsUnitTest.APPLICATION_JSON_UTF8))
                .andExpect(
                        jsonPath(
                                "message",is("required String parameter 'email' is not present")));

     }
}

但是当我执行此测试时,我注意到响应不是JSON消息.事实上,我得到一个例外:

java.lang.AssertionError: Content type not set

特别是,完成的结果是

MockHttpServletRequest:
         HTTP Method = POST
         Request URI = /user/activate
          Parameters = {}
             Headers = {Content-Type=[application/x-www-form-urlencoded]}

             Handler:
                Type = com.company.controller.UserRestController
              Method = public org.springframework.http.ResponseEntityjava.lang.String)

               Async:
       Async started = false
        Async result = null

  Resolved Exception:
                Type = org.springframework.web.bind.MissingServletRequestParameterException

        ModelAndView:
           View name = null
                View = null
               Model = null

            FlashMap:

MockHttpServletResponse:
              Status = 400
       Error message = required String parameter 'email' is not present
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = null
      Redirected URL = null
             Cookies = []

我推断当抛出异常时,这不会转换为JSON格式(当我发送电子邮件和关键参数时,我得到了正确的JSON结果)

问题很明显:如果抛出异常,我应该在单元测试配置中更改什么来获取JSON错误消息?

最佳答案
问题是在断言失败后测试停止:

.andExpect(mockmvcResultMatchers.content().contentType(UtilsUnitTest.APPLICATION_JSON_UTF8))

除此之外,jsonPath(“message”…不会点击任何内容.要验证返回的错误消息,请使用mockmvcResultMatchers.status().reason(< ResultMatcher>).

以下测试应该完成这项工作:

@Test
public void testActivaterequiredParams() throws Exception {
    final ResultActions result = mockmvc
            .perform(mockmvcRequestBuilders.post("/user/activate")
                    .contentType(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON))
            .andDo(mockmvcResultHandlers.print());
    result.andExpect(mockmvcResultMatchers.status().isBadRequest());
    result.andExpect(mockmvcResultMatchers.status().reason(is("required String parameter 'email' is not present")));
}

但是考虑一下这个(测试错误信息)是不是一个好主意,也许看看this discussion.

java – 如何在Spring 3中使用注释配置RESTful控制器?

java – 如何在Spring 3中使用注释配置RESTful控制器?

我正在尝试使用Spring 3.0创建一个RESTful控制器.控制器用于门户应用程序的管理API.我想要执行的操作是:

> GET / api /门户列出所有门户网站
> POST / api /门户创建新门户
> GET / api / portals / {id}来检索现有门户
> PUT / api / portals / {id}更新现有门户
> DELETE / api / portal / {id}删除现有门户

在如下图所示对控制器进行注释之后,我发现列出所有门户的操作或创建新的门户不会被映射.

所以我的问题是:

>我是否正确注释了课程?
>我是否遵循了实施RESTful Web服务的正确约定?
>春天可能会有什么东西坏掉吗?

下面的代码提取显示了我如何注释我的类:

@Controller
@RequestMapping("/api/portals")
public final class PortalAPIController
{
    private final static Logger LOGGER = LoggerFactory.getLogger(PortalAPIController.class);

    @RequestMapping(value = "/",method = RequestMethod.GET)
    public String listPortals(final Model model)
    {
         PortalAPIController.LOGGER.debug("Portal API: listPortals()");
         .
         .
         return "portals";
    }

    @RequestMapping(value = "/",method = RequestMethod.POST)
    public String createPortal(@RequestBody final MultiValueMap

在启动期间,我看到Spring注册了它们的终点:

2010-02-19 01:18:41,733 INFO [org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping] - Mapped URL path [/api/portals/] onto handler [com.btmatthews.mars.portal.web.controller.PortalAPIController@141717f]
2010-02-19 01:18:41,734 INFO [org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping] - Mapped URL path [/api/portals/{id}] onto handler [com.btmatthews.mars.portal.web.controller.PortalAPIController@141717f]
2010-02-19 01:18:41,734 INFO [org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping] - Mapped URL path [/api/portals/{id}.*] onto handler [com.btmatthews.mars.portal.web.controller.PortalAPIController@141717f]
2010-02-19 01:18:41,735 INFO [org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping] - Mapped URL path [/api/portals/{id}/] onto handler [com.btmatthews.mars.portal.web.controller.PortalAPIController@141717f]
2010-02-19 01:18:41,735 INFO [org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping] - Mapped URL path [/api/portals] onto handler [com.btmatthews.mars.portal.web.controller.PortalAPIController@141717f]
2010-02-19 01:18:41,735 INFO [org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping] - Mapped URL path [/api/portals.*] onto handler [com.btmatthews.mars.portal.web.controller.PortalAPIController@141717f]

但是当我尝试使用cURL调用我的API时

curl http://localhost:8080/com.btmatthews.minerva.portal/api/portals/

要么

curl http://localhost:8080/com.btmatthews.minerva.portal/api/portals

我收到以下错误:

2010-02-19 01:19:20,199 WARN [org.springframework.web.servlet.PageNotFound] - No mapping found for HTTP request with URI [/com.btmatthews.minerva.portal/api/portals] in dispatcherServlet with name 'portal'
2010-02-19 01:19:32,360 WARN [org.springframework.web.servlet.PageNotFound] - No mapping found for HTTP request with URI [/com.btmatthews.minerva.portal/api/portals/] in dispatcherServlet with name 'portal'

当我尝试创建时遇到同样的问题:

curl -F ...... --request POST http://localhost:8080/com.btmatthtews.minerva/api/portals

但是如果尝试对现有资源进行操作(检索,更新或删除),它就可以了.

更新:解决方案在@axtavt的评论中提供.我使用< url-pattern> / api / *< / url-pattern>在我的web.xml servlet映射中.需要将其更改为< url-pattern> /< / url-pattern>

最佳答案
仔细检查web.xml中的url-pattern并将其与curl参数进行比较.

我编写的Here is an example引导您完成整个Spring MVC过程.

JavaWeb-RESTful(三)_使用SpringMVC开发RESTful_下

JavaWeb-RESTful(三)_使用SpringMVC开发RESTful_下

 

 

  JavaWeb-RESTful(一)_RESTful初认识  传送门

  JavaWeb-RESTful(二)_使用SpringMVC开发RESTful_上  传送门

  JavaWeb-RESTful(三)_使用SpringMVC开发RESTful_下  传送门

  项目已上传至github  传送门

 

  Learn

    一、单元测试:添加用户

    二、单元测试:修改用户

    三、单元测试:删除用户

    四、SpringBoot默认处理异常路径

 

 

一、单元测试:添加用户

  在MainController.java中添加addUser()添加用户的单元测试方法

        @Test
        public void addUser() throws Exception
        {
            mockMvc.perform(MockMvcRequestBuilders.post("/user")
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .content("{\"username\":\"Gary\"}"))
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1"));
            
            
        }

 

  给User实体对象设置三个熟悉,id、username、password

private String username;
    private String password;
    private String id;

 

  通过id和username获得的试图都是简单试图,通过password获得的试图是复杂试图

@JsonView(UserSimpleView.class)
    public String getId() {
        return id;
    }

    @JsonView(UserSimpleView.class)
    public String getUsername() {
        return username;
    }

    @JsonView(UserDetailView.class)
    public String getPassword() {
        return password;
    }

 

  在UserController.java中通过addUser()方法获得MainController.java中的addUser()的POST请求

@RequestMapping(value="/user",method= RequestMethod.POST)
    public User addUser(@RequestBody User user)
    {
        //传输json格式的时候,一定要记得加上@RequestBody注解
        //输出 null
        System.out.println(user.getPassword());
        //输出 Gary
        System.out.println(user.getUsername());
        
        user.setId("1");
        return user;
    }

 

 

 

package com.Gary.GaryRESTful;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class GaryResTfulApplication {

    public static void main(String[] args) {
        SpringApplication.run(GaryResTfulApplication.class, args);
    }

}
GaryResTfulApplication.java

 

package com.Gary.GaryRESTful.controller;

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;



//这是SpringBoot测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class MainController {

        @Autowired
        private WebApplicationContext webApplicationContext;
            
        //SpringMV单元测试独立测试类
        private MockMvc mockMvc;
        
        
        @Before
        public void before()
        {
            //创建独立测试类
            mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        }
        
        
        //@Test
        //查询user
        public void test() throws Exception
        {
            //发起一个Get请求
            String str = mockMvc.perform(MockMvcRequestBuilders.get("/user")
                    .param("username", "Gary")
                        //json的形式发送一个请求
                        .contentType(MediaType.APPLICATION_JSON_UTF8))
                        //期望服务器返回什么(期望返回的状态码为200)
                        .andExpect(MockMvcResultMatchers.status().isOk())
                        //期望服务器返回json中的数组长度为3
                        .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3))
                        .andReturn().getResponse().getContentAsString();
            
            System.out.println("查询简单试图"+str);
        }
        
        //@Test
        public void getInfo() throws Exception
        {
            //发起一个get请求,查看用户详情
            String str = mockMvc.perform(MockMvcRequestBuilders.get("/user/1")
                    .contentType(MediaType.APPLICATION_JSON_UTF8))
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    .andExpect(MockMvcResultMatchers.jsonPath("$.username").value("Gary"))
                    .andReturn().getResponse().getContentAsString();
            
            System.out.println("查询复杂试图"+str);
                    
        }
        
        
        @Test
        public void addUser() throws Exception
        {
            mockMvc.perform(MockMvcRequestBuilders.post("/user")
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .content("{\"username\":\"Gary\"}"))
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1"));
            
            
        }
        
        
        
        
        
        
}
MainController.java

 

package com.Gary.GaryRESTful.controller;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.Gary.GaryRESTful.dto.User;
import com.fasterxml.jackson.annotation.JsonView;

//表示这个Controller提供R二十天API
@RestController
public class UserController {

    
    @RequestMapping(value="/user",method = RequestMethod.GET)
    /*
     * default value     默认
     * name             请求的名字
     * required            是否是必须的,true
     * value            别名
     * 
     * */
    @JsonView(User.UserSimpleView.class)
    public List<User> query(@RequestParam(name="username",required=false) String username)
    {
        System.out.println(username);
        //满足期望服务器返回json中的数组长度为3
        List<User> list = new ArrayList<>();
        list.add(new User());
        list.add(new User());
        list.add(new User());
        return list;
        
    }
    
    @RequestMapping(value="/user/{id}",method= RequestMethod.GET)
    //将@PathVariable路径中的片段映射到java代码中    
    @JsonView(User.UserDetailView.class)
    public User getInfo(@PathVariable String id)
    {
        User user = new User();
        user.setUsername("Gary");
        return user;
    }
    
    @RequestMapping(value="/user",method= RequestMethod.POST)
    public User addUser(@RequestBody User user)
    {
        //传输json格式的时候,一定要记得加上@RequestBody注解
        //输出 null
        System.out.println(user.getPassword());
        //输出 Gary
        System.out.println(user.getUsername());
        
        user.setId("1");
        return user;
    }
    
    
    
}
UserController.java

 

package com.Gary.GaryRESTful.dto;

import com.fasterxml.jackson.annotation.JsonView;

public class User {

    //简单试图 只有一个username
    public interface UserSimpleView{};
    //复杂试图 有username 和   password 
    public interface UserDetailView extends UserSimpleView{};

    private String username;
    private String password;
    private String id;
    
    @JsonView(UserSimpleView.class)
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    @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;
    }
    
}
User.java

 

 

二、单元测试:修改用户

  在MainController.java中添加updataUser()修改用户的单元测试方法

//修改用户
        @Test
        public void updataUser() throws Exception
        {
            mockMvc.perform(MockMvcRequestBuilders.put("/user/1")
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .content("{\"username\":\"Garyary\",\"id\":\"1\"}"))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1"));
            
        }

 

  在UserController.java中接收来自updataUser的请求

//修改用户资料
    @RequestMapping(value="/user/{id}",method = RequestMethod.PUT)
    public User updataUser(@RequestBody User user)
    {
        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        
        return user;
    }

 

 

 

package com.Gary.GaryRESTful;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class GaryResTfulApplication {

    public static void main(String[] args) {
        SpringApplication.run(GaryResTfulApplication.class, args);
    }

}
GaryResTfulApplication.java

 

package com.Gary.GaryRESTful.controller;

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;



//这是SpringBoot测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class MainController {

        @Autowired
        private WebApplicationContext webApplicationContext;
            
        //SpringMV单元测试独立测试类
        private MockMvc mockMvc;
        
        
        @Before
        public void before()
        {
            //创建独立测试类
            mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        }
        
        
        //@Test
        //查询user
        public void test() throws Exception
        {
            //发起一个Get请求
            String str = mockMvc.perform(MockMvcRequestBuilders.get("/user")
                    .param("username", "Gary")
                        //json的形式发送一个请求
                        .contentType(MediaType.APPLICATION_JSON_UTF8))
                        //期望服务器返回什么(期望返回的状态码为200)
                        .andExpect(MockMvcResultMatchers.status().isOk())
                        //期望服务器返回json中的数组长度为3
                        .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3))
                        .andReturn().getResponse().getContentAsString();
            
            System.out.println("查询简单试图"+str);
        }
        
        //@Test
        public void getInfo() throws Exception
        {
            //发起一个get请求,查看用户详情
            String str = mockMvc.perform(MockMvcRequestBuilders.get("/user/1")
                    .contentType(MediaType.APPLICATION_JSON_UTF8))
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    .andExpect(MockMvcResultMatchers.jsonPath("$.username").value("Gary"))
                    .andReturn().getResponse().getContentAsString();
            
            System.out.println("查询复杂试图"+str);
                    
        }
        
        //添加用户
        //@Test
        public void addUser() throws Exception
        {
            mockMvc.perform(MockMvcRequestBuilders.post("/user")
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .content("{\"username\":\"Gary\"}"))
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1"));
            
            
        }
        
        //修改用户
        @Test
        public void updataUser() throws Exception
        {
            mockMvc.perform(MockMvcRequestBuilders.put("/user/1")
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .content("{\"username\":\"Garyary\",\"id\":\"1\"}"))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1"));
            
        }
        
        
        
        
}
MainController.java

 

package com.Gary.GaryRESTful.controller;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.springframework.web.bind.annotation.PathVariable;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.Gary.GaryRESTful.dto.User;
import com.fasterxml.jackson.annotation.JsonView;

//表示这个Controller提供R二十天API
@RestController
public class UserController {

    
    @RequestMapping(value="/user",method = RequestMethod.GET)
    /*
     * default value     默认
     * name             请求的名字
     * required            是否是必须的,true
     * value            别名
     * 
     * */
    @JsonView(User.UserSimpleView.class)
    public List<User> query(@RequestParam(name="username",required=false) String username)
    {
        System.out.println(username);
        //满足期望服务器返回json中的数组长度为3
        List<User> list = new ArrayList<>();
        list.add(new User());
        list.add(new User());
        list.add(new User());
        return list;
        
    }
    
    @RequestMapping(value="/user/{id}",method= RequestMethod.GET)
    //将@PathVariable路径中的片段映射到java代码中    
    @JsonView(User.UserDetailView.class)
    public User getInfo(@PathVariable String id)
    {
        User user = new User();
        user.setUsername("Gary");
        return user;
    }
    
    @RequestMapping(value="/user",method= RequestMethod.POST)
    public User addUser(@RequestBody User user)
    {
        //传输json格式的时候,一定要记得加上@RequestBody注解
        //输出 null
        System.out.println(user.getPassword());
        //输出 Gary
        System.out.println(user.getUsername());
        
        user.setId("1");
        return user;
    }
    
    //修改用户资料
    @RequestMapping(value="/user/{id}",method = RequestMethod.PUT)
    public User updataUser(@RequestBody User user)
    {
        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        
        return user;
    }
    
}
UserController.java

 

package com.Gary.GaryRESTful.dto;

import com.fasterxml.jackson.annotation.JsonView;

public class User {

    //简单试图 只有一个username
    public interface UserSimpleView{};
    //复杂试图 有username 和   password 
    public interface UserDetailView extends UserSimpleView{};

    private String username;
    private String password;
    private String id;
    
    @JsonView(UserSimpleView.class)
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    @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;
    }
    
}
User.java

 

 

三、单元测试:删除用户

  在MainController.java中添加deleteUser()修改用户的单元测试方法

//删除用户
        @Test
        public void deleteUser() throws Exception
        {
            mockMvc.perform(MockMvcRequestBuilders.delete("/user/1")
                    .contentType(MediaType.APPLICATION_JSON_UTF8))
                    .andExpect(MockMvcResultMatchers.status().isOk());
        }

 

  在UserController.java中接收来自deleteUser的请求

@RequestMapping(value="/user/{id}",method = RequestMethod.DELETE)
    public User deleteUser(@PathVariable String id)
    {
        System.out.println(id);
        return null;
    }

 

 

 

package com.Gary.GaryRESTful;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class GaryResTfulApplication {

    public static void main(String[] args) {
        SpringApplication.run(GaryResTfulApplication.class, args);
    }

}
GaryResTfulApplication.java

 

package com.Gary.GaryRESTful.controller;

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;



//这是SpringBoot测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class MainController {

        @Autowired
        private WebApplicationContext webApplicationContext;
            
        //SpringMV单元测试独立测试类
        private MockMvc mockMvc;
        
        
        @Before
        public void before()
        {
            //创建独立测试类
            mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        }
        
        
        //@Test
        //查询user
        public void test() throws Exception
        {
            //发起一个Get请求
            String str = mockMvc.perform(MockMvcRequestBuilders.get("/user")
                    .param("username", "Gary")
                        //json的形式发送一个请求
                        .contentType(MediaType.APPLICATION_JSON_UTF8))
                        //期望服务器返回什么(期望返回的状态码为200)
                        .andExpect(MockMvcResultMatchers.status().isOk())
                        //期望服务器返回json中的数组长度为3
                        .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3))
                        .andReturn().getResponse().getContentAsString();
            
            System.out.println("查询简单试图"+str);
        }
        
        //@Test
        public void getInfo() throws Exception
        {
            //发起一个get请求,查看用户详情
            String str = mockMvc.perform(MockMvcRequestBuilders.get("/user/1")
                    .contentType(MediaType.APPLICATION_JSON_UTF8))
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    .andExpect(MockMvcResultMatchers.jsonPath("$.username").value("Gary"))
                    .andReturn().getResponse().getContentAsString();
            
            System.out.println("查询复杂试图"+str);
                    
        }
        
        //添加用户
        //@Test
        public void addUser() throws Exception
        {
            mockMvc.perform(MockMvcRequestBuilders.post("/user")
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .content("{\"username\":\"Gary\"}"))
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1"));
            
            
        }
        
        //修改用户
        //@Test
        public void updataUser() throws Exception
        {
            mockMvc.perform(MockMvcRequestBuilders.put("/user/1")
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .content("{\"username\":\"Garyary\",\"id\":\"1\"}"))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1"));
            
        }
        
        
        //删除用户
        @Test
        public void deleteUser() throws Exception
        {
            mockMvc.perform(MockMvcRequestBuilders.delete("/user/1")
                    .contentType(MediaType.APPLICATION_JSON_UTF8))
                    .andExpect(MockMvcResultMatchers.status().isOk());
        }
}
MainController.java

 

package com.Gary.GaryRESTful.controller;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.springframework.web.bind.annotation.PathVariable;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.Gary.GaryRESTful.dto.User;
import com.fasterxml.jackson.annotation.JsonView;

//表示这个Controller提供R二十天API
@RestController
public class UserController {

    
    @RequestMapping(value="/user",method = RequestMethod.GET)
    /*
     * default value     默认
     * name             请求的名字
     * required            是否是必须的,true
     * value            别名
     * 
     * */
    @JsonView(User.UserSimpleView.class)
    public List<User> query(@RequestParam(name="username",required=false) String username)
    {
        System.out.println(username);
        //满足期望服务器返回json中的数组长度为3
        List<User> list = new ArrayList<>();
        list.add(new User());
        list.add(new User());
        list.add(new User());
        return list;
        
    }
    
    @RequestMapping(value="/user/{id}",method= RequestMethod.GET)
    //将@PathVariable路径中的片段映射到java代码中    
    @JsonView(User.UserDetailView.class)
    public User getInfo(@PathVariable String id)
    {
        User user = new User();
        user.setUsername("Gary");
        return user;
    }
    
    @RequestMapping(value="/user",method= RequestMethod.POST)
    public User addUser(@RequestBody User user)
    {
        //传输json格式的时候,一定要记得加上@RequestBody注解
        //输出 null
        System.out.println(user.getPassword());
        //输出 Gary
        System.out.println(user.getUsername());
        
        user.setId("1");
        return user;
    }
    
    //修改用户资料
    @RequestMapping(value="/user/{id}",method = RequestMethod.PUT)
    public User updataUser(@RequestBody User user)
    {
        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        
        return user;
    }
    
    
    //删除
    @RequestMapping(value="/user/{id}",method = RequestMethod.DELETE)
    public User deleteUser(@PathVariable String id)
    {
        //输出删除的用户    可以查看JUnit中的状态吗
        System.out.println(id);
        return null;
    }
}
UserController.java

 

package com.Gary.GaryRESTful.dto;

import com.fasterxml.jackson.annotation.JsonView;

public class User {

    //简单试图 只有一个username
    public interface UserSimpleView{};
    //复杂试图 有username 和   password 
    public interface UserDetailView extends UserSimpleView{};

    private String username;
    private String password;
    private String id;
    
    @JsonView(UserSimpleView.class)
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    @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;
    }
    
}
User.java

 

  在UserController.java中通过@RequestMapping("/user")映射来处理所有user请求,使代码变得简介一些

package com.Gary.GaryRESTful.controller;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.Gary.GaryRESTful.dto.User;
import com.fasterxml.jackson.annotation.JsonView;

//表示这个Controller提供R二十天API
@RestController
@RequestMapping("/user")
public class UserController {

    
    //@RequestMapping(value="/user",method = RequestMethod.GET)
    /*
     * default value     默认
     * name             请求的名字
     * required            是否是必须的,true
     * value            别名
     * 
     * */
    @GetMapping
    @JsonView(User.UserSimpleView.class)
    public List<User> query(@RequestParam(name="username",required=false) String username)
    {
        System.out.println(username);
        //满足期望服务器返回json中的数组长度为3
        List<User> list = new ArrayList<>();
        list.add(new User());
        list.add(new User());
        list.add(new User());
        return list;
        
    }
    

    //@RequestMapping(value="/user/{id}",method= RequestMethod.GET)
    //将@PathVariable路径中的片段映射到java代码中    
    @GetMapping("/{id}")
    @JsonView(User.UserDetailView.class)
    public User getInfo(@PathVariable String id)
    {
        User user = new User();
        user.setUsername("Gary");
        return user;
    }
    
    //添加用户
    //@RequestMapping(value="/user",method= RequestMethod.POST)
    @PostMapping
    public User addUser(@RequestBody User user)
    {
        //传输json格式的时候,一定要记得加上@RequestBody注解
        //输出 null
        System.out.println(user.getPassword());
        //输出 Gary
        System.out.println(user.getUsername());
        
        user.setId("1");
        return user;
    }
    
    //修改用户资料
    //@RequestMapping(value="/user/{id}",method = RequestMethod.PUT)
    @PutMapping("/{id}")
    public User updataUser(@RequestBody User user)
    {
        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        
        return user;
    }
    
    
    //删除
    //@RequestMapping(value="/user/{id}",method = RequestMethod.DELETE)
    @DeleteMapping("/{id}")
    public User deleteUser(@PathVariable String id)
    {
        //输出删除的用户    可以查看JUnit中的状态吗
        System.out.println(id);
        return null;
    }
}
UserController.java

 

 

四、SpringBoot默认处理异常路径

  在项目static->error目录下创建一个404.html,运行项目

 

 

 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>404页面</title>
</head>
<body>
<h1>404错误,你的页面找不到了!!!</h1>
</body>
</html>
404.html

 

我们今天的关于Spring RESTful控制器方法改进建议spring restcontroller的分享就到这里,谢谢您的阅读,如果想了解更多关于asp.net-mvc – 具有不同Http方法的RESTful控制器,但是相同的参数、java – 单元测试Spring RESTful控制器时“内容类型未设置”、java – 如何在Spring 3中使用注释配置RESTful控制器?、JavaWeb-RESTful(三)_使用SpringMVC开发RESTful_下的相关信息,可以在本站进行搜索。

本文标签: