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

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

 
 
 

猜你喜欢

转载自blog.csdn.net/wh8_2011/article/details/80367262