简体   繁体   中英

Unable to connect to servlet file in Netbeans

I'm trying to perform a servlet program which is to choose a color and show it through a servet. I've configured the tomcat server properly.But when I'm trying to run the code, the index.HTML file opens normally but when I click on submit button, it suppose to open my servlet file which will display my selected color.But, instead of getting my servlet I'm getting a 404 error. Here is the code given below. Any Suggestion?

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ColorPostServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException{
    String color = request.getParameter("color");
    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
    pw.println("<B>The Selected Color is:");
    pw.println(color);
}
} 

here is my html file

<html>
<head>
    <title> </title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
    <form name="Form1"
          method="post"
        action="http://localhost:8084/ServletExample/ColorGetPost">
        <B>Color:</B>
        <select name="color" size="1">
            <option value="Red">Red</option>
            <option value="Blue">Blue</option>
            <option value="Green">Green</option>
        </select>
        <br><br>
        <input type="submit" value="Submit">
    </form>
</center>
</body>
</html>

When I run this program I'm getting the page where I can choose the color:

屏幕截图

but after clicking on submit button I'm getting 404 error.

xml file for the servlet

<servlet>
    <servlet-name>ColorPostServlet</servlet-name>
    <servlet-class>ServletExample.ColorPostServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ColorPostServlet</servlet-name>
    <url-pattern>/ColorPostServlet</url-pattern>
</servlet-mapping>
<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>

我的应用程序“ ServletExample”

Your form has wrong action url.

<form name="Form1"
method="post"
action="http://localhost:8084/ServletExample/ColorGetPost">

It should point to the servlet url:

<form name="Form1"
method="post"
action="http://localhost:8084/ServletExample/ColorPostServlet">

So basically: action="http://localhost:[Port]/[ ProjectName ]/[ ServletName ]"

It must go as comment, but posting as answer due to lack of enough reputation.

You want to submit your form to ColorPostServlet so your form action must be ColorPostServlet (what is specified in url-pattern)

<form name="Form1"
      method="post"
    action="ColorPostServlet">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM