How to reach the WebContent folder from a web service method - java

I want to reach a file in WebContent folder from a method in a web service in the same project. For example:
#WebMethod
public String test() {
File configFile = new File("config.xml");
return configFile.getAbsolutePath();
}
It returns "/usr/share/glassfish3/glassfish/domains/domain1/config/config.xml". I want to get to a file in the directory "/usr/share/glassfish3/glassfish/domains/domain1/applications/my_project_name/" folder. How can I get to it?

The best way to do this that I use is:
Thread.currentThread().getContextClassLoader().getResource("myFile.txt").getPath()
This gives the path of any file myFile.txt placed in /WEB-INF/classes/ directory inside the WebContent folder of the WebApp.
In Eclipse JEE environment you need to keep the file myFile.txt, that you may want to read within the Web Service, in the src folder for it to be transported to the /WEB-INF/classes/ folder by the deployer.

From your code, I understand that yours is an JAXWS webservice.
In jaxws, you can get the HttpServletRequest, HttpServletResponse, ServletContext,
Have a private variable in your webservice class and annotate it in this way
#Resource
private WebServiceContext context;
And then in your method, you can get the ServletContext this way
ServletContext servletContext =
(ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
From servletContext, you can get the path.
Suppose if you need to get HttpServletRequest, you can get it in this way
HttpServletRequest request =
(HttpServletRequest) context.getMessageContext().get(MessageContext.SERVLET_REQUEST);
and you can get the context path of your app like
request.getContextPath() ;

Add the following parameter to your web service class:
#Context
ServletContext context;
Then, supposing your config.xml file is in the WebContent folder, you can get its absolute path by invoking the method context.getRealPath(String). Using your example code it would be:
#WebMethod
public String test() {
File configFile = new File(context.getRealPath("config.xml"));
return configFile.getAbsolutePath();
}
Or directly, without passing by a File object:
#WebMethod
public String test() {
return context.getRealPath("config.xml");
}

Related

Changing restAPI URI

I have created an application in java with the name hello. my class is below
#Path("/test")
class TestAPI
{
#GET
#Path("/hi")
public String sayHi()
{
return "Hi I am Shweta";
}
}
I am accessing this application using
GET http://localhost:8080/hello/test/hi
Is there anyway I can remove hello from URI or I can replace the same without changing application.
If I need to access like http://localhost:8080/test/hi what changes I need to do? I am using maven.
Yes you can do it in your server.Say if you are using tomcat to deploy your application,Then go through its configuration file and change the context path to '/'.It will work.You just need to check where context path is defined in what ever server you are using and just replace the path with '/'.

Get the Path of a resource from a spring boot aplication using servlet context

I have this structure, generated by spring boot
So I want to get a input stream of the file gastos.xlsx using sevletContext.
#Autowired
private ServletContext context;
#GetMapping("/grafico")
public ResponseEntity<String> exportExcelGrafico(HttpServletResponse response){
try{
//this path returns null. What is the real path to put here?
InputStream input = context.getResourceAsStream("src/main/resources/templates/gastos.xlsx");
//returns null
input = context.getResourceAsStream("/resources/templates/gastos.xlsx");
// Returns null
input = context.getResourceAsStream("/templates/gastos.xlsx");
}
catch(){
}
What would be the right path?
I didn't configure anything on my application.properties
What's in the src/main/resources folder of your Maven or Gradle project ends up in your jar, not in the web resources. And it should thus be loaded using the class loader, not using the servlet context:
MyClass.class.getResourceAsStream("/templates/gastos.xlsx")
Not sure why you put that file under templates, since... it's not a template.

How to redirect page to static file in Spring Boot?

How can I redirect a page web request / request mapping in Spring Boot (MVC) to point to a static file (example: .txt, .json, .jpg, .mp4, etc). All I have in my Spring Boot project is an application.properties file and the #Controllers.
I'd like for the user, when making a web request to the url in browser to be asked to download the file (not use it to attempt to render the page, like it does with .html, .jsp)
You can achive this by telling the response that you wish to attach a downloadable file. Then you can simple write the content you want to make downloadable.
Here is an example :
#ResponseStatus(HttpStatus.OK)
#RequestMapping(value = "/myredirect", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void downloadFile(HttpServletResponse response) {
// Remove this instruction if you wish to disable the download dialog.
response.setHeader("Content-Disposition", "attachment; filename=filename.ext");
// Load your file content as byte.
byte[] fileContent = IOUtils.toByteArray(new ClasspathResource("myfile").getIntputStream());
response.getOutputStream().write(fileContent);
}
On the other hand, if you simply want a direct mapping to a static file. You may use the default public folder of Spring Boot Starter Web.
Any file found inside classpath:/public will be mapped to /*by default.
You can redirect using the "redirect:" prefix in Spring. From the Spring documentation:
A logical view name such as redirect:/myapp/some/resource will redirect relative to the current Servlet context, while a name such as redirect:http://myhost.com/some/arbitrary/path will redirect to an absolute URL.
An example would be:
#RequestMapping("/redirectToResource")
protected String redirect(#RequestParameter("resource") String resource) {
return "redirect:/myapp/some/" + resource;
}
You can place static resources to be served directly in your classpath in any of the following locations (see Serving static resources):
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/" };

Spring Java mulipart data file save

I work with Spring.
I have this code on my controller
#Controller
public class FileUploadController {
#RequestMapping(value = "/file-upload", method = RequestMethod.POST)
#ResponseBody
public String uploadFile(#RequestParam("file") MultipartFile file, HttpServletRequest request,ServletContext context) throws IOException {
if(!file.isEmpty()) {
file.transferTo(new File("/data.xml"));
return "ok";
}
else {
return "Empty";
}
}
}
i just want to save the uploaded file to the root directory.
It seem to me that i use a absolute Path to the Root, but i don't now how i can find that out.
Can anybody help me ?
You can get real path with
HttpServletRequest.getSession().getServletContext() but this will be helpful If your application has session.If your application is sessionless than you can do by implementing ServletContextAware.
If application has session then
request.getSession().getServletContext().getRealPath("WEB-INF");
also one another way to get real path.
Get the class loader from one of your objects and use that to get its local path. That will give you a path from your execution point in Tomcat. From there you can find the location you want.
obj.getClass().getResource("/");

How do I access file in WEB-INF in JSP?

I am using Tomcat. I would like to put the config file in WEB-INF instead of the default root class path which is WEB-INF/classes. Currently I put the config.xml in WEB-INF and use the following relative addressing to locate it:
InputStream input = Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("..//config.xml");
Is this the correct way to do?
Or should I use the getServletContext().getRealPath("config.xml") first? But I don't know how to obtain the getServletContext() in a .java. (I tried to new HttpServlet for obtaining getServletContext(), but since it is an abstract class, can't be instanced... how can I get the getServletContext()?)
The method getRealPath() is not guaranteed to work, e.g. if your webapp is not expanded from a war file there is no 'real path' on the filesystem to a file inside the war file.
Since you say you are using a ServletContextListener, you can get the ServletContext out of the ServletContextEvent:
sce.getServletContext().getResourceAsStream("/WEB-INF/config.xml");
You can use getServletConfig() method return an instance of ServletConfig.
ServletContext sc=getServletConfig().getServletContext();
EDIT:
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
ServletContext sc=getServletContext();
...
}

Categories