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

本文介绍如何在SSM框架中配置返回JSON数据的方法,包括添加必要的jar包、配置web.xml及springmvc.xml文件、编写mapper和服务层接口,以及在controller中实现具体的逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.搭建好ssm框架

添加将结果转为json数据返回的jar包

jackson-annotations-2.8.4.jar

jackson-core-2.8.4.jar

jackson-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添加接口实现代码:

@Override
public 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":"果汁营养好!"}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值