由于前后端数据分离的强烈需要,现在越来越需要接口化的开发,特别是服务器端的开发和移动端后台的开发,前后端的数据交互自然不能使用之前直接传数据的方式,于是JSON便成了最佳的选择,JSON的底层是HashMap,键值对的方式可以生成或解析JavaBean,既能满足要求,又不失开发效率.下面开发一个简单的获取某个id数据的接口,给访问的前端返回JSON数据.
代码:
一.获取数据库中的数据
#数据模型层
- package com.east.entity;
- import java.io.Serializable;
- import java.sql.Timestamp;
- public class Inform implements Serializable {
- private Integer info_id;
- private String info_title;
- private String info_content;
- private Timestamp info_time;
- public Integer getInfo_id() {
- return info_id;
- }
- public void setInfo_id(Integer info_id) {
- this.info_id = info_id;
- }
- public String getInfo_title() {
- return info_title;
- }
- public void setInfo_title(String info_title) {
- this.info_title = info_title;
- }
- public String getInfo_content() {
- return info_content;
- }
- public void setInfo_content(String info_content) {
- this.info_content = info_content;
- }
- public Timestamp getInfo_time() {
- return info_time;
- }
- public void setInfo_time(Timestamp info_time) {
- this.info_time = info_time;
- }
- @Override
- public String toString() {
- return "Inform [info_id=" + info_id + ", info_title=" + info_title + ", info_content=" + info_content
- + ", info_time=" + info_time + "]";
- }
- }
#数据访问层
- package com.east.dao;
- import java.util.List;
- import org.apache.ibatis.annotations.Delete;
- import org.apache.ibatis.annotations.Insert;
- import org.apache.ibatis.annotations.Options;
- import org.apache.ibatis.annotations.Param;
- import org.apache.ibatis.annotations.Select;
- import com.east.entity.Inform;
- public interface InformDao {
- /*
- * 查询某个公告的信息
- */
- @Select("select * from inform where info_id = #{info_id}")
- Inform findById(Integer info_id);
- }
#业务逻辑层
- package com.east.biz;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Isolation;
- import org.springframework.transaction.annotation.Propagation;
- import org.springframework.transaction.annotation.Transactional;
- import com.east.dao.InformDao;
- import com.east.entity.Inform;
- @Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT)
- @Service("informBiz")
- public class InformBiz {
- /*
- * 自动注入InformDao
- */
- @Autowired
- private InformDao informDao;
- public Inform findById(Integer info_id){
- return informDao.findById(info_id);
- }
- }
二.JSON操作相关的对象类
- package com.east.util;
- import java.util.Date;
- /*
- * 建立AbstractJSON(JSON数据的响应基类 )
- */
- public class AbstractJSON {
- private String code; //响应状态码
- private String msg; //响应状态描述
- private Long time = new Date().getTime(); //时间戳
- public String getCode() {
- return code;
- }
- public void setCode(String code) {
- this.code = code;
- }
- public String getMsg() {
- return msg;
- }
- public void setMsg(String msg) {
- this.msg = msg;
- }
- public Long getTime() {
- return time;
- }
- public void setTime(Long time) {
- this.time = time;
- }
- public void setContent(String code, String msg) {
- this.code = code;
- this.msg = msg;
- }
- public void setStatusObject(StatusObject statusObject) {
- this.code = statusObject.getCode();
- this.msg = statusObject.getMsg();
- }
- }
- package com.east.util;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.StringWriter;
- import com.fasterxml.jackson.core.JsonFactory;
- import com.fasterxml.jackson.core.JsonGenerator;
- import com.fasterxml.jackson.core.JsonParseException;
- import com.fasterxml.jackson.databind.JsonMappingException;
- import com.fasterxml.jackson.databind.ObjectMapper;
- public class JsonWriter {
- private static ObjectMapper om = new ObjectMapper();
- private static JsonFactory jf = new JsonFactory();
- public static <T> Object fromJson(String jsonAsString, Class<T> pojoClass) {
- try {
- return om.readValue(jsonAsString, pojoClass);
- } catch (JsonParseException e) {
- throw new IllegalStateException(e.getMessage(), e);
- } catch (JsonMappingException e) {
- throw new IllegalStateException(e.getMessage(), e);
- } catch (IOException e) {
- throw new IllegalStateException(e.getMessage(), e);
- }
- }
- public static <T> Object fromJson(FileReader fr, Class<T> pojoClass) {
- try {
- return om.readValue(fr, pojoClass);
- } catch (JsonParseException e) {
- throw new IllegalStateException(e.getMessage(), e);
- } catch (JsonMappingException e) {
- throw new IllegalStateException(e.getMessage(), e);
- } catch (IOException e) {
- throw new IllegalStateException(e.getMessage(), e);
- }
- }
- public static String toJson(Object pojo, boolean prettyPrint) {
- try {
- StringWriter sw = new StringWriter();
- JsonGenerator jg = jf.createGenerator(sw);
- if (prettyPrint) {
- jg.useDefaultPrettyPrinter();
- }
- om.writeValue(jg, pojo);
- return sw.toString();
- } catch (JsonParseException e) {
- throw new IllegalStateException(e.getMessage(), e);
- } catch (JsonMappingException e) {
- throw new IllegalStateException(e.getMessage(), e);
- } catch (IOException e) {
- throw new IllegalStateException(e.getMessage(), e);
- }
- }
- public static void toJson(Object pojo, FileWriter fw, boolean prettyPrint) {
- try {
- JsonGenerator jg = jf.createGenerator(fw);
- if (prettyPrint) {
- jg.useDefaultPrettyPrinter();
- }
- om.writeValue(jg, pojo);
- } catch (JsonParseException e) {
- throw new IllegalStateException(e.getMessage(), e);
- } catch (JsonMappingException e) {
- throw new IllegalStateException(e.getMessage(), e);
- } catch (IOException e) {
- throw new IllegalStateException(e.getMessage(), e);
- }
- }
- public static String toJson(Object pojo) {
- return toJson(pojo, false);
- }
- }
- package com.east.util;
- import java.util.List;
- /*
- * 建立JSON数组类ListObject
- */
- public class ListObject extends AbstractJSON {
- private List<?> items; // 列表对象
- public List<?> getItems() {
- return items;
- }
- public void setItems(List<?> items) {
- this.items = items;
- }
- }
- package com.east.util;
- import com.fasterxml.jackson.databind.ObjectMapper;
- /*
- * JsonUtils生成json数据和解析json数据
- */
- public class JsonUtils {
- static ObjectMapper objectMapper;
- /*
- * 解析json
- */
- public static <T> T fromJson(String content, Class<T> valueType) {
- if (objectMapper == null) {
- objectMapper = new ObjectMapper();
- }
- try {
- return objectMapper.readValue(content, valueType);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- /*
- * 生成json
- */
- public static String toJson(Object object) {
- if (objectMapper == null) {
- objectMapper = new ObjectMapper();
- }
- try {
- return objectMapper.writeValueAsString(object);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- }
- package com.east.util;
- /*
- * 建立JSON对象类SingleObject
- */
- public class SingleObject extends AbstractJSON {
- private Object object;
- public Object getObject() {
- return object;
- }
- public void setObject(Object object) {
- this.object = object;
- }
- }
- package com.east.util;
- /*
- * 定义状态码
- */
- public class StatusCode {
- public static String CODE_SUCCESS = "ok"; //访问成功
- public static String CODE_ERROR = "0001"; //访问错误
- public static String CODE_ERROR_PARAMETER = "0002";//参数错误
- public static String CODE_ERROR_PROGRAM = "0003"; //程序异常
- public static String CODE_ERROR_NO_LOGIN_OR_TIMEOUT = "0004"; //未登录或登录超时,请重新登录
- public static String CODE_ERROR_EXIST_OPERATION = "0005"; //已操作
- }
- package com.east.util;
- import java.io.IOException;
- import javax.servlet.http.HttpServletResponse;
- /*
- * 响应处理
- */
- public class ResponseUtils {
- /*
- * 返回json串
- */
- public static void renderJson(HttpServletResponse response, String text) {
- // System.out.print(text);
- render(response, "text/plain;charset=UTF-8", text);
- }
- /*
- * 返回文本
- */
- public static void renderText(HttpServletResponse response, String text) {
- render(response, "text/plain;charset=UTF-8", text);
- }
- /*
- * 发送内容,使用UTF-8编码
- */
- public static void render(HttpServletResponse response, String contentType, String text) {
- response.setContentType(contentType);
- response.setCharacterEncoding("utf-8");
- response.setHeader("Pragma", "No-cache");
- response.setHeader("Cache-Control", "no-cache");
- response.setDateHeader("Expires", 0);
- try {
- response.getWriter().write(text);
- } catch (IOException e) {
- }
- }
- /*
- * 页面异步回调返回Json
- */
- public static void outputJson(HttpServletResponse response, Object obj) {
- String s = JsonWriter.toJson(obj, false);
- response.setContentType("text/plain;charset=UTF-8");
- response.setHeader("Pragma", "No-cache");
- response.setHeader("Cache-Control", "no-cache");
- response.setDateHeader("Expires", 0);
- try {
- response.getWriter().write(s);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
三.控制层(前端请求的路径)
- package com.east.action;
- import java.util.ArrayList;
- import java.util.List;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Qualifier;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import com.east.biz.InformBiz;
- import com.east.entity.Inform;
- import com.east.util.JsonUtils;
- import com.east.util.ListObject;
- import com.east.util.ResponseUtils;
- import com.east.util.StatusCode;
- /*
- * 处理用户请求的控制器
- */
- @Controller
- public class InformAction {
- // 自动注入UserService
- @Autowired
- @Qualifier("informBiz")
- private InformBiz informBiz;
- /*
- * 获取指定id的公告
- */
- @RequestMapping(value = "/findById")
- public void findById(String info_id, HttpServletRequest request, HttpServletResponse response) {
- Integer id = Integer.parseInt(info_id);
- Inform inform = informBiz.findById(id);
- List<Inform> list = new ArrayList<Inform>();
- list.add(inform);
- ListObject listObject = new ListObject();
- listObject.setItems(list);
- listObject.setCode(StatusCode.CODE_SUCCESS);
- listObject.setMsg("访问成功");
- ResponseUtils.renderJson(response, JsonUtils.toJson(listObject));
- }
- }
四.到此,接口开发圆满完成,看看效果
接口的链接为:http://localhost:8098/InterfaceTest/findById?info_id=1