Building Web Apps in Java: Servlet: A Servlet's Job
Building Web Apps in Java: Servlet: A Servlet's Job
Reference: http://courses.coreservlets.com
Last lecture/lab we have installed and used Eclipse with Tomcat to deploy simple
servlets.
A Servlet’s Job
Read explicit data sent by client (form data)
Read implicit data sent by client (request headers)
Generate the results
Send explicit data back to client (HTML)
Send implicit data to client (status codes and response headers)
Simple Servlets
1. A Servlet That Generates Plain Text (HelloWorld.java)
@WebServlet("/hello")
public class HelloWorld extends HttpServlet {
@Override
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
@WebServlet("/test1")
Idea
TestServlet2: Result
Custom URLs and web.xml
Tomcat 7 or Other Servlet 3.0 Containers
@WebServlet("/my-address")
public class MyServlet extends HttpServlet { … }
- Resulting URL
http://hostName/appName/my-address
Omit web.xml entirely
- You are permitted to use web.xml even when using @WebServlet, but the
entire file is completely optional.
In earlier versions, you must have a web.xml file even if there were no tags other
than the main start and end tags (<web-app …> and </web-app>).
Eclipse details
- Name of Eclipse project is “test-app”
- Servlet is in src/testPackage/TestServlet.java
- Deployed by right-clicking on Tomcat, Add and Remove Projects, Add,
choosing test-app project, Finish, right-clicking again, Start (or Restart)
Summary
Main servlet code goes in doGet or doPost:
- The HttpServletRequest contains the incoming information
- The HttpServletResponse lets you set outgoing information
Call setContentType to specify MIME type
Call getWriter to obtain a Writer pointing to client (browser)
Make sure output is legal HTML
Give address with @WebServlet or web.xml
@WebServlet("/some-address")
public class SomeServlet extends HttpServlet { … }
Resulting URL
- http://hostName/appName/some-address