页面url
http://www.jt.com/service/cart/update/num/562379/14
注意伪静态增强搜索引擎友好性的设置,不然报406(页面解析异常,页面要求解析的是.html页面,但是回传的数据是JSON串。这时解析发生报错)
/jt-web/src/main/webapp/WEB-INF/web.xml
<servlet-mapping>
<servlet-name>springmvc-web</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<!-- 防止springMVC框架返回json时和html冲突报 406 错误 -->
<servlet-mapping>
<servlet-name>springmvc-web</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>
当请求需要跳转页面时,后缀以.html结尾。当发起js/ajax请求时要以/service开始。上述配置是为了实现伪静态的操作,增强搜索引擎的友好性。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="jt-manage" version="2.5">
<display-name>jt-web</display-name>
<!-- 编码过滤器,以UTF8编码 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置SpringMVC -->
<servlet>
<servlet-name>springmvc-web</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定SpringMVC配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<description>
</description>
<display-name>ItemService</display-name>
<servlet-name>ItemService</servlet-name>
<servlet-class>com.jt.web.service.ItemService</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>springmvc-web</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<!-- 防止springMVC框架返回json时和html冲突报 406 错误 -->
<servlet-mapping>
<servlet-name>springmvc-web</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ItemService</servlet-name>
<url-pattern>/ItemService</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
var TTCart = {
load : function(){ // 加载购物车数据
},
itemNumChange : function(){
$(".increment").click(function(){//+
var _thisInput = $(this).siblings("input");
_thisInput.val(eval(_thisInput.val()) + 1);
$.post("/service/cart/update/num/"+_thisInput.attr("itemId")+"/"+_thisInput.val(),function(data){
TTCart.refreshTotalPrice();
});
});
$(".decrement").click(function(){//-
var _thisInput = $(this).siblings("input");
if(eval(_thisInput.val()) == 1){
return ;
}
_thisInput.val(eval(_thisInput.val()) - 1);
$.post("/service/cart/update/num/"+_thisInput.attr("itemId")+"/"+_thisInput.val(),function(data){
TTCart.refreshTotalPrice();
});
});
$(".quantity-form .quantity-text").rnumber(1);//限制只能输入数字
$(".quantity-form .quantity-text").change(function(){
var _thisInput = $(this);
$.post("/service/cart/update/num/"+_thisInput.attr("itemId")+"/"+_thisInput.val(),function(data){
TTCart.refreshTotalPrice();
});
});
},
refreshTotalPrice : function(){ //重新计算总价
var total = 0;
$(".quantity-form .quantity-text").each(function(i,e){
var _this = $(e);
//10000是为了处理小数的精度问题
total += (eval(_this.attr("itemPrice")) * 10000 * eval(_this.val())) / 10000;
});
$(".totalSkuPrice").html(new Number(total/100).toFixed(2)).priceFormat({ //价格格式化插件
prefix: '¥',
thousandsSeparator: ',',
centsLimit: 2
});
}
};
$(function(){
TTCart.load();
TTCart.itemNumChange();
});
@RequestMapping("/update/num/{itemId}/{num}")
@ResponseBody
public SysResult updateCartNum(@PathVariable Long itemId,@PathVariable Integer num){
try {
System.out.println("Map");
Cart cart=new Cart();
cart.setUserId(7L);
cart.setItemId(itemId);
cart.setNum(num);
cartService.updateCartNum(cart);
return SysResult.oK();
} catch (Exception e) {
e.printStackTrace();
}
return SysResult.build(201, "商品数量更新失败");
}
@ResponseBody不要遗忘
package com.jt.web.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jt.common.po.Cart;
import com.jt.common.vo.SysResult;
import com.jt.web.service.CartService;
@Controller
@RequestMapping("/cart")
public class CartController {
@Autowired
private CartService cartService;
// http://www.jt.com/cart/show.html
// 跳转购物车
@RequestMapping("/show")
public String show(Model model) {
// 根据userId查询购物车信息
Long userId = 7L;
List<Cart> cartList = cartService.findCartByUserId(userId);
// 将cartList数据保存到request对象中
model.addAttribute("cartList", cartList);
return "cart";
}
// http://www.jt.com/cart/add/562379.html
// 实现购物车新增
@RequestMapping("/add/{itemId}")
public String saveCart(@PathVariable Long itemId, Cart cart) {
Long userId = 7L;
cart.setItemId(itemId);
cart.setUserId(userId);
cartService.saveCart(cart);
// 重定向到购物车展现页面
return "redirect:/cart/show.html";
}
@RequestMapping("/update/num/{itemId}/{num}")
@ResponseBody
public SysResult updateCartNum(@PathVariable Long itemId,@PathVariable Integer num){
try {
System.out.println("Map");
Cart cart=new Cart();
cart.setUserId(7L);
cart.setItemId(itemId);
cart.setNum(num);
cartService.updateCartNum(cart);
return SysResult.oK();
} catch (Exception e) {
e.printStackTrace();
}
return SysResult.build(201, "商品数量更新失败");
}
}
package com.jt.web.service;
import java.util.List;
import com.jt.common.po.Cart;
public interface CartService {
List<Cart> findCartByUserId(Long userId);
void saveCart(Cart cart);
void updateCartNum(Cart cart);
}
package com.jt.web.service;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.common.po.Cart;
import com.jt.common.service.HttpClientService;
import com.jt.common.vo.SysResult;
@Service
public class CartServiceImpl implements CartService {
@Autowired
private HttpClientService httpClient;
private static ObjectMapper objectMapper=new ObjectMapper();
@SuppressWarnings("unchecked")
@Override
public List<Cart> findCartByUserId(Long userId) {
String url="http://cart.jt.com/cart/query/"+userId;
String resultJSON = httpClient.doGet(url);
List<Cart> cartList=null;
try {
SysResult sysResult = objectMapper.readValue(resultJSON, SysResult.class);
cartList=(List<Cart>) sysResult.getData();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException();
}
return cartList;
}
/**
* 如果一个对象中有100个属性问怎么传参数
*/
@Override
public void saveCart(Cart cart) {
String url="http://cart.jt.com/cart/save";
Map<String,String>params=new HashMap<String,String>();
params.put("userId",cart.getUserId()+"" );
params.put("itemId", cart.getItemId()+"");
params.put("itemTitle",cart.getItemTitle() );
params.put("itemImage",cart.getItemImage() );
params.put("itemPrice",cart.getItemPrice()+"" );
params.put("num", cart.getNum()+"");
httpClient.doPost(url, params);
//理论上需要对返回值进行处理,如果201报错,通过js告知用户,暂时没有实现
}
@Override
public void updateCartNum(Cart cart) {
//1.定义url
String url="http://cart.jt.com/cart/update/num";
//2.封装参数
try {
String cartJSON=objectMapper.writeValueAsString(cart);
Map<String,String> params=new HashMap<String,String>();
params.put("cartJSON", cartJSON);
httpClient.doGet(url,params);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
}