Java 如何在 spring mvc 控制器中获取 getServletContext()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26923907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get getServletContext() in spring mvc Controller
提问by Priyanka Shaju
I need to upload images in my project. How to get the upload path in SpringMVC. The path is;
我需要在我的项目中上传图片。SpringMVC中如何获取上传路径。路径是;
/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
三误
- This method must return a result of type ModelAndView
- The method setFileSizeMax(int) is undefined for the type ServletFileUpload
- The method getServletContext() is undefined for the type Homepage Controller
- 此方法必须返回 ModelAndView 类型的结果
- ServletFileUpload 类型的 setFileSizeMax(int) 方法未定义
- 对于主页控制器类型,方法 getServletContext() 未定义
采纳答案by Nirav Prajapati
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;
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
使用以下代码
ServletContext
在 SpringMVC 中自动装配对象@Autowired ServletContext context;
然后尝试执行您的代码,例如
String uploadPath = context.getRealPath("") + File.separator + UPLOAD_DIRECTORY;
你可以像这样在你的控制器中得到它;
private ServletContext context; public void setServletContext(ServletContext servletContext) { this.context = servletContext; }
但为此您的控制器必须实现
ServletContextAware
接口
回答by Priyanka Shaju
Try this:
尝试这个:
@Autowired
ServletContext servletContext;
回答by user3502676
This is just another alternative
这只是另一种选择
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServletContext()
回答by Arun Raaj
The parameters you passed or set to the ServletContext object, are stored into HttpServletRequest object, you can access them anywhere in application in following way:
您传递或设置给 ServletContext 对象的参数存储在 HttpServletRequest 对象中,您可以通过以下方式在应用程序的任何位置访问它们:
public void method(HttpServletRequest request){
String email=request.getServletContext().getInitParameter(“email”);
}