如何在spring mvc Controller中获取getServletContext() [英] how to get getServletContext() in spring mvc Controller

查看:683
本文介绍了如何在spring mvc Controller中获取getServletContext()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的项目中上传图像。如何在SpringMVC中获取上传路径。
路径是;

  /home/cme/project/eclipse/workspace_12_11/.metadata/.plugins/org .eclipse.wst.server.core / tmp0 / wtpwebapps / fileUploadTester / upload 

以下错误; / p>

 方法getServletContext()对于HomePageController类型未定义


出现;

  String uploadPath = getServletContext .getRealPath()+ File.separator + UPLOAD_DIRECTORY; 

我的代码是

  public ModelAndView UploadPhoto(@ModelAttribute User user,HttpServletRequest request,HttpServletResponse response)throws IOException {
final String UPLOAD_DIRECTORY =upload;
final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

String value [] = new String [10];
int i = 0;

//检查请求实际是否包含上传文件
if(!ServletFileUpload.isMultipartContent(request)){
PrintWriter writer = response.getWriter();
writer.println(请求不包含上传数据);
writer.flush();
return; //这里是错误这个方法必须返回一个ModelAndView类型的结果
}

DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(THRESHOLD_SIZE);
factory.setRepository(new File(System.getProperty(java.io.tmpdir)));

ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE); // here error方法setFileSizeMax(int)对ServletFileUpload类型未定义
upload.setSizeMax(MAX_REQUEST_SIZE);
String uploadPath = getServletContext()。getRealPath()+ File.separator + UPLOAD_DIRECTORY; //这里错误getServletContext()的方法是未定义的类型为Homepage Controller
//创建目录(如果不存在)
文件uploadDir = new File(uploadPath);
if(!uploadDir.exists()){
uploadDir.mkdir();
}

try {
列表< FileItem> items = upload.parseRequest(request); // request is HttpServletRequest
for(FileItem item:items){
if(item.isFormField()){//文本字段等...
String fieldName = item.getFieldName( );
System.out.print(fieldname+ fieldName);
value [i] = item.getString();
System.out.print(from uploader+ value [i]);
i ++;
} else {
// String fileName = new File(item.getName())。getName();使用它来使用默认文件名
String name = value [0];
System.out.println(file uploader name+ name);
String filePath = uploadPath + File.separator + name;
System.out.println(filePath);
文件storeFile = new File(filePath);
try {
item.write(storeFile);
} catch(Exception ex){
}
}
}
System.out.println(uploaded successfully);
} catch(Exception ex){
System.out.println(error not uploaded);
}
返回新的ModelAndView(ChangePhoto);
}

三个错误


  1. 此方法必须返回ModelAndView类型的结果

  2. 方法setFileSizeMax(int)对ServletFileUpload类型未定义

  3. 方法getServletContext()对于首页控制器类型未定义


解决方案


  1. 使用下面的代码自动连接 SpringMVC中的ServletContext 对象

      @Autowired 
    ServletContext上下文;

    之后,尝试执行您的代码,如

      String uploadPath = context.getRealPath()+ File.separator + UPLOAD_DIRECTORY; 


  2. 你可以在你的控制器中得到它;

     私有ServletContext上下文; 

    public void setServletContext(ServletContext servletContext){
    this.context = servletContext;
    }

    但是,为此,您的控制器必须实现 ServletContextAware 界面



I need to upload images in my project. How to get the upload path in SpringMVC. The path is;

/home/cme/project/eclipse/workspace_12_11/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/fileUploadTester/upload

The following error;

The method getServletContext() is undefined for the type HomePageController

appears when I use this code;

String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

My code is

public ModelAndView UploadPhoto(@ModelAttribute User user, HttpServletRequest request, HttpServletResponse response) throws IOException {
 final String UPLOAD_DIRECTORY = "upload";
 final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
 final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
 final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

 String value[] = new String[10];
 int i = 0;

 // checks if the request actually contains upload file
 if (!ServletFileUpload.isMultipartContent(request)) {
  PrintWriter writer = response.getWriter();
  writer.println("Request does not contain upload data");
  writer.flush();
  return; //here is error This method must return a result of type ModelAndView
 }

 DiskFileItemFactory factory = new DiskFileItemFactory();
 factory.setSizeThreshold(THRESHOLD_SIZE);
 factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

 ServletFileUpload upload = new ServletFileUpload(factory);
 upload.setFileSizeMax(MAX_FILE_SIZE); //here error The method setFileSizeMax(int) is undefined for the type ServletFileUpload
 upload.setSizeMax(MAX_REQUEST_SIZE);
 String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; // here error The method getServletContext() is undefined for the type Homepage Controller
 // creates the directory if it does not exist
 File uploadDir = new File(uploadPath);
 if (!uploadDir.exists()) {
  uploadDir.mkdir();
 }

 try {
  List < FileItem > items = upload.parseRequest(request); // request is HttpServletRequest
  for (FileItem item: items) {
   if (item.isFormField()) { // text fields, etc...
    String fieldName = item.getFieldName();
    System.out.print("fieldname" + fieldName);
    value[i] = item.getString();
    System.out.print("from uploader" + value[i]);
    i++;
   } else {
    //String fileName=new File(item.getName()).getName();   Use this to use default file name
    String name = value[0];
    System.out.println("file uploader name" + name);
    String filePath = uploadPath + File.separator + name;
    System.out.println(filePath);
    File storeFile = new File(filePath);
    try {
     item.write(storeFile);
    } catch (Exception ex) {
    }
   }
  }
  System.out.println("uploaded successfully");
 } catch (Exception ex) {
  System.out.println("error not uploaded");
 }
 return new ModelAndView("ChangePhoto");
}

Three error

  1. This method must return a result of type ModelAndView
  2. The method setFileSizeMax(int) is undefined for the type ServletFileUpload
  3. The method getServletContext() is undefined for the type Homepage Controller

解决方案

  1. Use below code to autowire ServletContext object in SpringMVC

    @Autowired
    ServletContext context; 
    

    and after that try to execute your code like

    String uploadPath = context.getRealPath("") + File.separator + UPLOAD_DIRECTORY;
    

  2. You can get it in your controller like this;

    private ServletContext context;
    
    public void setServletContext(ServletContext servletContext) {
        this.context = servletContext;
    }
    

    but for this your controller must implement ServletContextAware interface

这篇关于如何在spring mvc Controller中获取getServletContext()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆