Spring 4.2.4.RELEASE MVC 学习笔记 - 6 - RestFull API(咋个办呢 zgbn)

来源:互联网 发布:600718大数据 编辑:程序博客网 时间:2024/05/18 03:22

Spring 4.2.4.RELEASE MVC 学习笔记 - 6 - RestFull API

配置Spring mvc支持RestFull模式,发布API接口。


    在实际项目中,很多都需要系统对外发布接口,我们俗称API,这些接口请求、应答通常都采用JSON数据报文,那么下面我们看看spring mvc中如何发布接口。

Demo介绍

    在开始之前,我先把这次学习的结果写出来吧,有点目标往下比较容易。    因HTTP请求存在很多方法,所以我们可以通过在同一个接口判断不同的请求方式来做不同的动作,如下面说明。    但实际中下面的方式确实不是我们常用的,所以我就是写出来凑凑热闹而已,不要当真。
API URL 说明 请求类型 请求参数 返回结果 /api/user.api 添加新用户 HTTP POST {username:”xiaohong”,name:”小红”, age:22, sex:0} {code:0, error:”“, msgcode:200, msg:”添加一个新的用户成功”, data={…}} /api/user.api HTTP GET 查询用户 username=xiaohong {code:0, error:”“, msgcode:201, msg:”查询用户成功”, data={username:”xiaohong”,name:”小红”, age:22, sex:0}} /api/user.api 更新用户信息 HTTP PUT {username:”xiaohong”, age:23} {code:0, error:”“, msgcode:201, msg:”更新用户信息成功”, data={username:”xiaohong”,name:”小红”, age:23, sex:0}} /api/user.api 更新用户信息 HTTP DELETE username=xiaohong {code:0, error:”“, msgcode:201, msg:”更新用户信息成功”


    好吧,实际开发中我们常用的之后HTTP的GET、POST两种方式的请求,并且对不同的功能接口取不同的名字。所以这次主要去实现下面给出的API。    *POST方式,通常用来提交数据、新增数据、更新数据、上报数据、报文通讯等等;    *GET 方式,通常用来查询数据、删除数据等等;
API URL 说明 请求类型 请求参数 返回结果 /api/userAdd.api 添加新用户 HTTP POST {username:”xiaohong”,name:”小红”, age:22, sex:0} {code:0, error:”“, msgcode:200, msg:”添加一个新的用户成功”, data={…}} /api/userQuery.api HTTP GET 查询用户 username=xiaohong {code:0, error:”“, msgcode:201, msg:”查询用户成功”, data={username:”xiaohong”,name:”小红”, age:22, sex:0}} /api/userSave.api 更新用户信息 HTTP POST {username:”xiaohong”, age:23} {code:0, error:”“, msgcode:201, msg:”更新用户信息成功”, data={username:”xiaohong”,name:”小红”, age:23, sex:0}} /api/userDel.api 更新用户信息 HTTP GET username=xiaohong {code:0, error:”“, msgcode:201, msg:”更新用户信息成功”

导入JSON工具jar包

    打开framework_spring工程,在pom.xml中添加json工具jar包配置,这里引入的是Gson.jar因为我个人比较喜欢用,但是能否和spring mvc很好的整合我不知道,不过初级学习也没有整合的必要,只要能实现上面的结果就可以了,高级整合东东以后有时间在研究。
        <!-- 导入Gson json工具包 -->        <dependency>            <groupId>com.google.code.gson</groupId>            <artifactId>gson</artifactId>            <version>2.6</version>        </dependency>

创建自定义的ModelAndView

    先不考虑spring mvc自身有没有处理JSON的功能,我们就用之前学习到的知识来完成。    首先我的想法是,自定义ModelAndView去继承ModelAndView然后扩展我们需要的方法,利用之前验证过的controller对方法返回String结果的处理机制来实现。

创建XModeAndView

创建cn.vfire.framework.spring.mvc.view.XModelAndView类继承ModelAndView。
package cn.vfire.framework.spring.mvc.view;import java.util.Map;import org.springframework.web.servlet.ModelAndView;import com.google.gson.Gson;public class XModelAndView extends ModelAndView {    public String toJson() {        Map<String, Object> mode = super.getModel();        if(mode==null){            return "{}" ;        }        return new Gson().toJson(mode) ;    }}

实现过程

  • 创建cn.vfire.framework.spring.mvc.view.XModelAndView类
  • 创建cn.vfire.framework.spring.mvc.mode.UserMode类
  • 创建cn.vfire.framework.spring.mvc.controller.UserController类
  • 创建/framework_spring/src/main/webapp/user.html测试页面

cn.vfire.framework.spring.mvc.view.XModelAndView

package cn.vfire.framework.spring.mvc.view;import java.util.Map;import lombok.Getter;import lombok.Setter;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.View;import com.google.gson.Gson;public class XModelAndView extends ModelAndView {    public XModelAndView() {        super();    }    public XModelAndView(String viewName, Map<String, ?> model) {        super(viewName, model);    }    public XModelAndView(String viewName, String modelName, Object modelObject) {        super(viewName, modelName, modelObject);    }    public XModelAndView(String viewName) {        super(viewName);    }    public XModelAndView(View view, Map<String, ?> model) {        super(view, model);    }    public XModelAndView(View view, String modelName, Object modelObject) {        super(view, modelName, modelObject);    }    public XModelAndView(View view) {        super(view);    }    private static class Result {        @Getter        @Setter        private int code;        @Getter        @Setter        private String error;        @Getter        @Setter        private String msgcode;        @Getter        @Setter        private String msg;        @Getter        @Setter        private Object data;    }    /**     * 返回JSON报文。     *      * @param code     *            处理结果代码 0成功,1失败。     * @param error     *            当code=1时,传入错误描述。     * @param msgcode     *            处理结果信息代码,通过代码检索提示信息映射表,对msg属性赋值。     * @return     */    public String toJson(int code, String error, String msgcode) {        Result rs = new Result();        {            rs.setCode(code);            rs.setMsg(msgcode);            rs.setError(error == null ? code == 0 ? "SUCCESS" : "FAIL" : error);        }        Map<String, Object> mode = super.getModel();        if (mode != null && mode.isEmpty()==false) {            if(mode.size()==1){                String k = mode.keySet().iterator().next() ;                rs.setData(mode.get(k));            }            if(mode.size()>1){                rs.setData(mode);            }        }        return new Gson().toJson(rs);    }    /**     * 返回JSON报文。     *      * @param code     *            处理结果代码 0成功,1失败。     * @param msgcode     *            处理结果信息代码,通过代码检索提示信息映射表,对msg属性赋值。     * @return     */    public String toJson(int code, String msgcode) {        return this.toJson(code, null, msgcode);    }    /**     * 返回JSON报文。     *      * @param code     *            处理结果代码 0成功,1失败。     * @param msgcode     *            处理结果信息代码,通过代码检索提示信息映射表,对msg属性赋值。     * @return     */    public String toJson() {        return this.toJson(0, null, null);    }}

cn.vfire.framework.spring.mvc.mode.UserMode

package cn.vfire.framework.spring.mvc.mode;import lombok.Getter;import lombok.Setter;public class UserMode {    @Getter    @Setter    private String username ;    @Getter    @Setter    private String name ;    @Getter    @Setter    private int age ;    @Getter    @Setter    private int sex ;}

cn.vfire.framework.spring.mvc.controller.UserController

package cn.vfire.framework.spring.mvc.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import cn.vfire.framework.spring.mvc.mode.UserMode;import cn.vfire.framework.spring.mvc.view.XModelAndView;@RequestMapping("/api")@RestControllerpublic class UserController {    @RequestMapping(path = "/userAdd.api", method = RequestMethod.POST)    public String userAdd(UserMode user) {        XModelAndView modeView = new XModelAndView();        modeView.addObject("user", user);        System.out.println(String.format("添加用户%s完成", user.getName()));        return modeView.toJson();    }    @RequestMapping(path = "/userQuery.api", method = RequestMethod.GET)    public String userQuery(String username) {        XModelAndView modeView = new XModelAndView();        UserMode user = new UserMode();        {            user.setUsername(username);            user.setName("小红");            user.setAge(22);            user.setSex(0);        }        modeView.addObject("user", user);        System.out.println(String.format("查询用户名为%s用户 信息成功", user.getUsername()));        return modeView.toJson();    }    @RequestMapping(path = "/userSave.api", method = RequestMethod.POST)    public String userSave(UserMode user) {        XModelAndView modeView = new XModelAndView();        user.setAge(23);        modeView.addObject("user", user);        System.out.println(String.format("更新用户名为%s用户信息成功", user.getUsername()));        return modeView.toJson();    }    @RequestMapping(path = "/userDel.api", method = RequestMethod.GET)    public String userDel(String username) {        XModelAndView modeView = new XModelAndView();        System.out.println(String.format("删除用户名为%s用户信息成功", username));        return modeView.toJson();    }}

/framework_spring/src/main/webapp/user.html

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>测试页面</title></head><body>    <div>        <div>HTTP POST 添加用户 /api/userAdd.api</div>        <form action="/api/userAdd.api" method="post">            <div>用户名:<input name="username" value="xiaohong" /></div>            <div>姓名:<input name="name" value="小红" /></div>            <div>年龄:<input name="age" value="22" /></div>            <div>性别:<select name="sex"><option value="0" selected="selected"></option></select></div>            <div><button type="submit">添加新用户</button></div>        </form>        <hr />    </div>    <div>        <div>HTTP GET 查询用户 /api/userQuery.api</div>        <form action="/api/userQuery.api" method="get">            <div>用户名:<input name="username" value="xiaohong" /></div>            <div><button type="submit">查询</button></div>        </form>        <hr />    </div>    <div>        <div>HTTP POST 查询用户 /api/userSave.api</div>        <form action="/api/userSave.api" method="post">            <div>用户名:<input name="username" value="xiaohong" /></div>            <div>姓名:<input name="name" value="小红" /></div>            <div>年龄:<input name="age" value="23" /></div>            <div>性别:<select name="sex"><option value="0" selected="selected"></option></select></div>            <div><button type="submit">添加新用户</button></div>        </form>        <hr />    </div>      <div>        <div>HTTP GET 查询用户 /api/userDel.api</div>        <form action="/api/userDel.api" method="get">            <div>用户名:<input name="username" value="xiaohong" /></div>            <div><button type="submit">添加新用户</button></div>        </form>        <hr />    </div>      </body></html>

测试结果

    测试结果竟然有中文乱码,呵呵,先不管它。总之到这里已经简单粗暴的实现了前面的目标结果。    好了先写到这里吧,马上要赶火车了,等回来后我们在继续学习如何整合spring mvc处理json。

这里写图片描述

这里写图片描述

这里写图片描述

待续…

0 0
原创粉丝点击