Write a Web Application using Servlet to find the sum of all the digit of an input integer.
index.html
NewServlet.java
web.xml
index.html
- <!DOCTYPE html>
- <html>
- <head>
- <title>TODO supply a title</title>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- </head>
- <body>
- <form method="get" action="NewServlet">
- <p>enter any no:<input type="text" name="no"><br><br></p>
- <input type="submit" value="submit">
- </form>
- </body>
- </html>
NewServlet.java
- 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 NewServlet extends HttpServlet
- {
- protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
- {
- response.setContentType("text/html;charset=UTF-8");
- PrintWriter out = response.getWriter();
- try
- {
- int n,s=0,r,x;
- n=Integer.parseInt(request.getParameter("no"));
- x=n;
- while(x!=0)
- {
- r=x%10;
- s=s+r;
- x=x/10;
- }
- out.println("sum of all digits is:"+s);
- }
- catch(Exception e)
- {
- out.printf("error");
- }
- }
- }
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <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">
- <servlet>
- <servlet-name>NewServlet</servlet-name>
- <servlet-class>NewServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>NewServlet</servlet-name>
- <url-pattern>/NewServlet</url-pattern>
- </servlet-mapping>
- <session-config>
- <session-timeout>
- 30
- </session-timeout>
- </session-config>
- </web-app>