My servlet is not working even though the code seems to be correct. where have I gone wrong?


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class First extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try (PrintWriter out = response.getWriter()) {
            int sum;
            int x,y;
            String a = request.getParameter("num1");
            String b = request.getParameter("num2");
            x = Integer.parseInt(a);
            y = Integer.parseInt(b);
            sum = x + y;
            out.println("The sum is" + sum);


        <title>Supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <form action="First">
            Number1:<input type="text" name="num1" /><br/>
            Number2:<input type="text" name="num2" /><br/>
           <input type="submit" value="button" />

Edited by peter_budo: Moving to java web development

2 Years
Discussion Span
Last Post by milil

First you don't have annotiation to indicate what need to be call for this:


Second thing is that you need constructor for super:

public First() {
        // TODO Auto-generated constructor stub

Third thing is that server use methods like doGet and doPost you need to specify in form what are you calling:

<form method="post" action="/Project/First" class="login">

and in servlet to have that doPost method:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // here you do your calculations

            // this will redirect you to new page...
            RequestDispatcher rd = getServletContext().getRequestDispatcher("/Pages/newpage.jsp");
            rd.forward(request, response);


If this helps you give thumb up so it can help others.
Thanks, Mike.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.