SpringSecurity下做POST测试以及传递实体

来源:互联网 发布:外国域名注册机构 编辑:程序博客网 时间:2024/05/29 13:07

     写完代码之后,要测试,由于不怎么会用postman,加上用了spring security,所以需要登录,很麻烦。对于对于get请求,直接访问还好,但是对于POST请求,我就很无可奈何了,一些post请求能改成get请求还好说,有些不好改的就太费劲了。后来有人告诉了我一个ajax的写法。其实也蛮麻烦的,但是还好。

首先,我不是用了spring security吗,所以需要先登录。

      然后,因为要用ajax,所以页面上一定要引用ajax,否则,会提示$.ajax is not a function。

      然后,你就可以使用OPTION+COMMAND+I(mac的chrome浏览器)打开console。然后,你就可以在console,写这样的代码就可以了。

$.ajax({      url:'http://127.0.0.1/test/post',      type:'post',      data:{         id:1,         name:'呵呵',         description:'为何会'      },     dataType:'json'}).then(function(data) {console.log(data)});
      然后后台可能是这样一个接收类。

package com.tgb.controller;import com.tgb.entity.MyEntity;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;import java.util.HashMap;import java.util.Map;/** * 测试post */@RestController@Controller@PreAuthorize("hasRole('ADMIN')")public class TestController extends BaseController {         /**     * 测试POST     * @param  id     * @param  name     * @param  description     * @return 信息     */    @RequestMapping(value = "/test/post",method = RequestMethod.POST)    public Object testPost(@RequestParam(value = "id")String id,@RequestParam(value = "name")String name,                              @RequestParam(value = "description",required = false)String description) {        String testPost = "test post:"+id+","+name+","+description;        Map<String, Object> result = new HashMap<>();        result.put("data", testPost);        return result;    }    /**     * 测试POST实体     * @param  entity 实体     * @param name     * @return 信息     */    @RequestMapping(value = "/test/post/entity",method = RequestMethod.POST)    public Object testPostEntity(MyEntity entity,                              @RequestParam(value = "name",required = false)String name) {        String testPost = "test post entity:"+entity.getId()+","+entity.getName()+","+entity.getDescription();        Map<String, Object> result = new HashMap<>();        result.put("data", testPost);        return result;    }}
      然后效果如下,


      然后对于测试实体写了不少不行的代码,

testPostEntity(MyEntity entity,                              @RequestParam(value = "name",required = false)String name) 

      这里要注意不能写成@RequestParam(value="entity")MyEntity entity这样,要不然总是提示你找不到叫entity的参数;

org.springframework.web.bind.MissingServletRequestParameterException: Required MyEntity parameter 'entity' is not present。

      除此之外,我还尝试了其他几种方式。效果如下


      JSON.stringfy不知道是不是使用方式不对,并没有什么效果;

 

      这样写也没有什么效果;


      然后这么写是可以的。

      总结一下就是:若是AJAX传递实体,直接将所有属性写出来,和普通的参数一样就行。