您的位置:首页 > Web前端 > JavaScript

ssm框架下开发RESTful json简单实例

2016-10-21 09:59 645 查看
1.搭建好ssm框架添加将结果转为json数据返回的jar包jackson-annotations-2.8.4.jarjackson-core-2.8.4.jarjackson-databind-2.8.4.jar如果不添加这3个jar包,会输出错误如下:java.lang.IllegalArgumentException: No converter found for return value of type web.xml修改:<url-pattern>/</url-pattern>springmvc.xml添加资源映射    <!-- 静态资源映射  -->    <mvc:resources location="/js/" mapping="/js/**" />    <mvc:resources location="/css/" mapping="/css/**" />    <mvc:resources location="/img/" mapping="/img/**" />    <mvc:resources location="/fonts/" mapping="/fonts/**" />2. 编写mapper和service接口以及实现类ItemsMapperCustom.xml添加:    <select id="findItemsById" parameterType="java.lang.Integer" resultType="com.yf.ssm.po.ItemsCustom">        select items.* from items        <where>            items.id=#{id}        </where>     </select>ItemsMapperCustom.java添加代码://根据id查询商品public ItemsCustom findItemsById(Integer id) throws Exception;ItemsService添加接口://查询商品public ItemsCustom findItemsById(Integer id) throws Exception;ItemsServiceImpl添加接口实现代码:@Overridepublic ItemsCustom findItemsById(Integer id) throws Exception {return itemsMapperCustom.findItemsById(id);}3. controller里面添加控制器映射代码:@RequestMapping("/itemsview/{id}")public @ResponseBody ItemsCustom findItemsById(@PathVariable("id") Integer id) throws Exception{ItemsCustom itemsCustom =  itemsService.findItemsById(id);return itemsCustom;}"/itemsview/{id}"这里的{id}传入到(@PathVariable("id") Integer id) 的id里面。如果有多个参数,例如增加name字段@RequestMapping("/itemsview/{id}/{name}")(@PathVariable("id") Integer id ,  @PathVariable("name") String diffname )return itemsCustom会经过@ResponseBody注解转换为json数据格式4. 测试,浏览器输入 http://localhost:8080/ssm/itemsview/1
{"id":1,"name":"果汁机","price":3000.0,"pic":null,"createtime":1422940972340,"detail":"果汁营养好!"}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: