Search code examples
jspjsp-tags

How to set the value returned from servlet to a Textbox in a JSP page


I have created a simple web service to add two numbers and executed the same using a console program in Java which worked fine. I wish to convert it to a web application, where I have three text boxes, two for the user input and third for the result. When the user clicks the add button, the web service is invoked and result is to be displayed in the textbox.

The index.jsp is as follows:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Simple Web Service</title>
</head>
<body>
    <form method="get" action="ServiceCall">
        <input type="text" name="x" />
        <input type="text" name="y" />
        <input type="text" name="sum" disabled />
        <button type="submit">Add</button>
    </form>
    <c:if test="${not empty result}">
        <h1>${result}</h1>
    </c:if>
</body>
</html>

Here the result will be displayed on a separate line with h1 heading. I would like to put the value of ${result} in the sum text field <input type="text" name="sum" disabled />.

Referring to this setting value of input textbox in jsp, I found value='<%=${result}%>' /> will do it. But the <c:if>..</c:if> are to be included as well. How do I achieve this?


Solution

  • First of all, forget completely about scriptlets (anything starting with <% except <%@). These are obsolete and shouldn't be used anymore. The JSP EL and the JSTL are the appropriate tools.

    You want the result to be set as the value of the value attribute of your input element. So all you need is

    <input type="text" name="sum" disabled value="${result}"/>
    

    You don't need any if test since, if the result is empty, you also want the value attribute to be the empty string. If you really want to use an if test, then use it the same way you did for the h1:

    <input type="text" name="sum" disabled 
        <c:if test="${not empty result}">
            value="${result}"
        </c:if>
    />