I am trying a simple program with Java Servlet wherein a HTML page with a text box and a submit button will be displayed. Once the user enters the data and submits it, the next page will display a Hello . Calling the servlet URL with the GET parameter directly shows that it works fine. But when I open the HTML file and submit data from there, the GET request isn’t formed properly, i.e. the parameters are not getting passed in the address of the ‘action’ URL.
Here is the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<form action="/TestServlt/TestClass" name="myform" method="get">
Enter your name: <input type="text name="username">
<br />
<input type="submit" value="Go">
</form>
</body>
</html>
and the servlet code:
package in.lguruprasad;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestClass extends HttpServlet implements Servlet {
static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter output = response.getWriter();
response.setContentType("text/html");
String name = request.getParameter("username");
output.println("Hello "+name+"!");
output.flush();
output.close();
}
}
The servlet is mapped to /TestServlt/TestClass URL and the form submit redirects http://localhost:8080/TestServlt/TestClass instead of http://localhost:8080/TestServlt/TestClass?username=<user input> which would work fine. The output I get is ‘Hello null!’.
In all the browsers the form submits without the get parameter. I tried writing a similar doPost method, but that didn’t work as well.
What is the issue here and how to fix it?
I am using Eclipse 3.1.2, Apache Tomcat 5.5, JDK 1.6.25 if that helps.
You are missing a quote in the html input:
should be