First Servlet
In this JSP-tutorial we’ll cover the web.xml file (and the working of mapping-url, servlet-name and servlet-class) and we’ll create our first Servlet.
It would be easy to follow a standard file structure, which looks like this:
- Src
- Model
- Beans
- Servlet
- FirstServlet.java
- AnotherServlet.java
- Web
- WEB-INF
- Web.xml
- firstpage.jsp
- anotherpage.jsp
- WEB-INF
All the JAVA-code will go in src-file and we’ll put the html-pages in the web-file.
The web.xml file is a very important file, it will define our servlets which will make it possible for the server to call these servlets.
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <servlet> <servlet-name>FirstServlet</servlet-name> <servlet-class>servlets.FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FirstServlet</servlet-name> <url-pattern>/firstservlet.do</url-pattern> </servlet-mapping> </web-app>
The servlet-class-tag defines the path where the Servlet can be found. The servlet-mapping-tag tells the server which servlet to call when a certain url is opened. If someone opens “yoursite.com/firstervlet.do” your server will call the FirstServlet class and execute it.
There’s many different ways a servlet can be called, but we’ll start with the default: GET. If someone actually browses to firstservlet.do the server will call the doGet method on the servlet. Here’s an example how this looks like:
package servlets;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import java.io.IOException;
public class FirstServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("sales.jsp");
}
}
This will forward your user to the sales page which is a jsp, and most likely a page with all sales from a certain period. Of course we can do a lot more than just forward the user, we might handle user input or write data to a database.