根据商品id显示商品详情的SQL语句
SELECT * FROM t_product WHERE id=?
在ProductMapper接口中添加抽象方法
/**
* 根据商品id查询商品详情
* @param id 商品id
* @return 匹配的商品详情,如果没有匹配的数据则返回null
*/
Product findById(Integer id);
在ProductMapper.xml文件中配置findById(Integer id)方法的映射
如果商品数据不存在,应该抛出ProductNotFoundException,所以创建ProductNotFoundException异常类并使其继承ServiceException
/** 商品数据不存在的异常 */
public class ProductNotFoundException extends ServiceException {
/**重写ServiceException的所有构造方法*/
}
1.在业务层IProductService接口中添加findById(Integer id)抽象方法
/**
* 根据商品id查询商品详情
* @param id 商品id
* @return 匹配的商品详情,如果没有匹配的数据则返回null
*/
Product findById(Integer id);
2.在ProductServiceImpl类中,实现接口中的findById(Integer id)抽象方法
@Override
public Product findById(Integer id) {
Product product = productMapper.findById(id);
// 判断查询结果是否为null
if (product == null) {
throw new ProductNotFoundException("尝试访问的商品数据不存在");
}
// 将查询结果中的部分属性设置为null
product.setPriority(null);
product.setCreatedUser(null);
product.setCreatedTime(null);
product.setModifiedUser(null);
product.setModifiedTime(null);
return product;
}
在BaseController类中的handleException()方法中添加处理ProductNotFoundException的异常
else if (e instanceof ProductNotFoundException) {
result.setState(4006);
result.setMessage("访问的商品数据不存在的异常");
}
- /products/{id}/details
- Integer id
- GET
- JsonResult
在ProductController类中添加处理请求的getById()方法
@GetMapping("{id}/details")
public JsonResult getById(@PathVariable("id") Integer id) {
Product data = productService.findById(id);
return new JsonResult(OK, data);
}
1.首页将商品id发送给详情页后,详情页需要从url中裁取获得该id,实现方法在jquery-getUrlParam.js中(目前怎么实现裁取可以先不学),所以需要在product.html页面中导入该js文件,这里我在body标签内部的最后引入该js文件
jquery-getUrlParam.js
(function ($) {
$.getUrlParam = function (name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null)
return unescape(r[2]);
return null;
}
})(jQuery);
2.在product.html页面中body标签内部的最后添加获取当前商品详情的代码