案例:
显示商品列表信息(注:数据直接在代码中模拟一下,没有通过访问数据库)
1.创建web工程
2.导入jar包、配置tomcat
(1,2步若没有操作过,请自行百度)
3.在web.xml中添加一个前端控制器(springmvc的核心过滤器)DispatcherServlet,然后需要初始化一个springMVC容器(具体解释请详看代码)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置springmvc前端控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--因为前端过滤器会默认加载/WEB-INF/{servlet-name}-servlet.xml,{servlet-name}是指起的文件名字-->
<!--而我们一般不会将配置文件放到WEB-INF下-->
<!--因此通过<init-param>标签初始化springmvc容器(即{servlet-name}-servlet.xml文件)-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--/*:过滤所有请求,包括jsp-->
<!--/: 过滤所有请求,不包括jsp-->
<!--*.action:过滤所有以.action结尾的请求-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
4.添加springmvc.xml(注:list.action是在访问时候的路径)
<?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.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!--传统方式:将Controller配置到springmvc.xml中-->
<bean name="/list.action" class="com.xiaokuo.springmvc.controller.ItemController"/>
</beans>
5.创建商品pojo
Items.java
package com.xiaokuo.springmvc.pojo;
import java.util.Date;
public class Items {
private Integer id;
private String name;
private Float price;
private String pic;
private Date createtime;
private String 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 == null ? null : name.trim();
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic == null ? null : pic.trim();
}
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 == null ? null : detail.trim();
}
@Override
public String toString() {
return "Items [id=" + id + ", name=" + name + ", price=" + price
+ ", pic=" + pic + ", createtime=" + createtime + ", detail="
+ detail + "]";
}
}
6.创建一个商品的Controller
/**
* 传统方式,实现Controller接口
*/
public class ItemController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
List<Items> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Items items = new Items();
items.setId(i);
items.setName("华为荣耀" + i);
items.setCreatetime(new Date());
items.setPrice((float) (1000 * i));
items.setDetail("华为,中华有为,国之骄傲!!!");
list.add(items);
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("itemList", list);//此句相当于将list放到request域中
modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");//相当于转发到item.jsp页面
return modelAndView;
}
}
7. 把Controller配置到springmvc.xml中(代码见第四步中)
8.创建jsp页面
<%@ 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>
9.tomcat测试
localhost:8080/springmvc_demo1/list.action
以上为传统方式,其工作原理:
请求访问list.action----->前端控制器DispatcherServlet拦截到,会加载springmvc.xml文件--------->在springmvc.xml文件中匹配到list.action,找到ItemController类,从而将数据传回itemList.jsp
但是传统的方式是有弊端的,在我们实际的开发中,Controller中不可能只写一个方法,若要写多个方法的话,而实现了Controller接口的ItemController类会默认自动加载handleRequest方法,那怎么让其他的访问路径也可以找到你所写的方法呢?这就要用到注解的方式:
重新写一个ItemController2类,不必实现Controller接口
此时,我们可以写多个方法,@RequestMapping就是你要访问的路径,会自动的找到相应的方法,从而返回到相应的jsp页面
/**
* 注解方式
*/
@Controller
public class ItemController2 {
@RequestMapping("huaweilist")
public ModelAndView huaWeiList(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
List<Items> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Items items = new Items();
items.setId(i);
items.setName("华为荣耀" + i);
items.setCreatetime(new Date());
items.setPrice((float) (1000 * i));
items.setDetail("华为,中华有为,国之骄傲!!!");
list.add(items);
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("itemList", list);//此句相当于将list放到request域中
modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");//相当于转发到item.jsp页面
return modelAndView;
}
@RequestMapping("iphonelist")//此处只需直接写list,不用写.action
public ModelAndView iphoneList(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
List<Items> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Items items = new Items();
items.setId(i);
items.setName("iphone" + i);
items.setCreatetime(new Date());
items.setPrice((float) (2000 * i));
items.setDetail("iPhone,垃圾东西,滚吊蛋的吧!!!");
list.add(items);
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("itemList", list);//此句相当于将list放到request域中
modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");//相当于转发到item.jsp页面
return modelAndView;
}
}
在springmvc.xml文件中可以将传统的方式注释掉,只需要开启注解扫描Controller所在的包即可
<!--传统方式:将Controller配置到springmvc.xml中-->
<!--<bean name="/list.action" class="com.xiaokuo.springmvc.controller.ItemController"/>-->
<!--注解方式,只需开启注解扫描-->
<context:component-scan base-package="com.xiaokuo.springmvc.controller"/>
tomcat测试:
localhost:8080/springmvc_demo1/huaweilist.action 会找到huaWeiList这个方法
localhost:8080/springmvc_demo1/iphonelist.action 会找到iphonelist方法