002_注解开发
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. 注解驅(qū)動(dòng)
<!-- 注解驅(qū)動(dòng)配置, 代替映射器與適配器的單獨(dú)配置, 同時(shí)支持json響應(yīng)(推薦使用) --> <mvc:annotation-driven />5. 視圖解析器
<!-- 配置視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><!-- 配置視圖響應(yīng)的前綴 --><property name="prefix" value="/WEB-INF/jsp/" /><!-- 配置視圖響應(yīng)的后綴 --><property name="suffix" value=".jsp" /> </bean>6. 例子
6.1. 新建一個(gè)名為SpringMVCAnnotation的Web工程, 同時(shí)拷入相關(guān)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;// 商品idprivate Integer id;// 商品名稱private String name;// 商品價(jià)格private Double price;// 商品創(chuàng)建時(shí)間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(), "網(wǎng)上沖浪"));itemList.add(new Item(3, "洗衣機(jī)", 4000.0, new Date(), "從此不用手。"));itemList.add(new Item(4, "空調(diào)", 2600.0, new Date(), "冬天制熱, 夏天制冷。"));itemList.add(new Item(5, "液晶電視", 20000.0, new Date(), "曲面屏幕"));//設(shè)置商品數(shù)據(jù)mav.addObject("itemList", itemList);//設(shè)置視圖名字mav.setViewName("itemList");return mav;} }6.4. 在src下, 編寫springmvc.xml
6.5. 在web.xml里配置請(qǐng)求路徑攔截、SpringMVC的前端控制器和加載SpringMVC的核心配置文件。
6.6. 編寫index.jsp
6.7. 編寫itemList.jsp
6.8. 運(yùn)行項(xiàng)目
6.9. 點(diǎn)擊查詢所有商品
總結(jié)
- 上一篇: 001_SpringMVC入门
- 下一篇: 003_Controller和Reque