Java 如何在SpringMVC中获取应用程序路径

Java 如何在SpringMVC中获取应用程序路径,java,spring,spring-mvc,Java,Spring,Spring Mvc,我在一个SpringMVC项目中工作,该项目上传一个图像并保存在项目文件夹中,该文件夹需要在项目中使用。 图像文件成功到达控制器,但我无法将文件保存在WebContent目录中 我非常感谢你的帮助。 问候哈里 项目类别 public class Item extends WebKinmelObject { private String name; private double price; private String manufacturer; private String descripti

我在一个SpringMVC项目中工作,该项目上传一个图像并保存在项目文件夹中,该文件夹需要在项目中使用。 图像文件成功到达控制器,但我无法将文件保存在WebContent目录中

我非常感谢你的帮助。 问候哈里

项目类别

public class Item extends WebKinmelObject {
private String name;
private double price;
private String manufacturer;
private String description;
private String category;
private String imagePath;
private int quantity;
@Temporal(value=TemporalType.TIMESTAMP)
private Date addedDate;

public String getCategory() {
    return category;
}
public void setCategory(String category) {
    this.category = category;
}
public String getManufacturer() {
    return manufacturer;
}
public void setManufacturer(String manufacturer) {
    this.manufacturer = manufacturer;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
private MultipartFile file;
public MultipartFile getFile() {
    return file;
}
@Transient
public void setFile(MultipartFile file) {
    this.file = file;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public double getPrice() {
    return price;
}
public void setPrice(double price) {
    this.price = price;
}
public String getImagePath() {
    return imagePath;
}
public void setImagePath(String imagePath) {
    this.imagePath = imagePath;
}
public int getQuantity() {
    return quantity;
}
public void setQuantity(int quantity) {
    this.quantity = quantity;
}
public Date getAddedDate() {
    return addedDate;
}
public void setAddedDate(Date addedDate) {
    this.addedDate = addedDate;
}
}

我的控制器是这样的

@RequestMapping("admin/addItemAction")
public ModelAndView addItemAction(@ModelAttribute("item")Item formItem,HttpServletRequest req){
    MultipartFile uploadedFile=formItem.getFile();
    if(uploadedFile!=null){
        String fileName=uploadedFile.getOriginalFilename();
        try {
            //-- if uploaded file is empty
            if(fileName!=""){
                //String imagePath="/Users/hari/Documents/workspace/WebKinmel/WebContent/resources/upload/"+fileName;
                String imagePath="/Users/hari/git/local_WebKinmel/WebKinmel/WebContent/resources/upload/"+fileName;
                File f=new File(imagePath);
                formItem.setImagePath("/WebKinmel"+imagePath.substring(imagePath.indexOf("/resources")));
                formItem.setFile(null);
                FileOutputStream fos=new FileOutputStream(f);
                fos.write(uploadedFile.getBytes());
                fos.flush();
                fos.close();
                f.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("==>>The uploaded file cound not be saved");
        }
    }
    if(formItem.isPersisted()){

        // to be done if no image
        String fileName=uploadedFile.getOriginalFilename();
        if(fileName==""){
            Item i=(Item) WebKinmelServiceManager.find(formItem.getId(), Item.class);
            formItem.setImagePath(i.getImagePath());//transferring old image path if no image path found
        }
        Date date=new Date();
        formItem.setAddedDate(date);
        WebKinmelServiceManager.update(formItem);
    }
    else{
        Date date=new Date();
        formItem.setAddedDate(date);
        WebKinmelServiceManager.save(formItem);
    }
    System.out.println("object"+formItem+" saved");
    ModelAndView mav=new ModelAndView("admin/adminItem");
    addItemContent(mav);
    mav.addObject("recent", formItem);
    return mav; 

}
我想将图像保存在WebContent目录中,而不是保存在 “/Users/hari/git/local_WebKinmel/WebKinmel/WebContent/resources/upload/”目录

我的servlet xml如下所示

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans     
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />

<context:component-scan base-package="com.hari.controller" />

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView"></property>
    <property name="prefix">
        <value>/WEB-INF/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>

</bean>
<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

<bean name="webkinmelProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
            <value>classpath*:webkinmel.properties</value>
    </property>
</bean>

/WEB-INF/jsp/
.jsp
类路径*:webkinmel.properties

您可以使用获取服务器文件系统上已部署/扩展的WAR文件夹结构的路径。 虽然不建议在爆炸战争中保存上传的图像。您应该使用专用的外部文件夹。

如前所述,您可以使用ServletContext获取上下文的实际路径。获取ServletContext的最简单方法是在控制器类中自动创建它。例如:

    @Controller
    @RequestMapping("/")
    public class ExampleController{

        @Autowired
        ServletContext context;

    }
之后,您可以在控制器的方法中使用
context.getRealPath(“/”)
来获取应用程序上下文的根路径。但是,正如前面所说的,最好使用专用的外部文件夹,而不是爆炸战争的文件夹

我建议您在
webkinmel.properties
文件中添加具有所需路径的属性:

webcontent.path=/Users/hari/git/local_WebKinmel/WebKinmel/
并在带有弹簧注入的控制器中使用此属性:

@Controller
public class ControllerClass{

  @Value("${webcontent.path}")
  private String webcontentPath;

  ...
}
或者另一种方法是在配置xml中传递属性:

<bean name="myController" class="ControllerClass">
  <property name="webcontentPath" value="${webcontent.path}"/>
</bean>
<mvc:resources mapping="/web/**" location="file:${webcontent.path}"/>

要从浏览器访问文件夹,只需添加配置xml:

<bean name="myController" class="ControllerClass">
  <property name="webcontentPath" value="${webcontent.path}"/>
</bean>
<mvc:resources mapping="/web/**" location="file:${webcontent.path}"/>


例如,您将文件
hello.png
保存到
/Users/hari/git/local\u WebKinmel/WebKinmel/
。可通过url
http://yourhost:8080/web/hello.png

包甚至可能不会被分解。@chrylis-是的,尽管大多数容器都创建分解结构,但这是不可依赖的,所以在运行时不向war内容添加任何内容总是正确的。您的意思是==>ServletContext.getRealPath(),不要认为ServletContext类有getRealPath()方法,请详细说明:)请看我提供的链接中的文档。我可以在那里看到这个方法。谢谢shailendra,但是因为我使用eclipse进行开发,所以它给了我输出路径。“/Users/hari/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/WebKinmel/”相反,我需要类似于“/Users/hari/git/local_WebKinmel/WebKinmel/”的路径(任何想法:)?您能了解一下WebKinmel.properties文件吗。我对此不太熟悉。根据servlet.xml,在项目的类路径中有webkinmel.properties。此文件应包含名称=值的属性。您可以将任何属性添加到此文件中,并在控制器类中获取它。我只是在尝试,但尚未添加该文件。不知道如何实现itOkay我有了一些想法,可以为属性文件添加值。。但如何通过控制器访问