-2

When i try to run the code in eclipse it won't pass the arguments. please check the below images url.

enter image description here

But when i individually run the html code it passes the values.

enter image description here

I don't know why this work like this. My Servlet code is

package com.example;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AddServelet extends HttpServlet
{

    public void services(HttpServletRequest req, HttpServletResponse resp) {

        int i = Integer.parseInt(req.getParameter("num1"));
        int j = Integer.parseInt(req.getParameter("num2"));

        int k = i+j;    
        System.out.println(k);  
    }
}

and my web.xml code is

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">

<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>com.example.AddServelet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>

</web-app>

my html code

<html>
<body>
<form action="add">
Number 1: <input type="number" name="num1"><br>
Number 2: <input type="number" name="num2"><br>
<input type="submit">
</form>
</body>
</html>

Can anyone please help me with this. Thank you in advance.

  • 1
    The method is called `service`, not `services`. But, yeah, if you are using `HttpServlet`, you might as well override one of the `doXYZ` methods. – Savior Apr 03 '20 at 19:37

2 Answers2

2

You need to override the doPost method because you are submitting the form and it's a post request.

public class AddServelet extends HttpServlet { private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public AddServelet() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    int i = Integer.parseInt(req.getParameter("num1"));
    int j = Integer.parseInt(req.getParameter("num2"));

    int k = i+j;    
    System.out.println(k); 
}

}

Amit Kumar
  • 177
  • 4
1

override the HttpServlet protected void doGet(HttpServletRequest req, HttpServletResponse resp) method if you want to handle a GET request

pero_hero
  • 1,912
  • 2
  • 5
  • 15