SpringMVC

案例:链接:https://pan.baidu.com/s/14xggiT0cej20LpHCZS6Usw
提取码:cslw

SpringMVC处理流程框架

步骤1:

在WebContent下新建一个index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>SpringMVC Test</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/showAllProduct.action">展示所有商品</a>
</body>
</html>

在WEN-INF下新建一个jsp文件夹,并在里面新建一个pro_list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>Insert title here</title>
</head>
<body>
    <table width="100%" border="1" cellspacing="0" >
        <tr>
            <td>序号</td>
            <td>商品名称</td>
            <td>商品价格</td>
            <td>操作</td>
        </tr>
        <c:forEach items="${proList}" var="pro" varStatus="vs">
            <tr>
                <td>${vs.count}</td>
                <td>${pro.name }</td>
                <td>${pro.price }</td>
                <td>编辑 | 删除</td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

步骤2:

在com.hello.pojo包下新建一个Product类

package com.hello.pojo;

import java.io.Serializable;
import java.util.Date;

public class Product implements Serializable{

    private static final long serialVersionUID = 1L;

    private String name;
    private Float price;
    public Product() {
        super();
    }
    public Product(String name, Float price) {
        super();
        this.name = name;
        this.price = price;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Float getPrice() {
        return price;
    }
    public void setPrice(Float price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Product [name=" + name + ", price=" + price "]";
    }   
}

步骤3:

在com.hello.controller包下新建一个ProductController类

package com.hello.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.hello.pojo.Product;

@Controller
public class ProductController{

    @RequestMapping("/showAllProduct")
    public ModelAndView showAllProduct() {
        List<Product> proList = new ArrayList<>();
        Product pro = new Product("娃哈哈", 2.5f);
        proList.add(pro);
        pro = new Product("旺仔", 6.5f);
        proList.add(pro);
        pro = new Product("力加", 2.5f);
        proList.add(pro);
        // 创建 ModelAndView 对象并返回
        ModelAndView mv= new ModelAndView();
        mv.addObject("proList", proList);
        mv.setViewName("pro_list");
        
        return mv;
    }   
}

@RequestMapping是Spring Web应用程序中最常被用到的注解之一。这个注解会将HTTP请求映射到MVC和REST控制器的处理方法上。

步骤4:

在src下新建一个配置文件springmvc.xml

<?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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        

    <!-- 开启注解扫描 -->
    <context:component-scan base-package="com.hello.controller"/>
    
    <!--(视图解析器?) 为了更方便指定视图的位置,可以配置视图的前缀和后缀 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
    <mvc:annotation-driven></mvc:annotation-driven>
    
</beans>

配置文件中的 <context:component-scan/>标签是用来扫描注解的,ProductController中的@RequestMapping需要扫描才能起作用;
然后配置文件中的bean是视图解析器,在ProductController中的

// 创建 ModelAndView 对象并返回
        ModelAndView mv= new ModelAndView();
        mv.addObject("proList", proList);
        mv.setViewName("pro_list");
        
        return mv;

return的时候会给"pro_list"加上一个前缀和后缀,然后才能找到对应的路径了(大概是这个意思,有什么不对后面再来改)

步骤5:

配置我们的web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>SpringMVC_test1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 配置 DispatcherServlet 前端控制器 -->
  <servlet>
    <servlet-name>springMVCDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <!-- 初始化 SpringMVC 配置文件 -->
    <init-param>
        <!-- contextConfigLocation 主要是让当前工程上下文主动加载指定的 xml 配置文件 -->
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    
    <!-- 配置 tomcat 启动的时候,也一同加载当前控制器 -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>springMVCDispatcherServlet</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
  
</web-app>

tomcat 启动的时候,也一同加载当前控制器

步骤6:

接下来就可以进行测试了,把项目部署到Tomcat上运行
我们跟着走一遍大概就能了解SpringMVC是怎么工作的了...
↓↓↓↓↓↓↓↓
启动Tomcat,web.xml文件中的控制器一同被加载,springmvc.xml文件被执行,ProductController类中的注解被扫描


案例运行截图

点击“展示所有商品”链接后,页面发送请求"${pageContext.request.contextPath }/showAllProduct.action"到服务器,找到web.xml中符合的servlet-mapping
image.png
然后找到对应的servlet
image.png
然后交给前端控制器执行相对应的请求映射方法。
ProductController类已经通注解@Controller注册为前端控制器
image.png
showAllProduct()方法也通过注解@RequestMapping注册为映射方法
image.png
然后该干嘛干嘛,搞完之后创建 ModelAndView 对象并返回
image.png

需要带什么就带走,return之后会给视图解析器解析,前面也提到了,视图解析器会帮加上我们设置的前缀和后缀,才能找到正确的路径。
image.png
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,928评论 6 509
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,748评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,282评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,065评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,101评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,855评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,521评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,414评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,931评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,053评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,191评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,873评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,529评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,074评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,188评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,491评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,173评论 2 357

推荐阅读更多精彩内容