目录
一、SpringMVC简介以及配置
①什么是SpringMVC?
Spring Web MVC是一种基于Java的实现了MVC设计模式的、请求驱动类型的、轻量级Web框架。
也有的称SpringMVC为:
1、视图层框架:
因为SpringMVC部分功能时向用户渲染展示数据的
2、控制层框架:
因为DispatcherServlet接受浏览器的任意请求然后转交请求给对应的适配器
②SpringMVC处理请求的流程
2.1 首先用户发送请求-->中央控制器DispatherServlet
2.2 中央控制器DispatherServlet-->处理器映射器HandlerMapping
2.3 DispatcherServlet-->处理器适配器HandlerAdapter
2.4 执行HandlerAdapter-->处理器功能处理方法的调用生成返回值ModelAndView
2.5 返回值ModelAndView-->ViewRecolver对其进行渲染得到视图View视图对象
2.6 返回控制权给DispatcherServlet,由DispatcherServlet返回视图对象给用户,流程结束
③SpringMVC的配置流程
3.1导入POM依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
补充一个pom依赖是JSTL依赖缺少下面的这两个jar包会报j
ava.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config
原因:org.springframework.web.servlet.view.JstlView在视图解析时需要这二个jar包
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
注意:在这里提醒大家,如果我们的pom文件出现问题的话明明导入了jar包,但是还是出现红色波浪的话如下图:
解决方式就是:英文状态下Shift+ctrl+F更改格式
3.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.zq.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>
在SpringMVC框架的配置文件中,基础功能包含为:
3.2.1扫描Base-package
定义Base-package
开启注解扫描
开启动态代理
3.2.2配置视图解析器
本地资源视图解析器
多功能视图解析器
3.3.3静态资源映射
3.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 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>
</web-app>
wen.xml包含的内容:
3.3.1SpringMVC与web容器的集成:Servlet ——>DispatherServlet
3.4 补充的开发技巧:
我们的配置文件在开发的过程中有很多,不可能所有的都放在resources中如下图:
我们在这里是可以使用技巧,创建一个类似于中间连接的配置文件,然后通过这个文件来连接到对应的配置文件,然后我们在别的地方调用的时候直接调用这个汇总了的配置文件,它会自动的连接到对应的文件:
applicationContext.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"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="applicationContext-mybatis.xml"></import>
</beans>
二、简单初步实现SpringMVC开发
我们用SpringMVC来初步试用一下跳转一个界面:
①创建一个Controller用来存放web层的方法和内容
package com.zq.ssm.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author张强
* @site www.zq.com
* @create 2022-08-17 0:10
*/
//被Contorller标记的类 会交给Spring进行管理
@Controller
public class HelloController {
// 自定义mvc:浏览器发送请求 http://localhost:8080/hello.action?methodName=hello
// springmvc:浏览器发送请求 http://localhost:8080/helloReq
@RequestMapping("/helloReq")
public String hello(){
System.out.println("helloe spreingMVC……");
return "hello";
}
}
②创建一个前端页面用来做测试展示
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/16
Time: 17:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Title</title>
</head>
<body>
SpringMVC 你好
${msg}
<hr>
${lst}
<c:forEach items="${lst}" var="l">
${l.bid}:${l.bname}<hr>
</c:forEach>
</body>
</html>
做完这两步,我们运行controller页面,然后我们在地址栏拼接上我们在controller中标记的@RequestMapping中的内容(/helloReq)即可实现页面跳转!
③补充知识:SpringMVC的返回值
在SpringMVC中的返回方式有两个:
3.1String
String的返回方式默认为转发直接获取这段字符串然后通过本地资源视图解析器找到对应的页面无需后缀,但是我们在增删改的时候使用重定向的 只需在该字符串前加上redirect
3.2ModelAndView
这种方式的话就是通过对象调用方法进行转发setViewName("跳转页面");也无需后缀。还可以带返回值参数:addObject("键","值");
三、SpringMVC实现CRUD
这里我们简单实现四个功能CRUD,页面美观度就不考虑了
①写一个controller
BookControlle:
package com.zq.ssm.controller;
import com.zq.ssm.biz.BookBiz;
import com.zq.ssm.model.Book;
import com.zq.ssm.util.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.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author张强
* @site www.zq.com
* @create 2022-08-17 11:49
*/
@Controller
@RequestMapping("/book")
public class BookControlle{
@Autowired
private BookBiz bookbiz;
@RequestMapping("/list")
public String hello(HttpServletRequest req){
System.out.println("helloe spreingMVC……");
PageBean pagebean = new PageBean();
pagebean.setRequest(req);
Map map = new HashMap();
String bname= req.getParameter("bname");
map.put("bname",bname);
List<Map> maps = this.bookbiz.listPager(map,pagebean);
req.setAttribute("lst",maps);
return "hello";
}
@RequestMapping("/add")
public String add(Book book){
this.bookbiz.insertSelective(book);
return "redirect:/book/list";
}
@RequestMapping("/edit")
public String edit(Book book){
this.bookbiz.updateByPrimaryKey(book);
return "redirect:/book/list";
}
@RequestMapping("/del/{bid}")
public String del(@PathVariable("bid") Integer bid){
this.bookbiz.deleteByPrimaryKey(bid);
return "redirect:/book/list";
}
}
这里就是四个方法,然后 对应的增删改在实现后重定向回到主界面(查询)
②写前端页面
index.jsp(这里的增删改都是死数据,大家可以灵活一点改一下成为表单就可以了)
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/16
Time: 21:52
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>
<a href="${pageContext.request.contextPath}/book/list?bname=圣墟">查询所有</a>
<a href="${pageContext.request.contextPath}/book/add?bid=2&bname=sb&price=9.9">增加</a>
<a href="${pageContext.request.contextPath}/book/edit?bid=2&bname=suibian&price=9.8">修改</a>
<a href="${pageContext.request.contextPath}/book/del/2">删除</a>
</body>
</html>
hello.jsp:(展示数据)
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/16
Time: 17:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Title</title>
</head>
<body>
SpringMVC 你好
${msg}
<hr>
${lst}
<c:forEach items="${lst}" var="l">
${l.bid}:${l.bname}<hr>
</c:forEach>
</body>
</html>