I am trying to create a program in which I can accept input and get the square root of a number with a servlet. I am a beginner, so I don't know much. The problem is when I try my code, it doesn't work. Here is the code:
MyServletDemo.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.lang.Math;
public class MyServletDemo extends HttpServlet {
public void init() throws ServletException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
String num2 = request.getParameter("num");
int num3 = Integer.parseInt(num2); //This is where the error
int numSqrt = Math.sqrt(num3);
PrintWriter out = response.getWriter();
out.println("<p> The sqrt is "+numSqrt+"</p>");
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Get sqrt of num</title>
</head>
<body>
<p>Num to find sqrt of: </p> <input type="text" name="num"/>
<a href="welcome">Click to call Servlet</a>
</body>
</html>
I don't know much about xml, I found the code in a tutorial: web.xml
<?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_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Find-the-sqrt-of-num</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>MyHttpServletDemo</servlet-name>
<servlet-class>MyServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyHttpServletDemo</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
The results are: First this, then when you hit the link, you get :