Issue
I have a JavaBean that is deployed in a Java web application which is based on a complex workflow framework such as CMN, BPMN, and DMN. The point here is that my JavaBean is invoked from a BPMN and it seems to me like it is in a context of a rest API endpoint because I can test the deployed JavaBean from postman. When I invoke the JavaBean from the BPMN, I don't see any reference to ServletContext or JSP or request object or anything like that.
I need to modify the JavaBean to add some feature that requires loading json data file from a data folder under the web root path.
I did build a sample web application successfully using dynamic Java web application and JavaBean and was able to access the web root path from the request object, and I was able to load the json data file as intended.
I need now to do the same from the real Java web application framework. The only issue I'm facing is how to access the web root path if i don't have access to HttpServlet and the other related objects.
I used the APIs below in a sample web application and they worked successfully:
Request.getsession (). Getservletcontext (). Getrealpath ();
Servletconfig.getservletcontext (). Getrealpath ("/");
See the related repo below for the sample project to clarify the question:
https://github.com/tarekahf/JavaBeanExample2/tree/master
In the project presented in the above repo, I'm loading a JSON file from a folder under the webroot. I was able to do so because I have access to the request
object and HttpServletContext
. See the source code in the following files in the above repo:
- src\com\app\EmployeeClass.java
- WebContent\data\list.json
- WebContent\index.jsp
The question now is how to access the ServletContext if I don't see it defined anywhere in the main java application?
If the JavaBean is invoked from the context of a rest API execution thread, how I can access the webroot path in this JavaBean so that I can load the needed JSON data file under the root path?
Tarek
Solution
If the JavaBean is CDI managed, you can inject the ServletContext
with:
@Inject
private ServletContext;
——
If you just want to read a json file in the java code, I would say that you maybe look at this: read ressource from folder
Edit:
Since it is found that the application is based on Spring, then the appropriate method to inject a servlet into a Bean is by using the @Autowired
annotation or implementing the ServletContextAware interface. See this for details:
https://roytuts.com/how-to-get-servletcontext-and-servletconfig-object-in-a-spring-bean/
Also, this is another resource for how to read files in Java:
https://www.baeldung.com/reading-file-in-java
Answered By - Jelmen
Answer Checked By - David Marino (JavaFixing Volunteer)