1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > SSM编写http接口返回JSON格式数据

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

时间:2020-11-23 04:48:46

相关推荐

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

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

代码:

一.获取数据库中的数据

#数据模型层

[java]view plaincopypackagecom.east.entity;importjava.io.Serializable;importjava.sql.Timestamp;publicclassInformimplementsSerializable{privateIntegerinfo_id;privateStringinfo_title;privateStringinfo_content;privateTimestampinfo_time;publicIntegergetInfo_id(){returninfo_id;}publicvoidsetInfo_id(Integerinfo_id){this.info_id=info_id;}publicStringgetInfo_title(){returninfo_title;}publicvoidsetInfo_title(Stringinfo_title){this.info_title=info_title;}publicStringgetInfo_content(){returninfo_content;}publicvoidsetInfo_content(Stringinfo_content){this.info_content=info_content;}publicTimestampgetInfo_time(){returninfo_time;}publicvoidsetInfo_time(Timestampinfo_time){this.info_time=info_time;}@OverridepublicStringtoString(){return"Inform[info_id="+info_id+",info_title="+info_title+",info_content="+info_content+",info_time="+info_time+"]";}}

#数据访问层[java]view plaincopypackagecom.east.dao;importjava.util.List;importorg.apache.ibatis.annotations.Delete;importorg.apache.ibatis.annotations.Insert;importorg.apache.ibatis.annotations.Options;importorg.apache.ibatis.annotations.Param;importorg.apache.ibatis.annotations.Select;importcom.east.entity.Inform;publicinterfaceInformDao{/**查询某个公告的信息*/@Select("select*frominformwhereinfo_id=#{info_id}")InformfindById(Integerinfo_id);}

#业务逻辑层[java]view plaincopypackagecom.east.biz;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importorg.springframework.transaction.annotation.Isolation;importorg.springframework.transaction.annotation.Propagation;importorg.springframework.transaction.annotation.Transactional;importcom.east.dao.InformDao;importcom.east.entity.Inform;@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT)@Service("informBiz")publicclassInformBiz{/**自动注入InformDao*/@AutowiredprivateInformDaoinformDao;publicInformfindById(Integerinfo_id){returninformDao.findById(info_id);}}

二.JSON操作相关的对象类[java]view plaincopypackagecom.east.util;importjava.util.Date;/**建立AbstractJSON(JSON数据的响应基类)*/publicclassAbstractJSON{privateStringcode;//响应状态码privateStringmsg;//响应状态描述privateLongtime=newDate().getTime();//时间戳publicStringgetCode(){returncode;}publicvoidsetCode(Stringcode){this.code=code;}publicStringgetMsg(){returnmsg;}publicvoidsetMsg(Stringmsg){this.msg=msg;}publicLonggetTime(){returntime;}publicvoidsetTime(Longtime){this.time=time;}publicvoidsetContent(Stringcode,Stringmsg){this.code=code;this.msg=msg;}publicvoidsetStatusObject(StatusObjectstatusObject){this.code=statusObject.getCode();this.msg=statusObject.getMsg();}}

[java]view plaincopypackagecom.east.util;importjava.io.FileReader;importjava.io.FileWriter;importjava.io.IOException;importjava.io.StringWriter;importcom.fasterxml.jackson.core.JsonFactory;importcom.fasterxml.jackson.core.JsonGenerator;importcom.fasterxml.jackson.core.JsonParseException;importcom.fasterxml.jackson.databind.JsonMappingException;importcom.fasterxml.jackson.databind.ObjectMapper;publicclassJsonWriter{privatestaticObjectMapperom=newObjectMapper();privatestaticJsonFactoryjf=newJsonFactory();publicstatic<T>ObjectfromJson(StringjsonAsString,Class<T>pojoClass){try{returnom.readValue(jsonAsString,pojoClass);}catch(JsonParseExceptione){thrownewIllegalStateException(e.getMessage(),e);}catch(JsonMappingExceptione){thrownewIllegalStateException(e.getMessage(),e);}catch(IOExceptione){thrownewIllegalStateException(e.getMessage(),e);}}publicstatic<T>ObjectfromJson(FileReaderfr,Class<T>pojoClass){try{returnom.readValue(fr,pojoClass);}catch(JsonParseExceptione){thrownewIllegalStateException(e.getMessage(),e);}catch(JsonMappingExceptione){thrownewIllegalStateException(e.getMessage(),e);}catch(IOExceptione){thrownewIllegalStateException(e.getMessage(),e);}}publicstaticStringtoJson(Objectpojo,booleanprettyPrint){try{StringWritersw=newStringWriter();JsonGeneratorjg=jf.createGenerator(sw);if(prettyPrint){jg.useDefaultPrettyPrinter();}om.writeValue(jg,pojo);returnsw.toString();}catch(JsonParseExceptione){thrownewIllegalStateException(e.getMessage(),e);}catch(JsonMappingExceptione){thrownewIllegalStateException(e.getMessage(),e);}catch(IOExceptione){thrownewIllegalStateException(e.getMessage(),e);}}publicstaticvoidtoJson(Objectpojo,FileWriterfw,booleanprettyPrint){try{JsonGeneratorjg=jf.createGenerator(fw);if(prettyPrint){jg.useDefaultPrettyPrinter();}om.writeValue(jg,pojo);}catch(JsonParseExceptione){thrownewIllegalStateException(e.getMessage(),e);}catch(JsonMappingExceptione){thrownewIllegalStateException(e.getMessage(),e);}catch(IOExceptione){thrownewIllegalStateException(e.getMessage(),e);}}publicstaticStringtoJson(Objectpojo){returntoJson(pojo,false);}}

[java]view plaincopypackagecom.east.util;importjava.util.List;/**建立JSON数组类ListObject*/publicclassListObjectextendsAbstractJSON{privateList<?>items;//列表对象publicList<?>getItems(){returnitems;}publicvoidsetItems(List<?>items){this.items=items;}}

[java]view plaincopypackagecom.east.util;importcom.fasterxml.jackson.databind.ObjectMapper;/**JsonUtils生成json数据和解析json数据*/publicclassJsonUtils{staticObjectMapperobjectMapper;/**解析json*/publicstatic<T>TfromJson(Stringcontent,Class<T>valueType){if(objectMapper==null){objectMapper=newObjectMapper();}try{returnobjectMapper.readValue(content,valueType);}catch(Exceptione){e.printStackTrace();}returnnull;}/**生成json*/publicstaticStringtoJson(Objectobject){if(objectMapper==null){objectMapper=newObjectMapper();}try{returnobjectMapper.writeValueAsString(object);}catch(Exceptione){e.printStackTrace();}returnnull;}}

[java]view plaincopypackagecom.east.util;/**建立JSON对象类SingleObject*/publicclassSingleObjectextendsAbstractJSON{privateObjectobject;publicObjectgetObject(){returnobject;}publicvoidsetObject(Objectobject){this.object=object;}}

[java]view plaincopypackagecom.east.util;/**定义状态码*/publicclassStatusCode{publicstaticStringCODE_SUCCESS="ok";//访问成功publicstaticStringCODE_ERROR="0001";//访问错误publicstaticStringCODE_ERROR_PARAMETER="0002";//参数错误publicstaticStringCODE_ERROR_PROGRAM="0003";//程序异常publicstaticStringCODE_ERROR_NO_LOGIN_OR_TIMEOUT="0004";//未登录或登录超时,请重新登录publicstaticStringCODE_ERROR_EXIST_OPERATION="0005";//已操作}

[java]view plaincopypackagecom.east.util;importjava.io.IOException;importjavax.servlet.http.HttpServletResponse;/**响应处理*/publicclassResponseUtils{/**返回json串*/publicstaticvoidrenderJson(HttpServletResponseresponse,Stringtext){//System.out.print(text);render(response,"text/plain;charset=UTF-8",text);}/**返回文本*/publicstaticvoidrenderText(HttpServletResponseresponse,Stringtext){render(response,"text/plain;charset=UTF-8",text);}/**发送内容,使用UTF-8编码*/publicstaticvoidrender(HttpServletResponseresponse,StringcontentType,Stringtext){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(IOExceptione){}}/**页面异步回调返回Json*/publicstaticvoidoutputJson(HttpServletResponseresponse,Objectobj){Strings=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(IOExceptione){e.printStackTrace();}}}

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

[java]view plaincopypackagecom.east.action;importjava.util.ArrayList;importjava.util.List;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importcom.east.biz.InformBiz;importcom.east.entity.Inform;importcom.east.util.JsonUtils;importcom.east.util.ListObject;importcom.east.util.ResponseUtils;importcom.east.util.StatusCode;/**处理用户请求的控制器*/@ControllerpublicclassInformAction{//自动注入UserService@Autowired@Qualifier("informBiz")privateInformBizinformBiz;/**获取指定id的公告*/@RequestMapping(value="/findById")publicvoidfindById(Stringinfo_id,HttpServletRequestrequest,HttpServletResponseresponse){Integerid=Integer.parseInt(info_id);Informinform=informBiz.findById(id);List<Inform>list=newArrayList<Inform>();list.add(inform);ListObjectlistObject=newListObject();listObject.setItems(list);listObject.setCode(StatusCode.CODE_SUCCESS);listObject.setMsg("访问成功");ResponseUtils.renderJson(response,JsonUtils.toJson(listObject));}}

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

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。