Reputation: 395
HTML FILE
<form method = "post" action = "getSum">
Enter first no. : <input type = "text" name = "First"/>
Enter Second no.: <input type = "text" name = "Second"/>
SUM : <input type = "text" name = "Sum"/>
</form>
sum.java
package calculation;
public class sum extends HttpServlet {
private static final long serialVersionUID = 1L;
public sum() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int first = Integer.parseInt(request.getParameter("First"));
int second = Integer.parseInt(request.getParameter("Second"));
int sum = first+second;
PrintWriter out = response.getWriter();
out.println("");
}
}
I want to put the result sent by servlet into the input box which i made in html file how to do that? I am new to servlet programming pls help me out a little bit
Upvotes: 0
Views: 2364
Reputation:
In short.
Create the form in the doGet()
method of the servlet. In the action
attribute, specify the name of the servlet in the method
attribute, specify POST
.
...
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(...) // form here
...
You can use *.html
file instead of creating the form in the servlet.
Get the passed parameters in the doPost()
method of the servlet.
...
request.getParameter("First");
request.getParameter("Second");
request.getParameter("Sum");
...
Perform the necessary checks, generate the form with the filled fields.
Then call the servlet you will see the blank form. Write values in the fields and submit the form. You will see the filled form.
Although it is better to use JSP in this case - What is the difference between JSF, Servlet and JSP?
Upvotes: 2
Reputation: 1560
There are a lot of possibilities for client-server interaction. I see two common cases:
out.println("");
line in the Servlet and add a submit button in HTML form to achieve this. But in practice you need something for generating dynamic HTML pages, you can use JSP or template engine like Velocity, FreeMarker or something else. Also there are a lot of frameworks.Upvotes: 1
Reputation: 14188
The simplest is to have all the HTML generated in your servlet. When doGet is called, return the empty HTML form. When doPost() is called, return the HTML form with the data populated.
doGet(...){
out.println("<html> ... <form> .... </form> ... </html>
}
doPost(...){
out.println("<html> ...<form> populate inputs </form> ... </html>");
}
You could also create a new method
renderHtml(Integer first, Integer second, Integer sum) {
// print out html. If first, second, or sum is null, then don't add those to
// the value of the input boxes
}
which you call do eliminate duplicating code.
The next level is to use a templating system like: jsp, Velocity, FreeMarker, etc ....
Upvotes: 0