Main Tutorials

The method getRealPath(String) from the type ServletRequest is deprecated

See following example to get the real server file path via servletRequest.getRealPath("/"). However, warning is prompt and complained that this method is deprecated.


import javax.servlet.http.HttpServletRequest;

public class DisplayAction  {

	private HttpServletRequest servletRequest;
	
	public String execute() {	
		//The method getRealPath(String) from the type ServletRequest is deprecated 
		String filePath = servletRequest.getRealPath("/");
	}
	
	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		this.servletRequest = arg0;
	}

}

Instead, you should use servletRequest.getSession().getServletContext().getRealPath("/") (refer to the end of the reference site for detail). See updated example again.


import javax.servlet.http.HttpServletRequest;

public class DisplayAction  {

	private HttpServletRequest servletRequest;
	
	public String execute() {	
		servletRequest.getSession().getServletContext().getRealPath("/");
	}
	
	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		this.servletRequest = arg0;
	}

}

Reference

  1. JavaEE ServletRequest#getRealPath documentation

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
lakshman
11 years ago

nice it worked for me..

Nameera Shaikh
2 years ago

was really helpful 🙂

medo gado
10 years ago

how to get full path from a file input field in jsp??

Vijay
10 years ago

Hi,

I have 1 question.

You used the session to get the context object, while we can directly use the static method “getServletContext” of the “ServletActionContext” class.

Is there any difference between them and what should be the aproach to use this.