1

I have below Dynamic web project setup

Index.jsp

<form action="submitClick" method ="post"
<textarea> id="textarea" name="textarea" rows="25" cols="100">${result}</textarea>
<input type="submit">


 SubmitClick.java //servlet class
    public class SubmitClick extends HttpServlet{
    public void doPost(HttpServletRequest request, HttpServletResponse response){
    MainLogicClass mainLogic = new MainLogicClass(username,password); //let's suppose hardcoded
    
    request.setAttribute("result", "Hello");// Hello is getting printed on textarea, but I want to print output text on textarea from MainLogicClass.
    
    getServletContext().getRequestDispatcher("/index.jsp").forward(request,response);
    }
    }

MainLogicClass//different class, present in same package

public class MainLogicClass{
public MainLogicClass(String username, String password){
//DB Connection logic
System.out.println("Database Connection successful");
/* I want to print "Database Connection successful" on textarea which presents on index.jsp
And after that, I need to print few more output so that the text gets appended to textarea like-
"Database Connection successful

DB query executed

DB connection closed"
*/
}
}

How can I print text from MainLogicClass to Servlet using request.setAttribute method or any other workaround.

1 Answers1

0

Constructor doesn't have any return type so instead of constructor you can create a method and put your logic code there and return some value from there . So , your method inside MainLogicClass will look like somewhat below :

public String Something(String username, String password){
String msg = "" ;
msg +="Something to return";
msg +="soemthing more";
//your logic code
return msg;//return back   
}

And then in your servlets doPost method do like below :

 MainLogicClass mainLogic = new MainLogicClass();
 String message  =  mainLogic.Something(String username, String password);//call that function
 request.setAttribute("result", message );
Swati
  • 28,069
  • 4
  • 21
  • 41
  • Thanks for the quick answer, it does answer my question almost entirely, but one question here, if I want to print live text instead of returning string at the end of method and then print. Assume if, I want to print live cricket scores. Any suggestions/approaches would be highly appreciated. – Raghav Bakshee Sep 08 '20 at 13:31
  • Then using `ajax` would work here ,because here to call your backend you need to submit your form and the page will get refresh as well so use ajax . Here is an [example](https://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax) how to achieve same . – Swati Sep 08 '20 at 13:44