SpringMVC

SpringMVC

      • 一. 什么是springMVC?
      • 二.SpringMVC环境搭建与配置
          • ①在Pom.xml添加SpringMVC依赖:
          • ②**用于JSP跳转页面时用的,项目中使用前后端分离的就不需要此依赖:**
          • ③ **在WEB-INF下添加spring-mvc.xml**
          • ④ **修改web.xml**
          • ⑥测试是否SpringMVC配置成功:
      • 三. 数据绑定和表单标签库
      • 四.SpringMVC工作原理,流程,注解

一. 什么是springMVC?

Spring Web MVC是一种基于Java的实现了MVC设计模式的、请求驱动类型的、轻量级Web框架。

二.SpringMVC环境搭建与配置

SpringMVC_第1张图片

①在Pom.xml添加SpringMVC依赖:
 
        org.springframework
        spring-webmvc
        ${spring.version}

用于JSP跳转页面时用的,项目中使用前后端分离的就不需要此依赖:

      
      
      
          jstl
          jstl
          1.2
      
      
          taglibs
          standard
          1.1.2
      
在WEB-INF下添加spring-mvc.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"
       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">
    <!-- 通过context:component-scan元素扫描指定包下的控制器-->
    <!--1) 扫描com.zking.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
    <!--<context:component-scan base-package="com.zking.zf"/>-->

    <!--1) use-dafault-filters="false"的情况下,根据表达式包含(include-filter)或排除(exclude-filter)指定包-->
    <context:component-scan base-package="com.zking.ssm" use-default-filters="false">
        <!--type掃描註解  expression指定的註解-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <!--<context:exclude-filter type="regex" expression=".+\.controller2\..*"/>-->
    </context:component-scan>

    <!--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="/WEB-INF/jsp/"/>
        <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
<?xml version="1.0" encoding="UTF-8"?>
<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>
  <!-- Spring和web项目集成start -->
  <!-- spring上下文配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml</param-value>
  </context-param>
  <!-- 读取Spring上下文的监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- Spring和web项目集成end -->

  <!-- 防止Spring内存溢出监听器 -->
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>

  <!-- 中文乱码处理 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>com.zking.ssm.util.EncodingFiter</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>/*
  

  
  
    SpringMVC
    org.springframework.web.servlet.DispatcherServlet
    
    
      contextConfigLocation
      /WEB-INF/spring-mvc.xml
    
    1
    
    true
  
  
    SpringMVC
    /
  

EncodingFiter:

package com.zking.ssm.util;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 中文乱码处理
 * 
 */
public class EncodingFiter implements Filter {

	private String encoding = "UTF-8";// 默认字符集

	public EncodingFiter() {
		super();
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		String method = request.getMethod();
		if (method.equalsIgnoreCase("get")) {
			Map<String, String[]> map = (Map<String, String[]>) request.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
			for (String[] values : map.values()) {
				for (int i = 0; i < values.length; i++) {
					values[i] = new String(values[i].getBytes("ISO-8859-1"), this.encoding);
				}
			}
		} else if (method.equalsIgnoreCase("post")) {
			request.setCharacterEncoding(this.encoding);
		}
		response.setContentType("text/html;charset=" + this.encoding);

		chain.doFilter(servletRequest, servletResponse);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
		if (null != s && !s.trim().equals("")) {
			this.encoding = s.trim();
		}
	}

}

注意事项:

  1. 在spring中有一个上下文而springmvc中也有一个上下文会起冲突使用需要改配置文件:
    spring-mybatis.xml:
    SpringMVC_第2张图片
    spring-mvc.xml:
    SpringMVC_第3张图片
  2. 在配置Spring-mvc.xml中注意URI加的prefix前缀,sufix后缀

SpringMVC_第4张图片

⑥测试是否SpringMVC配置成功:

在Controller层,创建HelloController类:
@RequestMapping("/xxx") 对应xxx.jsp页面

package com.zking.ssm.controller;

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

import javax.servlet.http.HttpServletRequest;

@Controller
public class HelloController {


    @RequestMapping("/hello")
    public String hello(HttpServletRequest rsq) {
        rsq.setAttribute("msg","springmvc配置成功");
        return "hello";
    }

    @RequestMapping("/hello1")
    public ModelAndView hello1(HttpServletRequest rsq) {
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("/hello1");
        modelAndView.addObject("msg1","springmvc正式搭建完毕配置成功");
        return modelAndView;
    }
}

SpringMVC_第5张图片
SpringMVC_第6张图片
SpringMVC_第7张图片

三. 数据绑定和表单标签库

BookList.jsp(主页面):

<%--
  Created by IntelliJ IDEA.
  User: zjjt
  Date: 2020/6/29
  Time: 19:21
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Book</title>
    <%@include file="/common/head.jsp" %>
    <script>
            function prom(name){
                alert(name);
            }
    </script>
</head>
<body>
        <div>
            <p onclick="prom(${msg})"></p>
        </div>
                <h1 style="text-align: center">小学生书店!欢迎您</h1>
                <%--<f:form modelAttribute="Book" action="${ctx}/Book/BookList" enctype="multipart/form-data" method="post">
                    书名:<input placeholder="请输入" name="bookName" />
                        <input type="submit" value="查询" />
                </f:form>--%>
                <f:form modelAttribute="Book" action="${ctx}/Book/BookList" method="post">
                    书名:<input name="bookName" />
                    <input type="submit" value="查询" />
                </f:form>
                <a href="${ctx}/Book/merge">增加</a>
                <table border="1" width="100%">
                    <tr>
                        <td>编号</td>
                        <td>名称</td>
                        <td>价格</td>
                        <td>操作</td>
                    </tr>
                <c:forEach items="${list}" var="b">
                    <tr>
                        <td>${b.bookId}</td>
                        <td>${b.bookName}</td>
                        <td>${b.price}</td>
                        <td>
                            <a href="${ctx}/Book/merge?bookid=${b.bookId}">修改</a>
                            <a href="${ctx}/Book/del/${b.bookId}">删除</a>
                        </td>
                    </tr>

                </c:forEach>
</body>
</html>

AddUpda.jsp:

<%--
  Created by IntelliJ IDEA.
  User: zjjt
  Date: 2020/6/30
  Time: 15:33
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>${bookname}</title>
    <%@include file="/common/head.jsp"%>
</head>
<body>
        <h1 style="text-align: center">${bookname}</h1>
        <f:form modelAttribute="Book" action="${ctx}${b.bookId==null?'/Book/add':'/Book/edit'}" method="post" cssStyle="text-align: center">
                    <input type="hidden" value="${b.bookId}" name="bookId">
                书名:<input value="${b.bookName}"  name="bookName"><br>
                价格:<input value="${b.price}" name="price"><br>
                <input type="submit" value="添交">
        </f:form>
        <div style="text-align: center">
            <button><a href="${ctx}/Book/BookList">返回</a></button>
        </div>

</body>
</html>

BookController:

package com.zking.ssm.controller;

import com.zking.ssm.model.Book;
import com.zking.ssm.service.IBookService;
import com.zking.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/Book")
public class BookController {

    @Autowired
    private IBookService bookService;

    @RequestMapping("/BookList")
    public String BookList(Book book, HttpServletRequest rsq){
        System.out.println(book.getBookName());
        PageBean pageBean = new PageBean();
        pageBean.setRequest(rsq);
        List<Book> list = bookService.list(book, pageBean);
        rsq.setAttribute("list",list);
        rsq.setAttribute("page",pageBean);
        return "BookList";
    }

    @RequestMapping("/add")
    public String add(Book book,HttpServletRequest rsq){
        int b = bookService.save(book);
        if(b==1){
            rsq.setAttribute("msg","添加成功");
        }else{
            rsq.setAttribute("msg","添加失败");
        }
        return "redirect:/Book/BookList";
    }
    @RequestMapping("/edit")
    public String edit(Book book,HttpServletRequest rsq){
        Book b = bookService.update(book);
        if(b!=null){
            rsq.setAttribute("msg","修改成功");
        }else{
            rsq.setAttribute("msg","修改失败");
        }
        return "redirect:/Book/BookList";
    }
    @RequestMapping("/del/{bookId}")
    public String del(@PathVariable("bookId") Integer bookId){
        bookService.del(bookId);
        return "redirect:/Book/BookList";
    }

    @RequestMapping("/merge")
    public String merge(Integer bookid, Book book, HttpServletRequest rsq){
        if (bookid==null){
            rsq.setAttribute("bookname","添加书本");
            return "porat/AddUpda";
        }
        rsq.setAttribute("bookname","修改书本");
        Book b = bookService.selectByPrimaryKey(bookid);
        System.out.println(b);
        rsq.setAttribute("b",b);
        return "porat/AddUpda";
    }
}

IBookService:

package com.zking.ssm.service;

import com.zking.ssm.model.Book;
import com.zking.ssm.util.PageBean;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional//注解事务管理器
@CacheConfig(cacheNames = "bookCheable")
public interface IBookService {
    //@CacheEvict(value = "bookCheable",allEntries = true)
    int del(Integer bookId);

    int save(Book record);

    @Transactional(readOnly = true)// @Transactional注解readOnly属性设置此方法只读
    //@Cacheable(value = "bookCheable",key = "#bookId+''")
    Book selectByPrimaryKey(Integer bookId);

    //@CachePut(value = "bookupdat",key = "#record.getBookId()+''")
    Book update(Book record);

    //@Transactional(readOnly = true)//@Transactional注解readOnly属性设置此方法只读
    //@Cacheable("bookCheable")//测试模式先关闭
    List<Book> list(Book book, PageBean pageBean);

    @Transactional(readOnly = true)
    List<Book> listBy(Book rebot);
}

BookMapper(持久层):

package com.zking.ssm.mapper;
	
	import com.zking.ssm.model.Book;
	import org.springframework.stereotype.Repository;
	
	import java.util.List;
	
	@Repository
	public interface BookMapper {
	    int deleteByPrimaryKey(Integer bookId);
	
	    int insert(Book record);
	
	    int insertSelective(Book record);
	
	    Book selectByPrimaryKey(Integer bookId);
	
	    int updateByPrimaryKeySelective(Book record);
	
	    int updateByPrimaryKey(Book record);
	
	    List<Book> list(Book book);
	
	    List<Book> listBy(Book rebot);
	}

实例结果(CRUD):
查询:
SpringMVC_第8张图片
添加书本信息
SpringMVC_第9张图片
修改书本信息
SpringMVC_第10张图片
删除书本信息:
SpringMVC_第11张图片
模糊查询根据书本名称
在这里插入图片描述
中途遇到的BUG:
1)@Cacheable(“xxxxxx”)
一旦在接口类的方法上注入就会去Redis缓存中找然后我就忘记打开Redis缓存了就遇到一直找缓存数据没找到就报出:
需要打开Redis缓存防止直接访问数据库,测试阶段可以先关闭@Cacheable注解缓存,@Cacheable用户开发完后打开;
SpringMVC_第12张图片
2)在模糊查询的时候BUG
@Transactional注解readOnly属性设置此方法只读
而模糊查需要从jsp页面获取值但是readOnly属性只读不能进行编辑所有一直会获取不到值;
SpringMVC_第13张图片

四.SpringMVC工作原理,流程,注解

SpringMVC处理请求的流程

  1.1 首先用户发送请求-->DispatherServlet
  1.2 DispatcherServlet-->HandlerMapping         Controller
  1.3 DispatcherServlet-->HandlerAdapter    
  1.4 HandlerAdapter-->处理器功能处理方法的调用  参数赋值
  1.5 ModelAndView的逻辑视图名-->ViewRecolver
  1.6 View-->渲染
  1.7 返回控制权给DispatcherServlet,由DispatcherServlet返回呼应给用户,流程结束

SpringMVC核心开发步骤

  2.1 DispatcherServlet在web.xml中的部署描述,从而拦截请求到springMVC
  2.2 HandlerMapping的配置,从而将请求映射到处理器
  2.3 HandlerAdapter的配置,从而支持多种类型的处理器
  2.4 处理器(页面控制器)的配置,从而刊行功能处理
  2.5 ViewResolver的配置,从而将逻辑视图名解析为具体的视图技术

SpringMVC的组件

  3.1 前端控制器(DispatcherServlet)
  3.2 请求到处理器映射(HandlerMapping)
  3.3 处理器适配器(HandlerAdapter)
  3.4 视图解析器(ViewResolver)
  3.5 处理器或页面控制器(Controller)
  3.6 验证器(Validator)
  3.6 命令对象(Command 请求参数绑定到的对象就叫命令对象)
  3.7 表单对象(Form Object提供给表单展示和提交到的对象就叫表单对象)

SpringMVC常用注解

@Controller 控制层:用于标识处理器类
@RestController 注解相当于@ResponseBody + @Controller合在一起的作用
@RequestMapping 请求到处理器功能方法的映射规则,可定义到类和方法
@RequestParam 请求参数到处理器功能处理方法的方法参数上的绑定
@ModelAttribute 请求参数到命令对象的绑定,,太麻烦几乎不用,不用直接保存到Model或ModelAndView中
@SessionAttributes 指定ModelMap中的哪些属性需要转存到session
@InitBinder 用于将请求参数转换到命令对象属性的对应类型,,日期格式到后台的数据转换
@RequestBody 用于目前比较流行的ajax开发的数据绑定(即提交数据的类型为json格式)
@ResponseBody 处理器功能处理方法的返回值作为响应体(通过HttpMessageConverter进行类型转换);
@RestController @RestController=@Controller+@ResponseBody

非常用注解

@CookieValue cookie数据到处理器功能处理方法的方法参数上的绑定
@RequestHeader 请求头(header)数据到处理器功能处理方法的方法参数上的绑定
@RequestBody 请求的body体的绑定(通过HttpMessageConverter进行类型转换);
@ResponseStatus 定义处理器功能处理方法/异常处理器返回的状态码和原因;
@ExceptionHandler 注解式声明异常处理器;
@PathVariable 请求URI中的模板变量部分到处理器功能处理方法的方法参数上的绑定,
@PostConstruct 初始化方法
@PreDestroy 销毁方法

你可能感兴趣的:(SpringMVC)