一,Springmvc简介及配置

1. 什么是springMVC?

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

Springmvc与struts相似,不同的是

1.struts配置的是过滤器,springMVC配置的是servlet

2.struts每写一个子控制器都需要在xml中配置,但是springMVC只需要配置一次

3.针对于结果的跳转,struts中需要额外配置,springMVC不需要

共同点:

1.web.xml进行核心类的配置

2.子控制器都需要交给框架来管理

SpringMVC处理请求的流程

1.首先用户发送请求----》DispatherServlet   找到 hangdlermapping使hangdlermapping拿到 

/hello字符串

2.HandlerAdapt 通过 /hello找到对应方法

3.方法被调用,return一个结果

4.结果会变成modelAndVie  通过 InternalResourceViewResolver实现这个过程返回到客户端

spring添删改查_spring添删改查

 

二、Springmvc之helloword实现

在pom中替换含有spring-context的那个dependency

<dependency> <groupId>org.springframework</groupId>
 <artifactId>spring-webmvc</artifactId>
 <version>${spring.version}</version>
 </dependency>

在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.ltf"/>扫描包,spring里面的注解默认扫描的是 mapper,dao,controler,但是spring管理的controler不会管理浏览器发送的请求,springmvc框架才会处理这个请求,因此springmvc框架要单独得去扫描com.ltf下面的包,再去子控制器找对应方法进行处理,提供请求地址进行关联
    <!--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>这就是区别于strus只需要配置一次的地方
    <!--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/spring-mvc.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>

在controller包下建立HelloController类

package com.ltf.controller;
  
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;
  
 @Controller
 public class HelloController {
     @RequestMapping("/hello")
     public String hello(){
         return "hello";
     }
 }

@Controller 表示交给spring进行管理

@RequestMapping("/hello")相当于struts-sy中的 Action标签的配置

建立jsp页面

package com.sjy.controller;
  
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;
  
 @Controller
 public class HelloController {
     @RequestMapping("/hello")
     public String hello(){
         return "hello";
     }
 }

配置项目

锤子旁边配置tomcat,点击编辑配置,点击+,如图选择

spring添删改查_spring添删改查_02

 配置tomcat路径

spring添删改查_java_03

 

spring添删改查_java_04

 第四个已经编译好了,运行起来较快 

spring添删改查_java_05

 选择浏览器和更新类和资源(修改页面内容自动更新)

spring添删改查_linq_06

 启动项目会报错

spring添删改查_spring添删改查_07

报错原因

  <!-- ********************** JSTL依赖 ********************** -->

      <!-- 缺少下面的这两个jar包会报java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config-->

      <!-- 原因:org.springframework.web.servlet.view.JstlView在视图解析时需要这二个jar包-->

前后端交互json则不需要

<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>

 重新启动项目

spring添删改查_linq_08

 

三、Springmvc常用注解及返回值处理

1.建立BookController类

package com.ltf.controller;
  
 import com.ltf.model.Book;
 import com.ltf.service.BookService;
 import com.ltf.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;
  
  
 @Controller
 @RequestMapping("/book")
 public class BookController {
     @Autowired
     private BookService bookService;
  
     @RequestMapping("/preSave")
     public String preSave(Book book, HttpServletRequest request){
         if(book.getBid() != null){
             Book b = this.bookService.selectByPrimaryKey(book.getBid());
             request.setAttribute("book2",b);
         }
  
         return "bookEdit";
     }
  
     @RequestMapping("/add")
     public String add(Book book){
         this.bookService.insert(book);
         return "redirect:/book/list";
     }
  
     @RequestMapping("/del/{bid}")
     public String del(@PathVariable(value = "bid") Integer bid){
         this.bookService.deleteByPrimaryKey(bid);
         return "redirect:/book/list";
     }
  
     @RequestMapping("/list")
     public String list(HttpServletRequest request,Book book){
         PageBean pageBean = new PageBean();
         pageBean.setRequest(request);
         Map map = new HashMap();
         map.put("bname","%圣墟%");
         List<Map> list = this.bookService.listPager(map, pageBean);
         request.setAttribute("bookList",list);
         request.setAttribute("pageBean",pageBean);
         return "bookList";
     }
  
     @RequestMapping("/edit")
     public String edit(Book book){
         this.bookService.updateByPrimaryKeySelective(book);
         return "redirect:/book/list";
     }
 }

@Controller :标识当前controller类交给spring进行管理
@RequestMapping:
①此注解标记在类上面,那么相当于struts中命名空间的概念sy/book.action
②此注解标记在方法上,仅代表浏览器访问地址
springMVC针对于结果的处理有四种形式: 

①转发到页面 :“hello”

②重定向到页面  :“redirect:hello”

③转发到子控制器 :“forward:/book/list”

④重定向到子控制器  :return “redirect:/book/list”

删除方法中 

@RequestMapping("/del/{bid}")和@PathVariable(value = "bid") Integer bid
第一个的pid要与第二个的pid一致,否则拿不到

@PathVariable将浏览器中最后的参数进行封装获取

2.建立查询和修改的页面

bookList

<%@ 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="/zking" 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 οnclick="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 οnclick="update(${b.bid });">修改</button>   
                     <button οnclick="del(${b.bid });">删除</button>
                 </td>
             </tr>
         </c:forEach>
     </table>
     <%--<z:page pageBean="${pageBean }"></z:page>--%>
 </body>
 </html>

 bookEdit

<%@ 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}/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="提交" οnclick="doSubmit('${book2.bid }');"><br>
     </form>
 </body>
 </html>

 运行结果如下  

spring添删改查_mvc_09

spring添删改查_java_10

四、Springmvc静态资源处理

把图片当成一个请求处理

需要在spring-mvc中进行配置

<mvc:resources location="/static/" mapping="/static/**"/>

spring添删改查_java_11