返回json数据要点及其他ssm注意事项

SSM 个人博客地址(欢迎访问我的个人博客,现开放注册)

路由传参问题:

 路由一:PaginationUser?page=2&limit=10
 路由二:/deleteUser/{id}
  如果像是路由二大家一看便知使用@ PathVariable注解实现取值,但是如果像是路由一就有可能犯迷糊了,会使用PaginationUser?page={page}&limit={limit}可以明确的告诉大家使用@ PathVariable注解会报错,我们的解析器是无法解析的,即使看似什么都没有问题,这时候就需要用到我们的@ RequestParam注解了,这个注解不单单有强制要求某一个参数的作用,还可以在这里实现取值。

@RequestParam 适用于

路由为 <PaginationUser?page=2&limit=10>

路由后携带数据 get 方式

    @RequestMapping(path = "/PaginationUser", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String PaginationUser(@RequestParam(name = "page") Integer page, @RequestParam(name = "limit") Integer limit) {

        List<User> users;

        if (page == 1) {
            users = service.PaginationUser(page - 1, limit);
        } else {
            users = service.PaginationUser((page - 1) * limit, limit);
        }

        int count = service.countAll();
        // 数据封装
        if (users.size() != 0) {
            return "{ \"code\":200,\"msg\":\"成功\",\"data\":" + JSONObject.toJSONString(users) + ",\"count\" : " + count + "}";
        } else {
            return "{ \"code\":100,\"msg\":\"失败\",\"data\": [],\"count\" : 0}";
        }

    }

@PathVariable 适用于

路由为 </deleteUser/{id}>

由斜杆分开的传参方式,如果使用<PaginationUser?page={page}&limit={limit}>是无法获取路由映射的

    @RequestMapping(value = "/deleteUser/{id}", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String deleteUser(@PathVariable(name = "id") Integer id) {
        if (service.deleteUser(id)) {
            return "{ \"code\":200,\"msg\":\"成功\"}";
        } else {
            return "{ \"code\":100,\"msg\":\"失败\"}";
        }
    }

为什么需要序列化?

 当数据中含有””或者其他特殊字符时,如果没有序列化数据,那么前端将无法解析,导致解析出错,本质上并不是数据或其他的问题,只需要中间多一步处理便可避免此问题发生。

操作步骤:

  将相关bean实现系列化接口,并使用fastjson进行序列化或反序列化处理。

    @RequestMapping(value = "/getArticleById/{id}", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    @ResponseBody
    public String getArticleById(@PathVariable(name = "id")Integer id) {
        Article article = service.getArticleById(id);
        if (!article.toString().equals("null")) {
            return "{ \"code\":200,\"msg\":\"成功\",\"data\":"+ JSON.toJSONString(article.toString()) +"}";
        } else {
            return "{ \"code\":100,\"msg\":\"失败\"}";
        }
    }

Request header too large问题:

 出现此类问题是由于请求头太大而无法解析的问题,由于tomcat默认对请求头进行了限定,所以我们可以去tomcat的安装目录下找到conf目录下的server.xml文件,向connector添加属性,则可以正常解析!

    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"
               maxHttpHeaderSize ="102400"
    />
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章