创建工程
首先创建一个maven的web,然后添加spring MVC的依赖和jstl的依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
配置前端控制器
在web.xml中添加如下配置
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
配置Spring MVC
编写配置文件springmvc.xml,在配置文件中开启注解扫描
<context:component-scan base-package="com.hw"></context:component-scan>
准备页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>查询商品列表</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/item/queryitem.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td><input type="submit" value="查询"/></td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
<td>商品名称</td>
<td>商品价格</td>
<td>生产日期</td>
<td>商品描述</td>
<td>操作</td>
</tr>
<c:forEach items="${itemList }" var="item">
<tr>
<td>${item.name }</td>
<td>${item.price }</td>
<td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
<td>${item.detail }</td>
<td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
准备实体类
public class Item {
private Integer id;
private String name;
private double price;
private Date createtime;
private String detail;
//get,set构造函数省略
}
在业务层准备模拟数据
@Service
public class ItemService {
static List<Item> items;
static {
items=new ArrayList<Item>();
for (int i = 0; i <10 ; i++) {
items.add(new Item(i,"name"+i,i*10.0,new Date(),"描述"+i));
}
}
public List getItems(){
return items;
}
}
编写controller
@Controller
public class ItemController {
@Resource
ItemService itemService;
@RequestMapping("/itemList")
public ModelAndView itemsList()throws Exception{
ModelAndView modelAndView=new ModelAndView();
List itemList=itemService.getItems();
modelAndView.addObject("itemList",itemList);
modelAndView.setViewName("static/itemList.jsp");
return modelAndView;
}
}
启动层序
启动应用程序,访问http://localhost:8080/itemList.do,正常显示数据就说明环境跑通了