1. 处理器映射器注解配置
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
2. 处理器适配器注解配置
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />
3. 映射器与适配器必需配套使用
3.1. 如果映射器使用了推荐的RequestMappingHandlerMapping, 适配器也必需使用推荐的RequestMappingHandlerAdapter。
4. 注解驱动
<!-- 注解驱动配置, 代替映射器与适配器的单独配置, 同时支持json响应(推荐使用) -->
<mvc:annotation-driven />
5. 视图解析器
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置视图响应的前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 配置视图响应的后缀 -->
<property name="suffix" value=".jsp" />
</bean>
6. 例子
6.1. 新建一个名为SpringMVCAnnotation的Web工程, 同时拷入相关jar包
6.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;
}
}
6.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.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.lywgames.domain.Item;
@Controller
public class ItemAction {
@RequestMapping("itemList")
public ModelAndView findAllProducts() {
ModelAndView mav = new ModelAndView();
List<Item> itemList = new ArrayList<Item>();
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(), "曲面屏幕"));
//设置商品数据
mav.addObject("itemList", itemList);
//设置视图名字
mav.setViewName("itemList");
return mav;
}
}
6.4. 在src下, 编写springmvc.xml
6.5. 在web.xml里配置请求路径拦截、SpringMVC的前端控制器和加载SpringMVC的核心配置文件。
6.6. 编写index.jsp
6.7. 编写itemList.jsp
6.8. 运行项目
6.9. 点击查询所有商品