1.導入jar包前端
2.在web.xml中配置前端控制器
java
<!-- spring前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 加載配置文件 --> <!-- SpringMVC的配置文件的默認路徑是/WEB-INF/${servlet-name}-servlet.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <!-- 映射 設置全部以action結尾的請求進入SpringMVC--> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping>
3.建立配置文件和包結構
web
springmvc.xmlspring
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> </beans>
4.建立實體類和controller
spring-mvc
Item.java服務器
public class Item { // 商品id private int id; // 商品名稱 private String name; // 商品價格 private double price; // 商品建立時間 private Date createtime; // 商品描述 private String detail; set/get.... }
ItemController.javamvc
@Controller public class ItemController { @RequestMapping(value="/iteam/findAllItem.action") public ModelAndView findALLItem(){ ModelAndView mav = new ModelAndView(); //模擬查找數據 List<Item> list = new ArrayList<>(); list.add(new Item(1, "1華爲 榮耀8", 2399, new Date(), "質量好!1")); list.add(new Item(2, "2華爲 榮耀8", 2399, new Date(), "質量好!2")); list.add(new Item(3, "3華爲 榮耀8", 2399, new Date(), "質量好!3")); list.add(new Item(4, "4華爲 榮耀8", 2399, new Date(), "質量好!4")); list.add(new Item(5, "5華爲 榮耀8", 2399, new Date(), "質量好!5")); list.add(new Item(6, "6華爲 榮耀8", 2399, new Date(), "質量好!6")); mav.addObject("itemList", list); mav.setViewName("/WEB-INF/jsp/itemList.jsp"); return mav; } }
5.在springmvc.xml中添加掃描註釋
app
<context:component-scan base-package="com.springmvc.controller"/>
6.加載的服務器,啓動服務器測試
jsp