Call a servlet method into a util class | Community
Skip to main content
Level 4
Jul 6, 2023 4:52 AM UTC
Solved

Call a servlet method into a util class

I have a servlet with doGet and navigationLogic methods. I need to call this navigationLogic method in my util class. How can I do that as @3214626 is making the servlet and util class unsatisfied? Please suggest something.

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Nishant-Singh
Nishant-SinghAccepted solution
Employee
Jul 6, 2023 5:32 AM UTC

@goyalkritika if your navigationLogic method is separate from doGetMethod and its not using request and response objects then you can simply create an object of servlet class and call the method.

ServletClass abc = new ServletClass();

abc.navigationLogic();

 

if navigationLogic method is common code that can be used in other places then better put that method in Util class and call in servlet. it will fulfil the purpose of util class.

 

4 replies

joerghoh
Employee
Jul 7, 2023 4:32 PM UTC

Please refactor your code and move that logic into a dedicated service, outside of the servlet. 

Translate
Nishant-Singh
Nishant-SinghAccepted solution
Employee
Jul 6, 2023 5:32 AM UTC

@goyalkritika if your navigationLogic method is separate from doGetMethod and its not using request and response objects then you can simply create an object of servlet class and call the method.

ServletClass abc = new ServletClass();

abc.navigationLogic();

 

if navigationLogic method is common code that can be used in other places then better put that method in Util class and call in servlet. it will fulfil the purpose of util class.

 

Translate
aanchal-sikka
New Participant
Jul 6, 2023 5:27 AM UTC

@goyalkritika 

 

I agree with @krati_garg . All reusable code should be part of Util or an independent Service.

These should in turn be used in Servlets / Sling models / Workflow Steps etc.

 

Translate
Aanchal Sikka
krati_garg
Employee
Jul 6, 2023 5:18 AM UTC

@goyalkritika 

In my opinion create a service class and put in your navigationlogic methods into it. This service can be referenced in both your servlet and utility class.

Adding a commonly used module in a Servlet, totally defeats the purpose of having services. 

Translate