1、Springmvc简介及配置
-
什么是springMVC?
Spring Web MVC是一种基于Java的实现了MVC设计模式的、请求驱动类型的、轻量级Web框架。 -
SpringMVC处理请求的流程
2.1 首先用户发送请求–>DispatherServlet
2.2 DispatcherServlet–>HandlerMapping
2.3 DispatcherServlet–>HandlerAdapter
2.4 HandlerAdapter–>处理器功能处理方法的调用
2.5 ModelAndView的逻辑视图名–>ViewRecolver
2.6 View–>渲染
2.7 返回控制权给DispatcherServlet,由DispatcherServlet返回呼应给用户,流程结束 -
SpringMVC核心开发步骤
(官方)
3.1 DispatcherServlet在web.xml中的部署描述,从而拦截请求到springMVC
3.2 HandlerMapping的配置,从而将请求映射到处理器
3.3 HandlerAdapter的配置,从而支持多种类型的处理器
3.4 处理器(页面控制器)的配置,从而刊行功能处理
3.5 ViewResolver的配置,从而将逻辑视图名解析为具体的视图技术 -
SpringMVC的组件
4.1 前端控制器(DispatcherServlet)
4.2 请求到处理器映射(HandlerMapping)
4.3 处理器适配器(HandlerAdapter)
4.4 视图解析器(ViewResolver)
4.5 处理器或页面控制器(Controller)
4.6 验证器(Validator)
4.6 命令对象(Command 请求参数绑定到的对象就叫命令对象)
4.7 表单对象(Form Object提供给表单展示和提交到的对象就叫表单对象) -
如何在项目中添加springmvc
1、导入pom依赖
<!--1.spring 5.0.2.RELEASE相关-->
<spring.version>5.0.2.RELEASE</spring.version>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
********************** JSTL依赖 *************
缺少下面的这两个jar包会报java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config
原因:org.springframework.web.servlet.view.JstlView在视图解析时需要这二个jar包
<jstl.version>1.2</jstl.version>
<standard.version>1.1.2</standard.version>
<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(spring-mvc.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.hyf.ssm"/>
<!--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"/>
</bean>
<!--4) 单独处理图片、样式、js等资源 -->
<!--<mvc:resources location="/css/" mapping="/css/**"/>-->
<!--<mvc:resources location="/images/" mapping="/images/**"/>-->
<!--<mvc:resources location="/js/" mapping="/js/**"/>-->
</beans>
修改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 MVC servlet -->
<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>
<!-- 3、添加过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<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>
</web-app>
2、Springmvc之helloword实现
创建一个类:
HelloController
package com.hyf.ssm.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* @author xhy
* @site www.4399.com
* @company xxx公司
* @create 2019-11-22 16:36
*/
@Controller
public class HelloController {
// 简化版
@RequestMapping("/say1")
public String say(){
return "hello";
}
// 按照springmvc的流程进行编写
@RequestMapping("/say2")
public ModelAndView say2(){
ModelAndView mv = new ModelAndView();
mv.setViewName("/hello2");
mv.addObject("msg","第二次使用springmvc");
return mv;
}
}
hello.jsp
<%--
Created by IntelliJ IDEA.
User: 17628
Date: 2019/11/22
Time: 16:41
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
这是我第一个springmvc
</body>
</html>
hello2.jsp
<%--
Created by IntelliJ IDEA.
User: 17628
Date: 2019/11/22
Time: 16:41
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
结果:
springmvc框架的运作原理
- 浏览器请求:http://localhost:8080/say1(dispatcherservlet),request对象去处理这个url,可以获取到除去ip+port项目这一个固定的串,拿到/say1
- 在dispatcherservlet去寻找HandlerMapping
HandlerMapping:去整个spring上下文寻找了所有的被@requestMapping注解所标记的方法,如果@requestMapping注解里面有值/say1,那么就进行下一步 - 从前面已经能够获取到需要被调用的方法,那么dispatcherservlet就会寻找到handlerAdapt适配器来动态调用方法,然后就会出一个结果
- dispatcherservlet将结果封装成一个modelAndView对象,然后将其结果返回给viewReslove进行解析
- viewReslover解析完毕之后,会将对应的试图展现给用户
3、Springmvc crud
通过crud进行演示常用注解及返回值处理
需要自定义分页标签(PageTag),tld文件, 分页pageBean
这篇博客里面有:https://blog.csdn.net/wx1762813417/article/details/96798945
实体类,和dao 方法,代码自动生成。
BookController
package com.hyf.ssm.controller;
import com.hyf.ssm.model.Book;
import com.hyf.ssm.service.BookService;
import com.hyf.ssm.utils.PageBean;
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;
import java.util.Map;
/**
* @author xhy
* @site www.4399.com
* @company xxx公司
* @create 2019-11-23 1:13
*/
@Controller
@RequestMapping("/book") //指定命名空间 ...8080/boob/...
public class BookController {
@Autowired
private BookService bookService;
@RequestMapping("/list")
public String list(Book book, HttpServletRequest req){
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<Map> list = bookService.listPager(book, pageBean);
req.setAttribute("bookList",list);
req.setAttribute("pagebean",pageBean);
return "bookList";
}
@RequestMapping("/preSave")
public String preSave(Book book, HttpServletRequest req){
if(book == null || book.getBid() ==null || book.getBid() ==0){
return "bookEdit";
}
Book b = bookService.selectByPrimaryKey(book.getBid());
System.out.println(b);
req.setAttribute("b",b);
return "bookEdit";
}
@RequestMapping("/add")
public String add(Book book){
bookService.insertSelective(book);
return "redirect:/book/list";
}
@RequestMapping("/del/{bid}")
public String del(@PathVariable(value = "bid") Integer bid ){
bookService.deleteByPrimaryKey(bid);
return "redirect:/book/list";
}
@RequestMapping("/edit")
public String edit(Book book){
bookService.updateByPrimaryKeySelective(book);
return "redirect:/book/list";
}
}
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="/hyf" prefix="h"%>
<!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>
<h2>书籍</h2>
<br>
<form action="${pageContext.request.contextPath}/book/list" method="post">
<!--用户设置查询 一页20条记录 -->
<!-- <input type="hidden" name="rows" value="20"/> -->
<!--用户设置不分页 -->
<!-- <input type="hidden" name="pagination" value="false"/> -->
书名:<input type="text" name="bname"> <input type="submit"
value="确定">
</form>
<a href="${pageContext.request.contextPath}/book/preSave">增加</a>
<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>
<a href="${pageContext.request.contextPath}/book/preSave?bid=${b.bid}">修改</a>
<a href="${pageContext.request.contextPath}/book/del/${b.bid}">删除</a>
</td>
</tr>
</c:forEach>
</table>
<h:page pageBean="${pagebean}"></h: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>编辑页面</title>
</head>
<body>
<form action="${pageContext.request.contextPath}${b.bname == null ?'/book/add' : '/book/edit'}" method="post">
bid: <input type="text" value="${b.bid}" name="bid"/><br>
bname:<input type="text" value="${b.bname}" name="bname"/><br>
price:<input type="text" value="${b.price}" name="price"/><br>
<button type="submit">确认</button>
</form>
</body>
</html>
增加
注解解释:
@Controller:用于标识处理器类
@RequestMapping:请求到处理器功能方法的映射规则,可定义到类和方法
常用参数:value、method 。可将@RequestMapping标签定义到类名处窄化路径
返回值处理
package com.hyf.ssm.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* @author xhy
* @site www.4399.com
* @company xxx公司
* @create 2019-11-22 16:36
*
* spirngmvc 中五种返回值处理
* 转发3种
* 转发到安全web-inf 下
* 转发到根目录下
* 转发到requestMapping
*
* 重定向2
* 根目录
* requesMapper
*/
@Controller
public class HelloController {
@RequestMapping("/say1")
public String say(){
return "hello";
}
@RequestMapping("/say2")
public ModelAndView say2(){
ModelAndView mv = new ModelAndView();
mv.setViewName("/hello2");
mv.addObject("msg","第二次使用springmvc");
return mv;
}
//转发到安全web-inf 下
@RequestMapping("/req1")
public String req1(){
System.out.println("转发到安全目录WEB-INF下");
return "a";
}
// 转发到根目录
@RequestMapping("/req2")
public String req2(){
System.out.println("转发到根目录下");
return "forward:/b.jsp";
}
// 转发到根RequestMapper
@RequestMapping("/req3")
public String req3(){
System.out.println("转发到根目录下");
return "forward:/req2";
}
// 转发到根目录
@RequestMapping("/red1")
public String red1(){
System.out.println("red1");
return "redirect:/b.jsp";
}
// 转发 requesMapper
@RequestMapping("/red2")
public String red2(){
System.out.println("red2");
return "redirect:/red1";
}
}
4、静态资源处理
我们通网址访问这张图片是访问不到的应为没有配静态资源的映射
在springmvx-serlvet.xml这个配置文件中