如何在Spring MVC中获取应用程序路径

时间:2015-12-06 06:01:45

标签: java spring spring-mvc

我正在一个spring mvc项目中工作,它上传一个图像并保存在需要在项目中使用的项目文件夹中。 图像文件成功进入控制器,但我无法将文件保存在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>

2 个答案:

答案 0 :(得分:2)

Shailendra所述,您可以使用ServletContext来获取上下文的真实路径。获取ServletContext的最简单方法是在控制器类中自动进行操作。例如:

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

        @Autowired
        ServletContext context;

    }

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

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

webcontent.path=/Users/hari/git/local_WebKinmel/WebKinmel/

在弹簧注射控制器中使用此属性:

@Controller
public class ControllerClass{

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

  ...
}

或者另一种方法是在config xml中传递属性:

<bean name="myController" class="ControllerClass">
  <property name="webcontentPath" value="${webcontent.path}"/>
</bean>

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

即可
<mvc:resources mapping="/web/**" location="file:${webcontent.path}"/>

例如,您将文件hello.png保存到/Users/hari/git/local_WebKinmel/WebKinmel/。它可以通过网址http://yourhost:8080/web/hello.png

访问

答案 1 :(得分:1)

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