MyServletDemo.java
[java]package servletresponse;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class MyServletDemo extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pwriter=res.getWriter();
String name=req.getParameter("uname");
pwriter.println("User Details Page:");
pwriter.println("Hello "+name);
pwriter.close();
}
}[/java]
The
doGet() Method. A GET request results from an normal request for a URL or from a
HTML web form that has no METHOD determined and it ought to be taken care of by
doGet() technique.
web.xml
[xml]<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>servletresponse.MyServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/mydetails</url-pattern>
</servlet-mapping>
</web-app>[/xml]
Make sure that servlet name should be same as that is
DemoServlet in both the tags.
URL pattern should be match with below HTML page action form.
index.html
[html]<form action="./mydetails" method="get">
User name: <input type="text" name="uname">
<input type="submit" value="login">
</form>[/html]
Here the developer just created the
User name and submit button that is
login.
Output
The following output is generated by compiling the above code.
Enter the name and click on the login button, following is the output will be displayed.
ServletResponse vs HttpServletResponse
- ServletResponse available in javax.servlet package where as HttpServletResponse available in javax.servlet.http package and it's a sub interface of ServletResponse.
- ServletResponse will have methods as getWriter() etc. and HttpServletResponse also have methods like encodeURL() and sendRedirect() etc and it will hire the methods from ServletResponse.
- ServletResponse is a protocol independent and HttpServletResponse is a protocol dependent.