Issue
I am building a JSP webapp using Tomcat and Maven. I want to update the value of a textarea in my jsp page when a button on that same jsp page is clicked.
In my XMLProcessor class I have a function called returnNextMessage() which returns a string of data.
<%@ page import="efidbg.XMLProcessor"%>
<html>
<head>
<title>Home</title>
</head>
<body>
<div id="base" class="">
<!-- Textbox that i want to fill using java function. -->
<div id="u1" class="ax_default text_area">
<textarea id="u1_input"></textarea>
</div>
<!-- Button when clicked call returnNextMessage() function -->
<div id="u9" class="ax_default primary_button">
<form action="MyServlet" method="POST">
<input
type="submit" value="Submit" />
</form>
</div>
</div>
</body>
</html>
I tried to implement it using a servlet called MyServlet but that seems to redirect me to a new page which makes me think that using a servlet is not the correct way to achieve this.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String Value = XMLProcessor.returnNextMessage();
request.setAttribute("u1_input", Value);
}
When I press the submit button I just get redirected to Localhost/MyServlet which gives me an empty page.
Solution
Change your JSP file like below:
<%@ page import="efidbg.XMLProcessor"%>
<html>
<head>
<title>Home</title>
</head>
<body>
<div id="base" class="">
<!-- Button when clicked call returnNextMessage() function -->
<div id="u9" class="ax_default primary_button">
<form action="MyServlet" method="POST">
<!-- Textbox that i want to fill using java function. -->
<div id="u1" class="ax_default text_area">
<textarea id="u1_input">${u1_input}</textarea>
</div>
<input
type="submit" value="Submit" />
</form>
</div>
</div>
</body>
</html>
And add the code in your java method after you set the attribute.
request.getRequestDispatcher("/xxx.jsp").forward(request, response);
Answered By - herokingsley
Answer Checked By - Timothy Miller (JavaFixing Admin)