Passing Parameter to the Java file using Html form I couldn’t run in my Tomcat server.
Who can describe this example step by step? where shall I put .html file and where .java and . class files. I am attaching html and java file. The compiled file with .class extension I have already done! Thank you in advance!
<html>
<head>
<title>New Page 1</title>
</head>
<body>
<h2>Login</h2>
<p>Please enter your username and password</p>
<form method="GET" action="/htmlform/LoginServlet">
<p> Username <input type="text" name="username" size="20"></p>
<p> Password <input type="text" name="password" size="20"></p>
<p><input type="submit" value="Submit" name="B1"></p>
</form>
<p> </p>
</body>
</html>
and this is my LoginServlet.java file:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("username");
String pass = request.getParameter("password");
out.println("<html>");
out.println("<body>");
out.println("Thanks Mr." + " " + name + " " + "for visiting roseindia<br>" );
out.println("Now you can see your password : " + " " + pass + "<br>");
out.println("</body></html>");
}
}
The HTML file has to go in public webcontent and the class file has to go in
/WEB-INF/classesin the right folder structure which conforms the class’packagedeclaration. Also don’t forget to declare the servlet in/WEB-INF/web.xml.As to the HTML form, you need to realize that a leading slash
/in the URL will bring you to domain root. So effectively your form submits to http://localhost:8080/htmlform/LoginServlet. You need to ensure that the webapp context path is indeed named/htmlformand that the Servlet is inweb.xmlbeen mapped on anurl-patternof/LoginServlet.See also:
Unrelated to the problem, Roseindia.net is considered the worst learning/example source. Relatively a lot of snippets over there are cluttered by bad practices. I’d suggest to ignore that list as long as you’re new.