Hari Babu
Hari Babu

Reputation: 244

How to get Application path in spring MVC

I am working in a spring mvc project which uploads an image and saves in the project folder which needs to be used in the project as . The image file successfully comes to the controller but I'm unable to save the file in WebContent directory.

I would really appreciate help. Regards Hari.

Item class

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;
}

}

My controller goes like this.

@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; 

}

I want to save the image in WebContent directory rather than saving in '/Users/hari/git/local_WebKinmel/WebKinmel/WebContent/resources/upload/' directory

my servlet xml goes like this

<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>

Upvotes: 3

Views: 18617

Answers (2)

Ken Bekov
Ken Bekov

Reputation: 14015

As Shailendra said, you can use ServletContext to get real path of your context. Easiest way to get ServletContext is autoware it in controller class. For example:

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

        @Autowired
        ServletContext context;

    }

After that you can use context.getRealPath("/") in controller's methods to get root path of your app context. But, again, as Shailendra said, it will be better to use dedicated external folder instead of exploded war's folder.

I recommend you add property in you webkinmel.properties file with desired path:

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

And use this property in you controller with spring injection:

@Controller
public class ControllerClass{

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

  ...
}

Or another way is pass property in config xml:

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

To make folder accessible from browser, just add in you config xml:

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

For example you saved file hello.png to /Users/hari/git/local_WebKinmel/WebKinmel/. It will be accessible by url http://yourhost:8080/web/hello.png

Upvotes: 4

Shailendra
Shailendra

Reputation: 9102

You can use ServletContext#getRealPath() to get the path of the deployed/expanded WAR folder structure on the server file system. Although saving an uploaded image inside the exploded war is not recommended. You should instead be using a dedicated external folder.

Upvotes: 1

Related Questions