0

I am trying to create a simple HTML form to submit data from JSP to Servlet. I am getting 404 not found exception. My request URL: http://*****:80**/myapps/more/test.html

HTML

<form id="userForm" action="/more/loginServlet" method="post">
   <input id="Submit"  value="Submit" type="submit">
</form>

web.xml


<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <servlet>
        <servlet-name>LoginServlet</servlet-name>                    
        <servlet-class>com.more1.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/more/loginServlet</url-pattern>
    </servlet-mapping>
</web-app>

Servlet code


package com.more1;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    System.out.println("===========================");
    // System.out.println(request.getParameter("service_number"));
 }
informatik01
  • 15,174
  • 9
  • 67
  • 100
user1793215
  • 1
  • 1
  • 3

2 Answers2

3

Your form action URL is wrong. It should stay in /myapps context and not go outside. The 404 error simply means that the requested URL does not point to any valid resource. If you have paid close attention to the request URL in the browser's address bar, you should have noticed that /myapps part has disappeared.

Fix it accordingly:

<form id="userForm" action="/myapps/more/loginServlet" method="post">

Or just as follows as you're currently (as per URL in browser's address bar) already sitting in /myapps/more:

<form id="userForm" action="loginServlet" method="post">

Or if you worry about the dynamicness of the context path, inline HttpServletRequest#getContextPath() as follows:

<form id="userForm" action="${pageContext.request.contextPath}/more/loginServlet" method="post">

An alternative is to introduce the HTML <base> tag.

See also:


Unrelated to the concrete problem, are you absolutely positive that you're reading proper and up to date tutorials when learning servlets? Your web.xml root declaration is a Servlet 2.3 one which is more than a decade old already. We're currently already on Servlet 3.0. Start at our servlets wiki page for some sane Hello World examples and links to sane tutorials.

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
1

Your app seems to be deployed in the myapps context path (th HTML page URL is /myapps/more/test.html). But your form submits to /more/loginServlet. It should submit to /myapp/more/loginServlet.

To avoid hard-coding the context path in your pages, use the JSTL tag:

<form action="<c:url value='/more/loginServlet'/>" ...>

or prepend the context path explicitely:

<form action="${pageContext.request.contextPath}/more/loginServlet" ...>
JB Nizet
  • 633,450
  • 80
  • 1,108
  • 1,174