SSM编写http接口返回JSON格式数据

由于前后端数据分离的强烈需要,现在越来越需要接口化的开发,特别是服务器端的开发和移动端后台的开发,前后端的数据交互自然不能使用之前直接传数据的方式,于是JSON便成了最佳的选择,JSON的底层是HashMap,键值对的方式可以生成或解析JavaBean,既能满足要求,又不失开发效率.下面开发一个简单的获取某个id数据的接口,给访问的前端返回JSON数据.


代码:

一.获取数据库中的数据

#数据模型层

[java]  view plain  copy
  1. package com.east.entity;  
  2.   
  3. import java.io.Serializable;  
  4. import java.sql.Timestamp;  
  5.   
  6. public class Inform implements Serializable {  
  7.     private Integer info_id;  
  8.     private String  info_title;  
  9.     private String  info_content;  
  10.     private Timestamp info_time;  
  11.     public Integer getInfo_id() {  
  12.         return info_id;  
  13.     }  
  14.     public void setInfo_id(Integer info_id) {  
  15.         this.info_id = info_id;  
  16.     }  
  17.     public String getInfo_title() {  
  18.         return info_title;  
  19.     }  
  20.     public void setInfo_title(String info_title) {  
  21.         this.info_title = info_title;  
  22.     }  
  23.     public String getInfo_content() {  
  24.         return info_content;  
  25.     }  
  26.     public void setInfo_content(String info_content) {  
  27.         this.info_content = info_content;  
  28.     }  
  29.     public Timestamp getInfo_time() {  
  30.         return info_time;  
  31.     }  
  32.     public void setInfo_time(Timestamp info_time) {  
  33.         this.info_time = info_time;  
  34.     }  
  35.     @Override  
  36.     public String toString() {  
  37.         return "Inform [info_id=" + info_id + ", info_title=" + info_title + ", info_content=" + info_content  
  38.                 + ", info_time=" + info_time + "]";  
  39.     }  
  40.       
  41. }  

#数据访问层

[java]  view plain  copy
  1. package com.east.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.apache.ibatis.annotations.Delete;  
  6. import org.apache.ibatis.annotations.Insert;  
  7. import org.apache.ibatis.annotations.Options;  
  8. import org.apache.ibatis.annotations.Param;  
  9. import org.apache.ibatis.annotations.Select;  
  10.   
  11. import com.east.entity.Inform;  
  12.   
  13. public interface InformDao {  
  14.       
  15.     /* 
  16.      * 查询某个公告的信息 
  17.      */  
  18.     @Select("select * from inform where info_id = #{info_id}")  
  19.     Inform findById(Integer info_id);  
  20. }  

#业务逻辑层

[java]  view plain  copy
  1. package com.east.biz;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.stereotype.Service;  
  5. import org.springframework.transaction.annotation.Isolation;  
  6. import org.springframework.transaction.annotation.Propagation;  
  7. import org.springframework.transaction.annotation.Transactional;  
  8.   
  9. import com.east.dao.InformDao;  
  10. import com.east.entity.Inform;  
  11.   
  12. @Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT)  
  13. @Service("informBiz")  
  14. public class InformBiz {  
  15.     /* 
  16.      * 自动注入InformDao 
  17.      */  
  18.     @Autowired  
  19.     private InformDao informDao;  
  20.       
  21.     public Inform findById(Integer info_id){  
  22.         return informDao.findById(info_id);  
  23.     }  
  24. }  

二.JSON操作相关的对象类

[java]  view plain  copy
  1. package com.east.util;  
  2.   
  3. import java.util.Date;  
  4.   
  5. /* 
  6.  * 建立AbstractJSON(JSON数据的响应基类 ) 
  7.  */  
  8. public class AbstractJSON {  
  9.     private String code;                            //响应状态码   
  10.     private String msg;                             //响应状态描述    
  11.     private Long time = new Date().getTime();       //时间戳    
  12.   
  13.     public String getCode() {  
  14.         return code;  
  15.     }  
  16.   
  17.     public void setCode(String code) {  
  18.         this.code = code;  
  19.     }  
  20.   
  21.     public String getMsg() {  
  22.         return msg;  
  23.     }  
  24.   
  25.     public void setMsg(String msg) {  
  26.         this.msg = msg;  
  27.     }  
  28.   
  29.     public Long getTime() {  
  30.         return time;  
  31.     }  
  32.   
  33.     public void setTime(Long time) {  
  34.         this.time = time;  
  35.     }  
  36.   
  37.     public void setContent(String code, String msg) {  
  38.         this.code = code;  
  39.         this.msg = msg;  
  40.     }  
  41.   
  42.     public void setStatusObject(StatusObject statusObject) {  
  43.         this.code = statusObject.getCode();  
  44.         this.msg = statusObject.getMsg();  
  45.     }  
  46. }  

[java]  view plain  copy
  1. package com.east.util;  
  2.   
  3. import java.io.FileReader;  
  4. import java.io.FileWriter;  
  5. import java.io.IOException;  
  6. import java.io.StringWriter;  
  7.   
  8. import com.fasterxml.jackson.core.JsonFactory;  
  9. import com.fasterxml.jackson.core.JsonGenerator;  
  10. import com.fasterxml.jackson.core.JsonParseException;  
  11. import com.fasterxml.jackson.databind.JsonMappingException;  
  12. import com.fasterxml.jackson.databind.ObjectMapper;  
  13.   
  14. public class JsonWriter {  
  15.     private static ObjectMapper om = new ObjectMapper();  
  16.     private static JsonFactory jf = new JsonFactory();  
  17.   
  18.     public static <T> Object fromJson(String jsonAsString, Class<T> pojoClass) {  
  19.         try {  
  20.             return om.readValue(jsonAsString, pojoClass);  
  21.         } catch (JsonParseException e) {  
  22.             throw new IllegalStateException(e.getMessage(), e);  
  23.         } catch (JsonMappingException e) {  
  24.             throw new IllegalStateException(e.getMessage(), e);  
  25.         } catch (IOException e) {  
  26.             throw new IllegalStateException(e.getMessage(), e);  
  27.         }  
  28.     }  
  29.   
  30.     public static <T> Object fromJson(FileReader fr, Class<T> pojoClass) {  
  31.         try {  
  32.             return om.readValue(fr, pojoClass);  
  33.         } catch (JsonParseException e) {  
  34.             throw new IllegalStateException(e.getMessage(), e);  
  35.         } catch (JsonMappingException e) {  
  36.             throw new IllegalStateException(e.getMessage(), e);  
  37.         } catch (IOException e) {  
  38.             throw new IllegalStateException(e.getMessage(), e);  
  39.         }  
  40.     }  
  41.   
  42.     public static String toJson(Object pojo, boolean prettyPrint) {  
  43.         try {  
  44.             StringWriter sw = new StringWriter();  
  45.             JsonGenerator jg = jf.createGenerator(sw);  
  46.   
  47.             if (prettyPrint) {  
  48.                 jg.useDefaultPrettyPrinter();  
  49.             }  
  50.             om.writeValue(jg, pojo);  
  51.             return sw.toString();  
  52.         } catch (JsonParseException e) {  
  53.             throw new IllegalStateException(e.getMessage(), e);  
  54.         } catch (JsonMappingException e) {  
  55.             throw new IllegalStateException(e.getMessage(), e);  
  56.         } catch (IOException e) {  
  57.             throw new IllegalStateException(e.getMessage(), e);  
  58.         }  
  59.     }  
  60.   
  61.     public static void toJson(Object pojo, FileWriter fw, boolean prettyPrint) {  
  62.         try {  
  63.             JsonGenerator jg = jf.createGenerator(fw);  
  64.             if (prettyPrint) {  
  65.                 jg.useDefaultPrettyPrinter();  
  66.             }  
  67.             om.writeValue(jg, pojo);  
  68.         } catch (JsonParseException e) {  
  69.             throw new IllegalStateException(e.getMessage(), e);  
  70.         } catch (JsonMappingException e) {  
  71.             throw new IllegalStateException(e.getMessage(), e);  
  72.         } catch (IOException e) {  
  73.             throw new IllegalStateException(e.getMessage(), e);  
  74.         }  
  75.     }  
  76.   
  77.     public static String toJson(Object pojo) {  
  78.         return toJson(pojo, false);  
  79.     }  
  80.   
  81. }  

[java]  view plain  copy
  1. package com.east.util;  
  2.   
  3. import java.util.List;  
  4.   
  5. /* 
  6.  * 建立JSON数组类ListObject 
  7.  */  
  8. public class ListObject extends AbstractJSON {  
  9.   
  10.     private List<?> items;                       // 列表对象  
  11.   
  12.     public List<?> getItems() {  
  13.         return items;  
  14.     }  
  15.   
  16.     public void setItems(List<?> items) {  
  17.         this.items = items;  
  18.     }  
  19.       
  20. }  

[java]  view plain  copy
  1. package com.east.util;  
  2.   
  3. import com.fasterxml.jackson.databind.ObjectMapper;  
  4.   
  5. /* 
  6.  * JsonUtils生成json数据和解析json数据 
  7.  */  
  8. public class JsonUtils {  
  9.     static ObjectMapper objectMapper;  
  10.   
  11.     /* 
  12.      * 解析json 
  13.      */  
  14.     public static <T> T fromJson(String content, Class<T> valueType) {  
  15.         if (objectMapper == null) {  
  16.             objectMapper = new ObjectMapper();  
  17.         }  
  18.         try {  
  19.             return objectMapper.readValue(content, valueType);  
  20.         } catch (Exception e) {  
  21.             e.printStackTrace();  
  22.         }  
  23.         return null;  
  24.     }  
  25.   
  26.     /* 
  27.      * 生成json 
  28.      */  
  29.     public static String toJson(Object object) {  
  30.         if (objectMapper == null) {  
  31.             objectMapper = new ObjectMapper();  
  32.         }  
  33.         try {  
  34.             return objectMapper.writeValueAsString(object);  
  35.         } catch (Exception e) {  
  36.             e.printStackTrace();  
  37.         }  
  38.         return null;  
  39.     }  
  40. }  

[java]  view plain  copy
  1. package com.east.util;  
  2.   
  3. /* 
  4.  * 建立JSON对象类SingleObject 
  5.  */  
  6. public class SingleObject extends AbstractJSON {  
  7.     private Object object;  
  8.   
  9.     public Object getObject() {  
  10.         return object;  
  11.     }  
  12.   
  13.     public void setObject(Object object) {  
  14.         this.object = object;  
  15.     }   
  16.       
  17. }  

[java]  view plain  copy
  1. package com.east.util;  
  2.   
  3. /* 
  4.  * 定义状态码 
  5.  */  
  6. public class StatusCode {  
  7.   
  8.     public static String CODE_SUCCESS = "ok";          //访问成功   
  9.   
  10.     public static String CODE_ERROR = "0001";          //访问错误   
  11.   
  12.     public static String CODE_ERROR_PARAMETER = "0002";//参数错误  
  13.   
  14.     public static String CODE_ERROR_PROGRAM = "0003";  //程序异常  
  15.   
  16.     public static String CODE_ERROR_NO_LOGIN_OR_TIMEOUT = "0004";  //未登录或登录超时,请重新登录   
  17.   
  18.     public static String CODE_ERROR_EXIST_OPERATION = "0005";      //已操作  
  19.   
  20. }  

[java]  view plain  copy
  1. package com.east.util;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.servlet.http.HttpServletResponse;  
  6.   
  7. /* 
  8.  * 响应处理 
  9.  */  
  10. public class ResponseUtils {  
  11.   
  12.     /* 
  13.      * 返回json串 
  14.      */  
  15.     public static void renderJson(HttpServletResponse response, String text) {  
  16.         // System.out.print(text);  
  17.         render(response, "text/plain;charset=UTF-8", text);  
  18.     }  
  19.   
  20.     /* 
  21.      * 返回文本 
  22.      */  
  23.     public static void renderText(HttpServletResponse response, String text) {  
  24.         render(response, "text/plain;charset=UTF-8", text);  
  25.     }  
  26.   
  27.     /* 
  28.      * 发送内容,使用UTF-8编码 
  29.      */  
  30.     public static void render(HttpServletResponse response, String contentType, String text) {  
  31.         response.setContentType(contentType);  
  32.         response.setCharacterEncoding("utf-8");  
  33.         response.setHeader("Pragma""No-cache");  
  34.         response.setHeader("Cache-Control""no-cache");  
  35.         response.setDateHeader("Expires"0);  
  36.         try {  
  37.             response.getWriter().write(text);  
  38.         } catch (IOException e) {  
  39.         }  
  40.     }  
  41.       
  42.     /* 
  43.      * 页面异步回调返回Json 
  44.      */  
  45.     public static void outputJson(HttpServletResponse response, Object obj) {  
  46.         String s = JsonWriter.toJson(obj, false);  
  47.         response.setContentType("text/plain;charset=UTF-8");  
  48.         response.setHeader("Pragma""No-cache");  
  49.         response.setHeader("Cache-Control""no-cache");  
  50.         response.setDateHeader("Expires"0);  
  51.         try {  
  52.             response.getWriter().write(s);  
  53.         } catch (IOException e) {  
  54.             e.printStackTrace();  
  55.         }  
  56.     }  
  57. }  


三.控制层(前端请求的路径)

[java]  view plain  copy
  1. package com.east.action;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpServletResponse;  
  8.   
  9. import org.springframework.beans.factory.annotation.Autowired;  
  10. import org.springframework.beans.factory.annotation.Qualifier;  
  11. import org.springframework.stereotype.Controller;  
  12. import org.springframework.web.bind.annotation.RequestMapping;  
  13.   
  14. import com.east.biz.InformBiz;  
  15. import com.east.entity.Inform;  
  16. import com.east.util.JsonUtils;  
  17. import com.east.util.ListObject;  
  18. import com.east.util.ResponseUtils;  
  19. import com.east.util.StatusCode;  
  20.   
  21. /* 
  22.  * 处理用户请求的控制器 
  23.  */  
  24. @Controller  
  25. public class InformAction {  
  26.     // 自动注入UserService  
  27.     @Autowired  
  28.     @Qualifier("informBiz")  
  29.     private InformBiz informBiz;  
  30.   
  31.     /* 
  32.      * 获取指定id的公告 
  33.      */  
  34.     @RequestMapping(value = "/findById")  
  35.     public void findById(String info_id, HttpServletRequest request, HttpServletResponse response) {  
  36.         Integer id = Integer.parseInt(info_id);  
  37.         Inform inform = informBiz.findById(id);  
  38.         List<Inform> list = new ArrayList<Inform>();  
  39.         list.add(inform);  
  40.         ListObject listObject = new ListObject();  
  41.         listObject.setItems(list);  
  42.         listObject.setCode(StatusCode.CODE_SUCCESS);  
  43.         listObject.setMsg("访问成功");  
  44.         ResponseUtils.renderJson(response, JsonUtils.toJson(listObject));  
  45.     }  
  46. }  

四.到此,接口开发圆满完成,看看效果

    接口的链接为:http://localhost:8098/InterfaceTest/findById?info_id=1

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值