SpringBoot:四、SpringBoot的基础知识(请求)

版权声明:转载请注明出处 https://blog.csdn.net/chenmingxu438521/article/details/89352196

一、@RestController的解释

1.@RestController=@Controller+@ResponseBody 表示这是个控制器bean,并且是将函数的返回值直接填入HTTP响应体中,是REST风格的控制器,会让所有返回的对象转成json格式,不会返回视图。

参考上一篇博文:https://blog.csdn.net/chenmingxu438521/article/details/87780803

二、@RequestMapping的解释

1.@RequestMapping是一个用来处理请求地址映射的注解,可用在类和方法上,用在类上,表示类中的所有响应请求方法都是以该地址作为父路径。

2.@RequstMapping有6个请求参数:

2.1.value:指定请求的具体地址;

@ReuestMapping(value = "/getList")

2.2.method:请求方法的类型,如GET,POST;

@RequestMapping(method = RequestMethod.GET)

2.3.consums:代表请求提交内容的类型,如application/json,text/html;

@RequestMapping(value = "getList",consumes = "application/json")

2.4.produce:指定返回内容的类型,只有当request请求头中包含返回的类型才返回,也就是说请求头中的Content-Type要和返回类型相同

@RequestMapping(value = "/getList", produce = "application/json")

2.5.param:代表请求中的参数必须和该变量中的参数相同才对请求做出处理;

@RequestMapping(value = "/getList/{id}", param = "myParam=param")

2.6.handers:指定请求中必须包含某些特定的hander值,才对请求进行处理;

@RequestMapping(value = "/getList/{ids}", handers = "Referer=http://www.baidu.com")

总结:如果在注解中不些参数名称,那么注解里面的值就默认赋给value参数@RequestMapping("/getLIst")相当于@RequestMapping(value = "/getList"),value参数还可以是某个变量的值(@RequestMapping(value = "/{id}")),也可以是一个正则表达式(@RequestMapping(value = "/getList/{id:[a-z-]}"));

三、@Pathvariable的解释

1.当使用@RequestMapping样式映射时, 即 someUrl/{paramId}, 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。@Pathvariable一个方法中可以方多个。

实例:

@Controller
@RequestMapping("/test1/{test1Id}")
public class DemoController {
  
  @RequestMapping("/test2/{test2Id}")
  public void findPet(@PathVariable String test1Id,@PathVariable String test2Id, Model model) {    
    // 具体代码
  }
}

四、@RequestHeader的解释

1.@RequestHeader注解,可以把Request请求header部分的值绑定到方法的参数上。

例子:

@RequestMapping(value = "/example", method = RequestMethod.GET)  
   public String  getHello(@RequestHeader ("host") String hostName,  
        @RequestHeader ("Accept") String acceptType,  
        @RequestHeader ("Accept-Language") String acceptLang,  
        @RequestHeader ("Accept-Encoding") String acceptEnc,  
        @RequestHeader ("Cache-Control") String cacheCon,  
        @RequestHeader ("Cookie") String cookie,  
        @RequestHeader ("User-Agent") String userAgent)  
   {  
    System.out.println("Host : " + hostName);  
    System.out.println("Accept : " + acceptType);  
    System.out.println("Accept Language : " + acceptLang);  
    System.out.println("Accept Encoding : " + acceptEnc);  
    System.out.println("Cache-Control : " + cacheCon);  
    System.out.println("Cookie : " + cookie);  
    System.out.println("User-Agent : " + userAgent);  
       return "example";  
   }

五、@CookieValue的解释

1.@CookieValue是SpringMvc的注解,用来获取Cookie中的值,@CookieValue参数有:

         1.1.value:参数名称

         1.2.required:是否必须

      1.3.defaultValue:默认值

   实例:

/**
 * 验证用户信息
 * @param token
 * @return
 */
@GetMapping("verify") //直接获取cookie中的token值
public ResponseEntity<UserInfo> verifyUser(@CookieValue("LY_TOKEN") String token) {
    try {
        // 获取token信息
        UserInfo userInfo = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
        // 成功后直接返回
        return ResponseEntity.ok(userInfo);
    } catch (Exception e) {
        // 抛出异常,证明token无效,直接返回401
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
    }
}

六、@RequestBody的解释

1.该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上。

2.再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。

3.使用时机:

3.1.GET、POST方式提时, 根据request header Content-Type的值来判断:

    3.1.1.application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理);

    3.1.2.multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);

    3.1.3.其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);

 3.2.PUT方式提交时, 根据request header Content-Type的值来判断:

     3.2.1.application/x-www-form-urlencoded, 必须;

     3.2.2.multipart/form-data, 不能处理;

     3.2.3. 其他格式, 必须;

说明:request的body部分的数据编码格式由header部分的Content-Type指定;

七、@ResponseBody的解释

1.该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

2.使用时机:

      返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

实际例子:@RequestBody注解可以接收json格式的数据,并将其转换成对应的数据类型。

2.1. @RequestBody接收一个对象
url请求:http://localhost:8080/WxProgram/findBookByName

@RequestMapping(value="/findBookByName", method = RequestMethod.POST)
@ResponseBody
public DbBook findBookByName(@RequestBody DbBook book){
    System.out.println("book: " + book.toString());
    System.out.println("book name: " + book.getTitle());
    String bookName = book.getTitle();
    DbBook book = wxService.findBookByName(bookName);    
    return book;
}

2.2. @RequestBody接收不同的字符串

wx.request({
      url: host.host + `/WxProgram/deleteBookById`,
      method: 'POST',
      data: {
        nick: this.data.userInfo.nickName,
        bookIds: bookIds
      },
      success: (res) => {
        console.log(res);
        this.getCollectionListFn();
      },
      fail: (err) => {
        console.log(err);
      }
    })

Controller.java

@RequestMapping(value="/deleteBookById",method=RequestMethod.POST)
@ResponseBody
public void deleteBookById(@RequestBody Map<String, String> map){
    String bookIds = map.get("bookIds");
    String nick = map.get("nick");
    String[] idArray = bookIds.split(",");
    Integer userId = wxService.findIdByNick(nick);
    for(String id : idArray){
        Integer bookid = Integer.parseInt(id);
        System.out.println("bookid: " + bookid);
        wxService.removeBookById(bookid, userId);
    }
}

@RequestBody
处理HttpEntity传递过来的数据,一般用来处理非Content-Type: application/x-www-form-urlencoded编码格式的数据。

GET请求中,因为没有HttpEntity,所以@RequestBody并不适用。
POST请求中,通过HttpEntity传递的参数,必须要在请求头中声明数据的类型Content-Type,SpringMVC通过使用HandlerAdapter 配置的HttpMessageConverters来解析HttpEntity中的数据,然后绑定到相应的bean上。

@RequestBody用于post请求,不能用于get请求

这里涉及到使用@RequestBody接收不同的对象
1. 创建一个新的entity,将两个entity都进去。这是最简单的,但是不够“优雅”。
2. 用Map<String, Object>接受request body,自己反序列化到各个entity中。
3. 类似方法2,不过更为generic,实现自己的HandlerMethodArgumentResolver

附加:@ModelAttribute的解释

1.@ModelAttribute注解类型将参数绑定到Model对象

2. userTest.jsp

<form action="/WxProgram/json/modelAttributeTest" method="post">
    modelAttribute Test<br>
    用户id:<input type="text" name="userId"><br>
    用户名:<input type="text" name="userName"><br>
    用户密码:<input type="password" name="userPwd"><br>
    <input type="submit" value="提交"><br>
</form>

name的属性值要跟User的属性相对应。

3.UserController.java

@RequestMapping(value="/modelAttributeTest", method = RequestMethod.POST)
    public String modelAttributeTest(@ModelAttribute User user){
        System.out.println("modelAttribute Test");
        System.out.println("userid: " + user.getUserId());
        System.out.println("username: " + user.getUserName());
        System.out.println("userpwd: " + user.getUserPwd());
        return "hello";
    }

4.User.java

public class User {
    private Integer userId;
    private String userName;
    private String userPwd;
    
    public User(){
        super();
    }
        //setter and getter      
}

总结:当前台界面使用GET或POST方式提交数据时,数据编码格式由请求头的ContentType指定。分为以下几种情况:
1. application/x-www-form-urlencoded,这种情况的数据@RequestParam、@ModelAttribute可以处理,@RequestBody也可以处理。
2. multipart/form-data,@RequestBody不能处理这种格式的数据。(form表单里面有文件上传时,必须要指定enctype属性值为multipart/form-data,意思是以二进制流的形式传输文件。)
3. application/json、application/xml等格式的数据,必须使用@RequestBody来处理。

八、@RequestParam的解释

1.@RequestParam的作用:GET和POST请求传的参数会自动转换赋值到@RequestParam 所注解的变量上。

2. @RequestParam(org.springframework.web.bind.annotation.RequestParam)用于将指定的请求参数赋值给方法中的形参。
例:
2.1.get请求例子:

url请求:http://localhost:8080/WxProgram/findAllBookByTag?tagId=1&pageIndex=3

userTest.jsp

<form action="/WxProgram/json/requestParamTest" method="get">
    requestParam Test<br>
    用户名:<input type="text" name="username"><br>
    用户昵称:<input type="text" name="usernick"><br>
    <input type="submit" value="提交">
</form>

UserController.java

@RequestMapping(value="/requestParamTest", method = RequestMethod.GET)
    //value中的参数名称要跟name中参数名称一致
    public String requestParamTest(@RequestParam(value="username") String userName, @RequestParam(value="usernick") String userNick){
        System.out.println("requestParam Test");
        System.out.println("username: " + userName);
        System.out.println("usernick: " + userNick);
        return "hello";
    }

上述代码等价于:

@RequestMapping(value="/requestParamTest", method = RequestMethod.GET)
    //request.getParameter("usernick")
    public String requestParamTest(String username, HttpServletRequest request){
        System.out.println("requestParam Test");
        System.out.println("username: " + username);
        String usernick = request.getParameter("usernick");
        System.out.println("usernick: " + usernick);
        return "hello";
    }

也可以不使用@RequestParam,直接接收,此时要求controller方法中的参数名称要跟form中name名称一致

@RequestMapping(value="/requestParamTest", method = RequestMethod.GET)
    //此时要参数名称一致
    public String requestParamTest(String username, String usernick){
        System.out.println("requestParam Test");
        System.out.println("username: " + username);
        System.out.println("usernick: " + usernick);
        return "hello";
    }

2.2. post请求:跟get请求格式一样,只是把方法中的get换成post

2.2.1.@RequestParam用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。提交方式为get或post。(Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)

2.2.2.RequestParam实质是将Request.getParameter() 中的Key-Value参数Map利用Spring的转化机制ConversionService配置,转化成参数接收对象或字段。

2.2.3.get方式中query String的值,和post方式中body data的值都会被Servlet接受到并转化到Request.getParameter()参数集中,所以@RequestParam可以获取的到。

可参考博客:https://www.cnblogs.com/zeroingToOne/p/8992746.html写的很详细。

九、@CrossOrigin

使用例子:

import java.util.HashMap;

import org.springframework.web.bind.annotation.CrossOrigin;
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;

/**
 * @author wujing
 */
@RestController
@RequestMapping(value = "/api", method = RequestMethod.POST)
public class ApiController {
        
    @CrossOrigin(origins = "http://172.16.71.27:8080")
    @RequestMapping(value = "/get")
    public HashMap<String, Object> get(@RequestParam String name) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("title", "hello world");
        map.put("name", name);
        return map;
    }
}
<script>
        $(function() {
            $('#title').click(function() {
//                 alert('点击了');
                $.ajax({
                    url : "http://localhost:8081/api/get",
                    type : "POST",
                    data : {
                        name : "测试"
                    },
                    success : function(data, status, xhr) {
                        console.log(data);
                        alert(data.name);
                    }
                });
            });
        })
    </script>

参考博客: https://www.cnblogs.com/xuyou551/p/8335623.html

十、结束

就介绍到这个地方吧!!!后期会在做补充。

猜你喜欢

转载自blog.csdn.net/chenmingxu438521/article/details/89352196