Write a Web Application using Servlet to find the sum of all the digit of an input integer

Write a Web Application using Servlet to find the sum of all the digit of an input integer.

index.html
  1. <!DOCTYPE html>
  2. <html>
  3.     <head>
  4.         <title>TODO supply a title</title>
  5.         <meta charset="UTF-8">
  6.         <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7.     </head>
  8.     <body>
  9.         <form method="get" action="NewServlet">
  10.             <p>enter any no:<input type="text" name="no"><br><br></p>
  11.                 <input type="submit" value="submit">
  12.         </form>
  13.     </body>
  14. </html>

NewServlet.java
  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;

  7. public class NewServlet extends HttpServlet 
  8. {

  9.      protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
  10. {
  11.          response.setContentType("text/html;charset=UTF-8");
  12.          PrintWriter out = response.getWriter();
  13.         
  14. try
  15.          {
  16.                  int n,s=0,r,x;
  17.             n=Integer.parseInt(request.getParameter("no"));
  18.             x=n;
  19.              while(x!=0)
  20.              {
  21.                  r=x%10;
  22.                  s=s+r;
  23.                  x=x/10;
  24.              }
  25.                   out.println("sum of all digits is:"+s);
  26.             
  27.          }
  28.          catch(Exception e)
  29.          {
  30.              out.printf("error");
  31.          }
  32.      }   
  33. }

web.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
  3.     <servlet>
  4.         <servlet-name>NewServlet</servlet-name>
  5.         <servlet-class>NewServlet</servlet-class>
  6.     </servlet>
  7.     <servlet-mapping>
  8.         <servlet-name>NewServlet</servlet-name>
  9.         <url-pattern>/NewServlet</url-pattern>
  10.     </servlet-mapping>
  11.     <session-config>
  12.         <session-timeout>
  13.             30
  14.         </session-timeout>
  15.     </session-config>
  16. </web-app>
Write a Web Application using Servlet to find the sum of all the digit of an input integer

Download the Android app to get all Government Job Notifications on your Mobile.
Download Now
Important: Please always Check and Confirm the above details with the official Advertisement / Notification.
Previous Post Next Post