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

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" />

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.