1. Restful风格url上的参数通过{}占位符绑定
2. 占位符参数名与方法参数名不一致时, 通过@PathVariable绑定
3. 例子
3.1. 新建一个名为SpringMVCRestfull的Web工程, 拷入相关jar包
3.2. 新建一个Item.java的实体类
package com.lywgames.domain;
import java.io.Serializable;
import java.util.Date;
public class Item implements Serializable{
private static final long serialVersionUID = 1L;
// 商品id
private Integer id;
// 商品名称
private String name;
// 商品价格
private Double price;
// 商品创建时间
private Date createtime;
// 商品描述
private String detail;
public Item() { }
public Item(Integer id, String name, Double price, Date createtime, String detail) {
this.id = id;
this.name = name;
this.price = price;
this.createtime = createtime;
this.detail = detail;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
}
3.3. 新建一个ItemAction.java的处理器
package com.lywgames.web.action;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.lywgames.domain.Item;
@Controller
@RequestMapping("item")
public class ItemAction {
List<Item> itemList = new ArrayList<Item>();
public ItemAction() {
itemList.add(new Item(1, "冰箱", 1999.0, new Date(), "保鲜。"));
itemList.add(new Item(2, "电脑", 8888.0, new Date(), "网上冲浪"));
itemList.add(new Item(3, "洗衣机", 4000.0, new Date(), "从此不用手。"));
itemList.add(new Item(4, "空调", 2600.0, new Date(), "冬天制热, 夏天制冷。"));
itemList.add(new Item(5, "液晶电视", 20000.0, new Date(), "曲面屏幕"));
}
@RequestMapping(value="findAllProducts")
public ModelAndView findAllProducts() {
ModelAndView mav = new ModelAndView();
mav.addObject("itemList", itemList);
mav.setViewName("itemList");
return mav;
}
// Restful风格url上的参数通过{}占位符绑定
@RequestMapping(value="productDetail/{id}")
// 占位符参数名与方法参数名不一致时, 通过@PathVariable绑定
public ModelAndView productDetail(@PathVariable("id") Integer ids) {
ModelAndView mav = new ModelAndView();
mav.addObject("item", itemList.get(ids));
mav.setViewName("item");
return mav;
}
}
3.4. 在src目录下新建springmvc.xml配置
3.5. 修改web.xml
3.6. 编写index.jsp
3.7. 编写itemList.jsp
3.8. 编写item.jsp
3.9. 运行项目
3.10. 查询所有商品
3.11. 商品详情, 请求使用了Restfull风格