使用SpringMVC教你五分钟写完增删改查

SSM---SpringMVC

    • 1、Springmvc简介及配置
    • 2、Springmvc之helloword实现
    • 3、Springmvc常用注解及返回值处理
    • 4、Springmvc静态资源处理

1、Springmvc简介及配置

①. 什么是springMVC?

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

②如何在项目中添加springmvc
添加相关依赖

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

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

tomcat-jsp-api

 <tomcat-jsp-api.version>8.0.47</tomcat-jsp-api.version>
 <dependency>
      <groupId>org.apache.tomcat</groupId>
      <artifactId>tomcat-jsp-api</artifactId>
      <version>${tomcat-jsp-api.version}</version>
    </dependency>

完整的pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.wyy</groupId>
  <artifactId>SSM</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>SSM Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version>

    <!--添加jar包依赖-->
    <!--1.spring 5.0.2.RELEASE相关-->
    <spring.version>5.0.2.RELEASE</spring.version>
    <!--2.mybatis相关-->
    <mybatis.version>3.4.5</mybatis.version>
    <!--mysql-->
    <mysql.version>5.1.44</mysql.version>
    <!--pagehelper分页jar依赖-->
    <pagehelper.version>5.1.2</pagehelper.version>
    <!--mybatis与spring集成jar依赖-->
    <mybatis.spring.version>1.3.1</mybatis.spring.version>
    <!--3.dbcp2连接池相关 druid-->
    <commons.dbcp2.version>2.1.1</commons.dbcp2.version>
    <commons.pool2.version>2.4.3</commons.pool2.version>
    <!--4.log日志相关-->
    <log4j2.version>2.9.1</log4j2.version>
    <!--5.其他-->
    <junit.version>4.12</junit.version>
    <servlet.version>4.0.0</servlet.version>
    <lombok.version>1.18.2</lombok.version>
    <!-- log4j2日志配置相关依赖 -->
    <log4j2.version>2.9.1</log4j2.version>
    <log4j2.disruptor.version>3.2.0</log4j2.disruptor.version>
    <slf4j.version>1.7.13</slf4j.version>
    <!-- redis与spring的整合依赖 -->
    <redis.version>2.9.0</redis.version>
    <redis.spring.version>1.7.1.RELEASE</redis.spring.version>
    <!-- jackson -->
    <jackson.version>2.9.3</jackson.version>
    <tomcat-jsp-api.version>8.0.47</tomcat-jsp-api.version>
  </properties>


  <dependencies>

    <!--1.spring相关-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!--2.mybatis相关-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!--mysql-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <!--pagehelper分页插件jar包依赖-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>${pagehelper.version}</version>
    </dependency>
    <!--mybatis与spring集成jar包依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatis.spring.version}</version>
    </dependency>

    <!--3.dbcp2连接池相关-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>${commons.dbcp2.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-pool2</artifactId>
      <version>${commons.pool2.version}</version>
    </dependency>

    <!--4.log日志相关依赖-->
    <!--核心log4j2jar包-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <!--web工程需要包含log4j-web,非web工程不需要-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-web</artifactId>
      <version>${log4j2.version}</version>
    </dependency>

    <!--5.其他-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>${servlet.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>${lombok.version}</version>
      <scope>provided</scope>
    </dependency>

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

    <!--mybatis与ehcache整合-->
    <dependency>
      <groupId>org.mybatis.caches</groupId>
      <artifactId>mybatis-ehcache</artifactId>
      <version>1.1.0</version>
    </dependency>

    <!--ehcache依赖-->
    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache</artifactId>
      <version>2.10.0</version>
    </dependency>

    <!-- log4j2日志相关依赖 -->
    <!-- log配置:Log4j2 + Slf4j -->
    <!-- slf4j核心包-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <version>${slf4j.version}</version>
      <scope>runtime</scope>
    </dependency>

    <!--核心log4j2jar包-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <!--用于与slf4j保持桥接-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <!--web工程需要包含log4j-web,非web工程不需要-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-web</artifactId>
      <version>${log4j2.version}</version>
      <scope>runtime</scope>
    </dependency>

    <!--需要使用log4j2的AsyncLogger需要包含disruptor-->
    <dependency>
      <groupId>com.lmax</groupId>
      <artifactId>disruptor</artifactId>
      <version>${log4j2.disruptor.version}</version>
    </dependency>

    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>${redis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>${redis.spring.version}</version>
    </dependency>

    <!-- jackson -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <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>
    <dependency>
      <groupId>org.apache.tomcat</groupId>
      <artifactId>tomcat-jsp-api</artifactId>
      <version>${tomcat-jsp-api.version}</version>
    </dependency>
  </dependencies>



  <build>
    <finalName>SSM</finalName>
    <resources>
      <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml
        
      
      
      
        src/main/resources
        
          *.properties
          *.xml
        
      
    

    
      
        
          org.apache.maven.plugins
          maven-compiler-plugin
          ${maven.compiler.plugin.version}
          
            ${maven.compiler.source}
            ${maven.compiler.target}
            ${project.build.sourceEncoding}
          
        
        
          org.mybatis.generator
          mybatis-generator-maven-plugin
          1.3.2
          
            
            
              mysql
              mysql-connector-java
              ${mysql.version}
            
          
          
            true
          
        

        
          maven-clean-plugin
          3.1.0
        
        
        
          maven-resources-plugin
          3.0.2
        
        
          maven-compiler-plugin
          3.8.0
        
        
          maven-surefire-plugin
          2.22.1
        
        
          maven-war-plugin
          3.2.2
        
        
          maven-install-plugin
          2.5.2
        
        
          maven-deploy-plugin
          2.8.2
        
      
    
  


修改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">

  <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和web项目集成end -->

  <!-- 防止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>/*
  

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



在WEB-INF下添加springmvc-servlet.xml(spring-mvc.xml)

使用SpringMVC教你五分钟写完增删改查_第1张图片

<?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及子子孙孙包,   gnhbgfbg下的控制器(扫描范围过大,耗时)-->
    <aop:aspectj-autoproxy/>
    <context:component-scan base-package="com.wyy"/>

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

2、Springmvc之helloword实现

第一个springMVC程序:HelloWorld
HelloController

package com.wyy.controller;

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

import javax.servlet.http.HttpServletRequest;

/**
 * @author 秃头集团王某
 * @company 秃头公司
 * @create 2019-09-28  10:43
 *
 * 关于结果集处理分五种情况
 * 1、转发到页面(webapp下)
 * 2、转发到action请求
 * 3、重定向页面(webapp下)
 * 4、重定向到action
 * 5、转发到web-inf下的页面
 */
@Controller
public class HelloController {

    @RequestMapping("hello")
    public String hello(HttpServletRequest request){
        request.setAttribute("msg","转发到页面的方式");
        return "hello";
    }

    /**
     * 重定向到action中
     * @param request
     * @return
     */
    @RequestMapping("hello2")
    public String redirectPage(HttpServletRequest request){
        request.setAttribute("msg","重定向到action的方式");
        return "redirect:hello";
    }

    /**
     * 重定向到页面
     * @param request
     * @return
     */
    @RequestMapping("hello3")
    public String redirectPage2(HttpServletRequest request){
        Object msg = request.getAttribute("msg");
        return "redirect:/hello.jsp";
    }

    @RequestMapping("hello4")
    public String forwardAction(HttpServletRequest request){
        request.setAttribute("msg","重定向到action的方式");
        return "forward:hello3";
    }

    @RequestMapping("hello5")
    public String forwardAction2(HttpServletRequest request){
        request.setAttribute("msg","转发访问安全页面");
        return "wyy";
    }
}

新建一个hello.jsp页面

<%--
  Created by IntelliJ IDEA.
  User: 20190614
  Date: 2019/9/28
  Time: 10:45
  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>
hello springmvc
<hr>
${msg}
</body>
</html>

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

相对应的文件
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="${b.bid }"><br>
		bname:<input type="text" name="bname" value="${b.bname }"><br>
		price:<input type="text" name="price" value="${b.price }"><br>
		<input type="submit" value="提交" onclick="doSubmit('${b.bid }');"><br>
	</form>
</body>
</html>

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 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>&nbsp;&nbsp;&nbsp;
					<button onclick="del(${b.bid });">删除</button>
				</td>
			</tr>
		</c:forEach>
	</table>
	<%--<z:page pageBean="${pageBean }"></z:page>--%>
</body>
</html>

z.tid

<?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>zking 1.1 core library</description>
  <display-name>zking core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>z</short-name>
  <uri>/zking</uri>

 <tag>
    <name>page</name>
    <tag-class>com.wyy.util.PageTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>pageBean</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
  
</taglib>

PageTag

package com.wyy.util;


import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


public class PageTag extends BodyTagSupport {

	private static final long serialVersionUID = 1L;
	private PageBean pageBean;
	public PageBean getPageBean() {
		return pageBean;
	}
	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}
	@Override
	public int doStartTag() throws JspException {
		JspWriter out = pageContext.getOut();
		try {
			out.print(toHTML());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return super.doStartTag();
	}
	private String toHTML() {
		StringBuffer sb = new StringBuffer();
		/*
		 * 拼接向后台提交数据的form表单
		 * 	注意:拼接的form表单中的page参数是变化的,所以不需要保留上一次请求的值
		 */
		sb.append("
"); sb.append(""); Map<String, String[]> parameterMap = pageBean.getMap(); if(parameterMap != null && parameterMap.size() > 0) { Set<Entry<String, String[]>> entrySet = parameterMap.entrySet(); for (Entry<String, String[]> entry : entrySet) { if(!"page".equals(entry.getKey())) { String[] values = entry.getValue(); for (String val : values) { sb.append(""); } } } } sb.append(""
); /* * 展示的分页条 */ sb.append("
"); sb.append("每页"+pageBean.getRows()+"条,共"+pageBean.getTotal()+"条,第"+pageBean.getPage()+"页,共"+pageBean.getMaxPage()+"页  首页  ); sb.append(" href='javascript:gotoPage("+pageBean.getPreivousPage()+")'>上一页  ); sb.append(" href='javascript:gotoPage("+pageBean.getNextPage()+")'>下一页  ); sb.append(" href='javascript:gotoPage("+pageBean.getMaxPage()+")'>尾页  ); sb.append(" id='skipPage'"); sb.append(" style='text-align: center; font-size: 12px; width: 50px;'>  ); sb.append(" href='javascript:skipPage()'>Go"); sb.append("
"
); /* * 给分页条添加与后台交互的js代码 */ sb.append(""); return sb.toString(); } }

进行增、删、查、改的编写

BookController

package com.wyy.controller;

import com.wyy.model.Book;
import com.wyy.service.BookService;
import com.wyy.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.List;
import java.util.Map;

/**
 * 自学@GetMapping @PostMapping
 * postman Swagger2
 * @author 秃头集团王某
 * @company 秃头公司
 * @create 2019-09-28  11:14
 */
@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;


    @RequestMapping("/list")
    public String list(Book book, HttpServletRequest request){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(request);
        List<Map> list = this.bookService.listPager(book, pageBean);
        request.setAttribute("bookList",list);
        request.setAttribute("pageBean",pageBean);
        return  "bookList";
    }

    @RequestMapping("/preSave")
    public String preSave(Book book, HttpServletRequest request){
        if(book.getBid()!=null){
            Book b = this.bookService.selectByPrimaryKey(book.getBid());
            request.setAttribute("b",b);
        }
        return  "bookEdit";
    }

    @RequestMapping("/add")
    public String add(Book book, HttpServletRequest request){
        this.bookService.insert(book);
        return  "redirect:/book/list";
    }

    @RequestMapping("/del/{bid}")
    public String del(@PathVariable(value = "bid") Integer bid, HttpServletRequest request){
        this.bookService.deleteByPrimaryKey(bid);
        return  "redirect:/book/list";
    }

    @RequestMapping("/edit")
    public String edit(Book book, HttpServletRequest request){
        this.bookService.updateByPrimaryKey(book);
        return  "redirect:/book/list";
    }
}

使用SpringMVC教你五分钟写完增删改查_第2张图片

4、Springmvc静态资源处理

导入一张图片进去
使用SpringMVC教你五分钟写完增删改查_第3张图片
记得把springmvc-servlet.xml

 <!--4) 单独处理图片、样式、js等资源 -->
    <!--<mvc:resources location="/css/" mapping="/css/**"/>-->
    <mvc:resources location="/static/" mapping="/static/**"/>
    <!--<mvc:resources location="/js/" mapping="/js/**"/>-->

Over…

你可能感兴趣的:(Mybatis,Spring,Maven)