SpringMVC—特点及Hello,SpringMVC
Spring MVC是Spring Framework的一部分,是基于Java实现MVC的轻量级Web框架。
查看官方文档:https://docs.spring.io/spring/docs/5.2.0.RELEASE/spring-framework-reference/web.html#spring-web
1、SpringMVC的特点:
轻量级,简单易学
高效,基于请求响应的MVC框架
与Spring兼容性好,无缝结合-
约定大于配置
功能强大,简介灵活
Spring的web框架围绕DispatcherServlet [ 调度Servlet ] 设计。
DispatcherServlet的作用是将请求分发到不同的处理器。从Spring 2.5开始,使用Java 5或者以上版本的用户可以采用基于注解形式进行开发,十分简洁;
正因为SpringMVC好 , 简单 , 便捷 , 易学 , 天生和Spring无缝集成(使用SpringIoC和Aop) , 使用约定优于配置 . 能够进行简单的junit测试 . 支持Restful风格 .异常处理 , 本地化 , 国际化 , 数据验证 , 类型转换 , 拦截器 等等......所以我们要学习 .
2、Hello,SpringMVC
首先看一下完整的目录结构
新建一个简单Maven项目,添加web支持!
在pom.xml文件中导入SpringMVC的依赖
配置web.xml,注册DispatcherServlet
注意点:
注意web.xml版本问题,要最新版!
注册DispatcherServlet
关联SpringMVC的配置文件
启动级别为1(让它在服务器启动的时候启动)
映射路径为 / 【不要用/*,会404】
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 的 配置文件!名称:springmvc-servlet.xml : [servletname]-servlet.xml说明,这里的名称要求是按照官方来的
xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
编写我们要操作业务HelloController,用注解!
@Controller是为了让Spring IOC容器初始化时自动扫描到;
@RequestMapping是为了映射请求路径,这里因为类与方法上都有映射所以访问时应该是/HelloController/hello;
方法中声明Model类型的参数是为了把Action中的数据带到视图中;
方法返回的结果是视图的名称hello,加上配置文件中的前后缀变成WEB-INF/jsp/hello.jsp。
package com.jiang.controller;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(Model model){
//我们要传的参数
model.addAttribute("msg","Hello,SpringMVC");
//后台的输出
System.out.println("aaa");
return "hello";
}
}
编写我们要跳转的页面hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
${msg}
配置Tomcat运行测试!
测试成功!