简体   繁体   中英

Servlet is not displaying the data fetched from an html page

I am new to Web Development in java, and just started with servlets with a project "Welcome Servlet". It has 3 files , 1. ColServlet.java in default package. 2. index.html in WebContent folder. 3. web.xml in WEB-INF folder. ColServlet.java is :

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
   public class ColServlet extends HttpServlet
{

public void doGet(HttpServletRequest request,HttpServletResponse response) 
                throws ServletException, IOException  

 {  
String colname =  request.getParameter("col"); 
response.setContentType("text/html");
PrintWriter info = response.getWriter();

info.println("The color is: ");
info.println(" <HTML>\n" +
            "<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" +
            "<BODY>\n" +
            "<H1>Hello WWW</H1>\n" +
            "<h1>"+colname+"</h1>"+
            "</BODY></HTML>");
info.close();
}
}

index.html file is :

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
            <title>Select Color</title>
    </head>
    <body>
        <form method="GET" action="/ColServlet">
            Select the color:
            <select name="col" size="3">
                <option value="blue">Blue</option>
                <option value="orange">Orange</option>
            </select>
            <input type="submit" value="Submit">
        </form>
    </body>
</html> 

web.xml file is :

<web-app>
    <servlet>
        <servlet-name>Servlet1</servlet-name>
        <servlet-class>ColServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Servlet1</servlet-name>
        <url-pattern>/ColServlet</url-pattern>
    </servlet-mapping>
</web-app>

NOW : the problem is whenever i select any color, next page doesn't show the selected one.

From @SotiriosDelimanolis' comment , you should change the action path in your <form> to also use the context path of the application. You should update this line in your index.html file:

<form method="GET" action="<applicationName>/ColServlet">

Where <applicationName> is the name of your web application, which is usually the name of your web project eg "WelcomeServet" (without quotes).

If you happen to use a JSP file instead (which can be as easy as renaming index.html to index.jsp), then update this line to:

<form method="GET" action="${pageContext.request.contextPath}/ColServlet">

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