SpringMVC(十四):SpringMVC 与表单提交(post/put/delete的用法);form属性设置encrypt='mutilpart/form-data'时,如何正确配置web.xml才能以put方式提交表单

SpringMVC 与表单提交(post/put/delete的用法)

为了迎合Restful风格,提供的接口可能会包含:put、delete提交方式。在springmvc中实现表单以put、delete方式提交时,需要使用HiddenHttpMethodFilter过滤器。该过滤器的实现原理,默认在form表单内部定义一个hidden隐藏的标签,默认需要标签名为:_method,hidden标签的value为put或delete;过滤器会接收_method的hidden标签的value,如果发现存在_method的标签,并且value为put或delete时,会重新包装一个请求,请求类型会设置为_method标签的value值。进而实现将post方式提交表单转化为Delete或Put请求。

实现form post表当以put或delete方式提交的步骤包含以下:

idea下创建一个pom.xml工程:

 创建完后,工程结构如下:

设置web.xml配置如下:

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>springmvcdemo</display-name>
    <welcome-file-list>
        <welcome-file>/index</welcome-file>
    </welcome-file-list>

    <!--结束后端数据输出到前端乱码问题-->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <!--可以通过配置覆盖默认'_method'值 -->
        <init-param>
            <param-name>methodParam</param-name>
            <param-value>_method</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>myAppServletName</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>myAppServletName</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

此时在WEB-INF下还需要新建一个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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--扫描所有的 spring包下的文件;-->
    <!--当然需要在spring配置文件里面配置一下自动扫描范围
    <context:component-scan base-package="*"/>
    *代表你想要扫描的那些包的目录所在位置。Spring 在容器初始化时将自动扫描 base-package 指定的包及其子包下的所有的.class文件,
    所有标注了 @Repository 的类都将被注册为 Spring Bean。
    -->
    <context:component-scan base-package="com.dx.test"/>
    <!--新增加的两个配置,这个是解决406问题的关键-->
    <!--mvc注解驱动(可代替注解适配器与注解映射器的配置),默认加载很多参数绑定方法(实际开发时使用)-->
    <context:annotation-config/>
    <mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> <property name="contentType" value="text/html;charset=UTF-8" /> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> </bean> <!--自己后加的,该BeanPostProcessor将自动对标注@Autowired的bean进行注入--> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"></bean> <bean id="restTemplate" class="org.springframework.web.client.RestTemplate"> <property name="messageConverters"> <list> <!--<ref bean="stringHttpMessageConverter"/>--> <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/> <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/> <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/> <bean class="org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter"/> <!-- <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> --> </list> </property> </bean> </beans>

配置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.dx.test</groupId>
    <artifactId>demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>demo 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>
        <!--Spring版本号-->
        <spring.version>5.2.0.RELEASE</spring.version>
        <!--jstl标签库-->
        <jstl.version>1.2</jstl.version>
        <standard.version>1.1.2</standard.version>
    </properties>

    <dependencies>
        <!-- servlet相关,在handler参数中中包含:HttpServletRequest request参数时,需要引入javax.servlet依赖
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
         -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>

        <!--form 设置为enctype="multipart/form-data",多文件上传,在applicationContext.xml中配置了bean multipartResolver时,需要依赖该包。-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>

        <!--spring单元测试依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>

        <!--springMVC核心包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--spring核心包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

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

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

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

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</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-tx</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-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--AOP begin-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.13</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.13</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.5</version>
        </dependency>
        <!--AOP end-->

        <!--json依赖-->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.5.2</version>
        </dependency>

        <!--jstl库-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>${standard.version}</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>demo</finalName>
        <plugins>
            <!-- 配置Tomcat插件 -->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <port>9090</port>
                    <path>/</path>
                    <uriEncoding>UTF-8</uriEncoding>
                    <server>tomcat7</server>
                </configuration>
            </plugin>
        </plugins>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            。。
        </pluginManagement>
    </build>
</project>

/WEB-INF/views/index.jsp内容如下:

<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

/WEB-INF/views/article/list.jsp内容如下:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!-- 屏蔽tomcat 自带的 EL表达式 -->
<%@ page isELIgnored="false" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>Spring MVC Demo</title>
</head>
<body>
 <h2>All Articles</h2>
 <table border="1">
     <tr>
         <th>Article Id</th>
         <th>Article Name</th>
     </tr>

     <c:forEach items="${articles}" var="article">
     <tr>
         <td>${article.id}</td>
         <td>${article.title}</td>
     </tr>
     </c:forEach>
 </table>
</body>
</html>

/WEB-INF/views/article/show.jsp内容如下:

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!-- 屏蔽tomcat 自带的 EL表达式 -->
<%@ page isELIgnored="false" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>Spring MVC Demo</title>
</head>
<body>
    <h2>Post方式提交:</h2>
    <form:form name="article" method="POST" action="update_with_post" modelAttribute="article">
        Id:<form:hidden path="id"/>
       Title: <form:input path="title" style="width:200px;"/><br/>
       Content: <form:input path="content" style="width:200px;"/><br/>
       <input type="submit" value="Submit" />
    </form:form>
    <form name="article" method="POST" action="update_with_post">
        Id:<input name="id" id="id" value="${article.id}"/><br/>
        Title:<input name="title" id="title" value="${article.title}"/><br/>
        Content:<input name="content" id="content" value="${article.content}"/><br/>
        <input type="submit" value="Submit" />
    </form>
    <h2>Post包含上传文件提交:</h2>
    <form:form name="article" method="POST" action="update_with_post_file" modelAttribute="article" enctype="multipart/form-data">
       Id:<form:hidden path="id"/>
      Title: <form:input path="title" style="width:200px;"/><br/>
      Content: <form:input path="content" style="width:200px;"/><br/>
      <input type="submit" value="Submit" />
    </form:form>
    <form name="article" method="POST" action="update_with_post_file" enctype="multipart/form-data">
       Id:<input name="id" id="id" value="${article.id}"/><br/>
       Title:<input name="title" id="title" value="${article.title}"/><br/>
       Content:<input name="content" id="content" value="${article.content}"/><br/>
       <input type="submit" value="Submit" />
    </form>

    <h2>Put方式提交:</h2>
    <form:form name="article" method="POST" action="update_with_put" modelAttribute="article">
        <input type="hidden" name="_method" value="PUT"/>
        Id:<form:hidden path="id"/>
       Title: <form:input path="title" style="width:200px;"/><br/>
       Content: <form:input path="content" style="width:200px;"/><br/>
       <input type="submit" value="Submit" />
    </form:form>
    <form name="article" method="POST" action="update_with_put">
        <input type="hidden" name="_method" value="PUT"/>
        Id:<input name="id" id="id" value="${article.id}"/><br/>
        Title:<input name="title" id="title" value="${article.title}"/><br/>
        Content:<input name="content" id="content" value="${article.content}"/><br/>
        <input type="submit" value="Submit" />
    </form>

    <h2>Put包含上传文件提交:</h2>
    <form:form name="article" method="POST" action="update_with_put2" modelAttribute="article" enctype="multipart/form-data">
        <input type="hidden" name="_method" value="PUT"/>
        Id:<form:hidden path="id"/>
       Title: <form:input path="title" style="width:200px;"/><br/>
       Content: <form:input path="content" style="width:200px;"/><br/>
       yourfile: <input type="file" name="file"/><br/>
       <input type="submit" value="Submit" />
    </form:form>
    <form method="POST" name="article" action="update_with_post1" enctype="multipart/form-data">
        Id:<input name="id" id="id" value="${article.id}"/><br/>
        Title:<input name="title" id="title" value="${article.title}"/><br/>
        Content:<input name="content" id="content" value="${article.content}"/><br/>
        yourfile: <input type="file" name="file"/><br/>
        <input type="submit" value="Submit" />
    </form>

</body>
</html>

com.dx.test.model.ArticleModel.java

package com.dx.test.model;

import java.io.Serializable;
import java.util.Date;

/**
 * 文章内容
 */
public class ArticleModel implements Serializable {
    private Long id;
    private Long categoryId;
    private String title;
    private String content;

    private Date createTime;
    private String createUser;
    private String createUserId;
    private Date modifyTime;
    private String modifyUser;
    private String modifyUserId;

    public ArticleModel() {
    }

    public ArticleModel(Long id, Long categoryId, String title, String content) {
        this.id = id;
        this.categoryId = categoryId;
        this.title = title;
        this.content = content;
    }

    。。。

    @Override
    public String toString() {
        return "ArticleModel{" +
                "id=" + id +
                ", categoryId=" + categoryId +
                ", title='" + title + '\'' +
                ", content='" + content + '\''
                '}';
    }
}

com.dx.test.controller.HomeController.java

package com.dx.test.controller;

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

@Controller
public class HomeController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        return "index";
    }
}

com.dx.test.controller.ArticleController.java

package com.dx.test.controller;

import com.dx.test.model.ArticleModel;
import com.dx.test.service.IArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.http.HTTPBinding;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Controller
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private IArticleService articleService;

    @GetMapping("/list")
    public String queryList(Model model, @RequestHeader(value = "userId", required = false) String userId) {
        List<ArticleModel> articleModelList = articleService.queryList();
        model.addAttribute("articles", articleModelList);
        return "article/list";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ModelAndView queryById(@PathVariable(value = "id", required = true) Long id) {
        ArticleModel articleModel = articleService.getById(id);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("article/show");
        mv.addObject("article", articleModel);
        return mv;
    }

    @RequestMapping(value = "/update_with_post", method = RequestMethod.POST)
    public String update_with_post(@ModelAttribute(value = "article") ArticleModel article) {
        System.out.println(article);
        return "index";
    }

    @RequestMapping(value = "/update_with_post_file", method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public String update_with_post_file(@ModelAttribute(value = "article") ArticleModel article, @RequestBody MultipartFile file, HttpServletRequest request) {
        System.out.println(article);
        System.out.println(file);
        String id = request.getParameter("id");
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        System.out.println(String.format("%s,%s,%s", id, title, content));

        return "index";
    }

    @RequestMapping(value = "/update_with_put", method = RequestMethod.PUT)
    public String update_with_put(@ModelAttribute(value = "article") ArticleModel article) {
        System.out.println(article);
        return "index";
    }

    @RequestMapping(value = "/update_with_put_file", method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public String update_with_put_file(@ModelAttribute(value = "article") ArticleModel article, @RequestBody MultipartFile file, HttpServletRequest request) {
        System.out.println(article);
        System.out.println(file);
        String id = request.getParameter("id");
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        System.out.println(String.format("%s,%s,%s", id, title, content));

        return "index";
    }
}

idea中配置安装SmartTomcat

给demo工程配置tomcat:

之后启动后可以从Console上打印信息,查看到端口,我这里端口是9090

1)Post(不含上传文件)方式提交

在http://localhost:9090/article/1页面中:

2)Post(包含上传文件)方式提交

在http://localhost:9090/article/1页面中:

3)Put(不含上传文件)方式提交

在http://localhost:9090/article/1页面中:

4)Put(包含上传文件)方式提交

在http://localhost:9090/article/1页面中:

form属性设置encrypt='mutilpart/form-data'时,如何正确配置web.xml才能以put方式提交表单

这问题涉及到ContextLoaderListener在Web.xml中配置与不配置的区别;

web.xml 中的 ContextLoaderListener 是干什么用的

猜你喜欢

转载自www.cnblogs.com/yy3b2007com/p/11780270.html