简介
什么是springMVC?
Spring Web MVC是一种基于Java的实现了MVC设计模式的、请求驱动类型的、轻量级Web框架。
SpringMVC处理请求的流程
假设发送请求http://localhost:8080/ssm/hello2
通过dispatcherservlet,拿到请求url并且处理获得/hello2
通过handlerMapping(处理器映射器),找到被@requestMapping注解所标记的类或者方法
通过handlerAdapter(处理器适配器),动态的实例化类,动态调用被标记的方法实现业务
调用方法后会产生结果,视图解析器internalResourceViewResolver会对结果进行渲染处理,然后将其返回给浏览器,用于页面展示
SpringMVC核心开发步骤
1、 DispatcherServlet在web.xml中的部署描述,从而拦截请求到springMVC
2 、HandlerMapping的配置,从而将请求映射到处理器
3、 HandlerAdapter的配置,从而支持多种类型的处理器
4、 处理器(页面控制器)的配置,从而刊行功能处理
5 、ViewResolver的配置,从而将逻辑视图名解析为具体的视图技术
SpringMVC的组件
1、 前端控制器(DispatcherServlet)
2 、请求到处理器映射(HandlerMapping)
3 、处理器适配器(HandlerAdapter)
4、 视图解析器(ViewResolver)
5、 处理器或页面控制器(Controller)
6、 验证器(Validator)
7 、命令对象(Command 请求参数绑定到的对象就叫命令对象)
8、 表单对象(Form Object提供给表单展示和提交到的对象就叫表单对象)
入门环境搭建
1、添加相关依赖(pom.xml)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
添加JSTL依赖案例需要用到,同时配置文件也需要依赖它
<!--版本号:-->
<jstl.version>1.2</jstl.version>
<standard.version>1.1.2</standard.version>
<tomcat-jsp-api.version>8.0.47</tomcat-jsp-api.version>
<!--依赖包:-->
<!-- 5.3、jstl、standard -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>${standard.version}</version>
</dependency>
<!-- 5.4、tomcat-jsp-api -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jsp-api</artifactId>
<version>${tomcat-jsp-api.version}</version>
</dependency>
2、在WEB-INF下创建springmvc-servlet.xml
2.1注解驱动扫描 扫描哪个包、开启注解驱动
2.2 配置本地资源视图解析器 internalResourceViewResolver
springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
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-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 通过context:component-scan元素扫描指定包下的控制器-->
<!--1) 扫描com.javaxl.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
<aop:aspectj-autoproxy/>
<context:component-scan base-package="com.liyingdong"/>
<!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
<!--两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,-->
<!--@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--3) ViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<!--<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>-->
<!--第二种情况-->
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--4) 单独处理图片、样式、js等资源 -->
<!--<mvc:resources location="/css/" mapping="/css/**"/>-->
<!--<mvc:resources location="/images/" mapping="/images/**"/>-->
<mvc:resources location="/static/" mapping="/static/**"/>
</beans>
3、配置web.xml
<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_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 读取Spring上下文的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- 中文乱码处理 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--web.xml 3.0的新特性,是否支持异步-->
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--SpringMVC-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--此参数可以不配置,默认值为:/WEB-INF/springmvc-servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!--web.xml 3.0的新特性,是否支持异步-->
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
第一个springMVC程序:HelloWorld
常用注解
@Controller
:用于标识处理器类
@RequestMapping
:请求到处理器功能方法的映射规则,可定义到类和方法
可将@RequestMapping标签定义到类名处窄化路径
@RequestParam:请求参数到处理器功能处理方法的方法参数上的绑定
常用参数:value、required、defaultValue
注:required设置成false的参数类型必须是引用类型,因为基本数据类型是不能为null的
@SessionAttributes:指定ModelMap中的哪些属性需要转存到session
常用参数:value、types
注1:必须放到class类名处
@RequestBody
(重要~~~~~):用于目前比较流行的ajax开发的数据绑定(即提交数据的类型为json格式)
相当于以前这一部分代码:
HelloController
package com.liyingdong.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
/**
* @author 李瀛东
* @site www.xiaomage.com
* @company xxx公司
* @create 2020-10-21 15:50
*/
@Controller
public class HelloController {
@ResponseBody
@RequestMapping("/hello2")
public String hello2(){
System.out.println("hello springmvc2你大爷!!");
return "hello";
}
@RequestMapping("/hello1")
public String hello1(){
System.out.println("hello springmvc1你大爷!!");
return "hello";
}
@ResponseBody
@RequestMapping("/hello3")
public Map hello3(){
System.out.println("map----");
Map map=new HashMap();
map.put("total",12);
map.put("rows","一串的数据");
return map;
}
/**
* 5种情况
* 1.转发到页面
* 2.转发到根路径下面的页面
* 3.转发到requestMapping下
* 4.重定向到dao根路径下的页面
* 5.重定向到requestMapping下
*/
@RequestMapping("/forward1")
public String forward1(){
System.out.println("进来forward");
return "aaa";
}
//不走视图解析器的情况
@RequestMapping("/forward2")
public String forward2(){
return "forward:/bbb.jsp";
}
@RequestMapping("/forward3")
public String forward3(){
return "forward:/forward1";
}
// 重定向到根路径下
@RequestMapping("/redirect1")
public String redirect1(){
return "redirect:/bbb.jsp";
}
@RequestMapping("/redirect2")
public String redirect2(){
return "redirect:/forward1";
}
}
hello1:
hello2:
hello3:
实现简单CURD
@PathVariable
:用于将请求 URL 中的模板变量映射到功能处理方法的参数上,即取出 uri 模板中的变量作为参数。
之前是实现Modedriver来进行传值的,现在不用了,只需要在方法里面加一个实体就ok了,前台传值只需要注意与实体的属性对应就没问题。
其实现原理是利用环绕通知中获取所有参数的那种方法+反射赋值实现的
。
案例所需要用到的:
BookController
package com.liyingdong.controller;
import com.liyingdong.model.Book;
import com.liyingdong.serivce.BookService;
import com.liyingdong.util.PageBean;
import com.liyingdong.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* @author 李瀛东
* @site www.xiaomage.com
* @company xxx公司
* @create 2020-10-22 9:46
*
*/
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
private BookService bookService;
@RequestMapping("/list")
public String list(Book book,HttpServletRequest req){
PageBean pageBean=new PageBean();
pageBean.setRequest(req);
List<Book> books=null;
if(book.getBname()!=null){
book.setBname(StringUtils.toLikeStr(book.getBname()));
books = this.bookService.MvclistPager(book, pageBean);
}
books = this.bookService.MvclistPager(book, pageBean);
req.setAttribute("bookList",books);
req.setAttribute("pageBean",pageBean);
return "bookList";
}
@RequestMapping("/preSave")
public String preSave(Book book,HttpServletRequest req){
if(book!=null && book.getBid()!=null && book.getBid()!=0){
Book b = this.bookService.selectByPrimaryKey(book.getBid());
req.setAttribute("book2",b);
}
return "bookEdit";
}
@RequestMapping("/add")
public String add(Book book,HttpServletRequest req){
this.bookService.insertSelective(book);
return "redirect:/book/list";
}
@RequestMapping("/edit")
public String edit(Book book,HttpServletRequest req){
this.bookService.updateByPrimaryKeySelective(book);
return "redirect:/book/list";
}
@RequestMapping("/del/{bid}")
public String del(@PathVariable("bid") Integer bid,HttpServletRequest req){
this.bookService.deleteByPrimaryKey(bid);
return "redirect:/book/list";
}
@RequestMapping("/del/{typeid}/{bid}")
public String xxx(@PathVariable("typeid") Integer typeid,@PathVariable("bid") Integer bid,HttpServletRequest req){
this.bookService.deleteByPrimaryKey(bid);
return "redirect:/book/list";
}
}
z.tld
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>liyingdong 1.1 core library</description>
<display-name>liyingdong core</display-name>
<tlib-version>1.1</tlib-version>
<short-name>z</short-name>
<uri>/liyingdong</uri>
<tag>
<name>page</name>
<tag-class>com.liyingdong.tag.PageTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>pageBean</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
bookList.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="/liyingdong" prefix="z" %>
<!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>
<script type="text/javascript">
function add(){
// window.location.href = "bookEdit.jsp";
window.location.href="${pageContext.request.contextPath}/book/preSave";
}
function update(bid){
window.location.href = "${pageContext.request.contextPath}/book/preSave?bid="+bid;
}
function del(bid){
window.location.href = "${pageContext.request.contextPath}/book/del/"+bid;
}
</script>
</head>
<body>
<form action="${pageContext.request.contextPath}/book/list"
method="post">
书名:<input type="text" name="bname"> <input type="submit"
value="确定">
</form>
<button onclick="add();">新增</button>
<table border="1" width="100%">
<tr>
<td>编号</td>
<td>名称</td>
<td>价格</td>
<td>操作</td>
</tr>
<c:forEach items="${bookList}" var="b">
<tr>
<td>${b.bid }</td>
<td>${b.bname }</td>
<td>${b.price }</td>
<td>
<button onclick="update(${b.bid });">修改</button>
<button onclick="del(${b.bid });">删除</button>
</td>
</tr>
</c:forEach>
</table>
<z:page pageBean="${pageBean }"></z:page>
</body>
</html>
bookEdit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
<script type="text/javascript">
function doSubmit(bid){
var bookForm = document.getElementById("bookForm");
if(bid){
//修改时候执行
<%--bookForm.action = '${pageContext.request.contextPath}/bookAction.action?methodName=update';--%>
bookForm.action = '${pageContext.request.contextPath}/book/edit';
}else{
//新增时候执行
bookForm.action = '${pageContext.request.contextPath}/book/add';
}
bookForm.submit();
}
</script>
</head>
<body>
<form id="bookForm" action="" method="post">
bid:<input type="text" name="bid" value="${book2.bid}"><br>
bname:<input type="text" name="bname" value="${book2.bname}"><br>
price:<input type="text" name="price" value="${book2.price}"><br>
<input type="submit" value="提交" onclick="doSubmit('${book2.bid}');"><br>
</form>
</body>
</html>
效果:
springmvc对静态资源的处理
正常来说我访问项目下这张图片是访问不到的会报错404,springmvc框架会将静态资源文件访问,当作一个request请求来处理,最终会找不到对应的资源文件
我们只需要在springmvc-servlet.xml中配置一个映射即可 访问到
如果你要映射js,和css文件也一样配置即可
<mvc:resources location="/static/" mapping="/static/**"/>
访问: