Spring-MVC 3.0 Ошибка контроллера: HTTP Status 400 - PullRequest
0 голосов
/ 02 июля 2018

поскольку мое приложение работает на платформе Spring-MVC 3.0, в чем проблема с контроллером ниже, который получает ошибку «Http Status 400»?

package com.maskkk.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;


@Controller
public class FileDownloadController
{
@RequestMapping(value="/spring/download")
public void downloadPDFResource( HttpServletRequest request, 
                                  HttpServletResponse response, 
                                   @PathVariable("fileName") String fileName
                                   ) 
{
    //If user is not authorized - he should be thrown out from here itself

    //Authorized user will download the file
    //String dataDirectory = request.getServletContext().getRealPath("/WEB- 
    INF/downloads/pdf/");
    String dataDirectory = 
    request.getServletContext().getRealPath("fileupload");
    Path file = Paths.get(dataDirectory, fileName);
    if (Files.exists(file))
    {
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; 
          filename="+fileName);
        try
        {
            Files.copy(file, response.getOutputStream());
            response.getOutputStream().flush();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    }
    }

А мой web.xml ниже:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"  
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
  version="3.0">  
<welcome-file-list>
    <welcome-file>dashboard.jsp</welcome-file>
    <welcome-file>form.jsp</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

 <!-- log4j2-begin -->
 <listener>
     <listener- 
 class>org.apache.logging.log4j.web.Log4jServletContextListener</listener- 
  class>
 </listener>
 <filter>
     <filter-name>log4jServletFilter</filter-name>
     <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter- 
 class>
 </filter>
 <filter-mapping>
     <filter-name>log4jServletFilter</filter-name>
     <url-pattern>/*</url-pattern>
     <dispatcher>REQUEST</dispatcher>
     <dispatcher>FORWARD</dispatcher>
     <dispatcher>INCLUDE</dispatcher>
     <dispatcher>ERROR</dispatcher>
 </filter-mapping>
 <!-- log4j2-end -->
   <!-- 编码处理过滤器 -->

 <filter>

  <filter-name>encodingFilter</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>

   </filter>



   <filter-mapping>

   <filter-name>encodingFilter</filter-name>

   <url-pattern>*.do</url-pattern>

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

     <servlet-mapping>  
     <!-- 这里的servlet-name和上面的要一致. -->
    <servlet-name>spring</servlet-name>  
    <!-- 这里就是url的匹配规则, / 就是匹配所有 -->
    <url-pattern>*.do</url-pattern>  
    </servlet-mapping>  
    </web-app>

Данный контроллер предназначен для загрузки файла с веб-сайта. И этот контроллер не активен, когда я набираю "http://localhost:8888/Upload/spring/download.do" на URL и нажимаю ввод. Так в чем проблема? Любые предложения будут очень признательны!

1 Ответ

0 голосов
/ 02 июля 2018

Вы указываете переменную пути в своем коде Spring MVC с помощью @PathVariable("fileName") String fileName, и вам следует разрешить ее при вызове конечной точки. Структура вашей конечной точки должна выглядеть следующим образом /../spring/download/{fileName}, где {fileName} заменяет переменную в вашем URL. Действительный URL может выглядеть следующим образом: http://localhost:8888/Upload/spring/download/yourFileName. Измените метод конечной точки на следующий, если вам нужна эта переменная пути:

@RequestMapping(value="/Upload/spring/download/{fileName}")
public void downloadPDFResource( HttpServletRequest request, HttpServletResponse response, @PathVariable("fileName") String fileName) {
  // do your logic
}
...