Home > Net >  Java Error when passing a value through html to a servlet but servlet not found. why?
Java Error when passing a value through html to a servlet but servlet not found. why?

Time:01-10

i made three files ->javaservlet, xml and html xml file gives mapping, html takes one number as parameter and forwards it into javaservlet java servlet finds its square and prints it but in the browser when i enter a number and submit it the following error is shown HTTP Status 404 – Not Found

Type Status Report

Message The requested resource [/ExampleLearning/Example.java] is not available

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.



<!DOCTYPE html>
<!--
Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Html.html to edit this template
-->
<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>
        <div>TODO write content</div>
        <form action ="Example.java" method ="get">
        num1:<input type="text" name="num1">
       <input type="submit" value="go">
 </form>
    </body>
</html>

javaservlet-




package Pack;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;


/**
 *
 * @author Ritik Sharma
 */
public class Example extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    
        PrintWriter pw= response.getWriter();
        int num1=Integer.parseInt( request.getParameter("num1"));
        pw.print(num1*num1 "is" num1 "'s square!!");
        System.out.println(num1);
        
    }
    }

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>Example</servlet-name>
        <servlet-class>Pack.Example</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Example</servlet-name>
        <url-pattern>/Example</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

CodePudding user response:

Your urlPattern is /Example, but in your HTML form, you are using Example.java which does not map to /Example. Change your HTML form action to /Example and it should work.

  • Related