一、 What are servlets?

【高级网络程序设计】Week3-2 Servlet-LMLPHP

1. 定义

(1)Servlets are Java’s answer to CGI:

(2)图解

2. A general purpose Web Server

【高级网络程序设计】Week3-2 Servlet-LMLPHP

二、Simple Example

ignore how the Container finds the servlet (via the deployment descriptor web.xml).
<form action=“http://server.com/ExecuteServlet”>
<input type=“submit” value = “press for servlet”>
</form>

1.  A Basic Servlet

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
//import jakarta.servlet.*:imports classes in this directory, but not in sub-directories
public class HelloServlet extends HttpServlet {
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("text/html");//设置响应文件类型、响应式的编码形式
        PrintWriter out = response.getWriter();//获取字符输出流
        out.println(“<html><body>Hello!</body></html>”);
        out.close();
    }
}

2.  Echo Servlet

【高级网络程序设计】Week3-2 Servlet-LMLPHP
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
public class GetEchoServlet extends HttpServlet {
    public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException {
        String userName = request.getParameter(“fname”);//获取form中输入的参数
        response.setContentType("text/html");//设置响应文件类型、响应式编码格式
        PrintWriter out = response.getWriter();//获取字符输出流
        out.println(“<html><body>Hello”);
        if (userName != null) 
            out.println(userName);
        else 
            out.println(“mystery person”);
        out.println(“</body></html>”);
        out.close();
    }
}

3. BMI Servlet

- HTML
//Page that asks for weight (kg) and height (cm) :Write the HTML and the HTTP Request (GET)
<form method=“GET”action=“http://server.com/BMIServlet”>
<input type=“text” name=“weight”/>weight<br>
<input type=“text” name=“height”/>height<br>
<input type=“submit” value=“send”>
</form>

- Servlet


import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
public class BMIServlet extends HttpServlet {
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
        String ht = request.getParameter(“height”);
        int height = Integer.parseInt(ht);
        double weight = Double.parseDouble(request.getParameter(“weight”));
        double ht_squared = (height/100.0)*(height/100.0);
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println(“<html><body><br>”);
        out.println(“Your BMI is: ” + weight/ht_squared + “<body></html>”);
        out.close();
    }
}

4. Name-salary Servlet

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
public class HelloServlet extends HttpServlet {
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        String name = request.getParameter("name");
        int salary = Integer.parseInt(salary);
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><body><br>");
        out.println("Hello,"+name);
        out.println("Your salary is"+salary);
        out.println("<body><html>");
        out.close();
    } // end of method
} // end of class

三、Servlet Key Points

1. Servlets: Key points

2. Finding things

3. JavaBeans, JSPs and Servlets

4. Advantages of Servlets over CGI

四、Servlets in Detail

1. A general purpose Web Server

【高级网络程序设计】Week3-2 Servlet-LMLPHP

2. What servlets do

3. Typical generic servlet code

import java.io.*;
import jakarta.servlet.*;
public class AnyServlet extends GenericServlet {
    public AnyServlet() {} 
        // constructor – BUT USE THE DEFAULT
        // NEVER ANY NEED TO WRITE ONE
        //ONLY creates an object, becomes a “proper” servlet after init().
    public void init(ServletConfig config) throws ServletException;
        // The method is actually called by container when servlet is
        // first created or loaded.
    public void service(ServletRequest req, ServletResponse res)throws ServletException, IOException;
        // Called by a new thread (in the container) each time a
        // request is received.
        public void destroy();
        // Called when servlet is destroyed or removed.
}

4. A Servlet is “deployed” in a container

• A program that receives (e.g. HTTP) requests to servlets from a web server application:
– finds the servlet (and loads, calls constructor & init() if not ready);
– creates or reuses a thread that calls service() method of chosen servlet;
– creates & passes request and response objects to chosen servlet;
– passes the response (e.g. HTTP response) back to the web server application; kills servlet thread or recycles into thread pool; and deletes request and response objects.
• More generally, manages the life cycle of its servlets:
Calls constructor, init(), service(), destroy().
– Also invokes methods of listening classes that a servlet implements (out of scope here).
• It has a main() and is working “all the time”.
• Also provides:
– Declarative security using settings in Deployment Descriptor (DD).
– JSP support.

5. Dissecting the Container’s actions

- HTTP request:
- Servlet:

6. The servlet life cycle

【高级网络程序设计】Week3-2 Servlet-LMLPHP

7. methods & inheritance

【高级网络程序设计】Week3-2 Servlet-LMLPHP

8. Servlet’s Life cycle

五、 Configuration Servlets To Run In Tomcat

1. Mapping names using the Deployment Descriptor (DD)

//For each servlet in the web application.
//Internal name of servlet can be “anything” following XML rules.
<web-app ...>
    <servlet>
        <servlet-name>…</servlet-name>
        //maps internal name to fully qualified class name (except without .class)
        <servlet-class>…</servlet-class>
        //maps internal name to public URL name e.g. /makebooking
    </servlet>
    <servlet-mapping>
        <servlet-name>…</servlet-name>
        <url-pattern>…</url-pattern >
    </servlet-mapping>
...
</web-app>

2. Servlet Mapping Examples

3. Example: A Small Form

//SmallForm.html
<html>
    <title>Sending Form Information to a Servlet</title>
    <body>
        <form action="http://localhost:8080/servlet/elem004.ProcessSmallForm"method="post">
            //Can use absolute or relative URLs or pre-configured names.
            Please input your login: <br>
            <input type="text" name="Login">
            <input type="submit" value="Login">
        </form>
    </body>
</html>

//the Deployment Descriptor (web.xml) and the servlet
<servlet>
     <servlet-name>smallForm</servlet-name>
     <servlet-class>SmallFormServlet</servlet-class>
</servlet>
<servlet-mapping>
     <servlet-name>smallForm</servlet-name>
     <url-pattern>/servlet/elem004.ProcessSmallForm</url-pattern>
</servlet-mapping>

4. Putting everything in the right place

5. Servlet initialisation & Servlet Configuration object

• Only one servlet instance is created: each request is serviced by a separate thread in the container.
• Prior to initialisation, the ServletConfig object is created by the container:
– one ServletConfig object per servlet;
– container uses it to pass deploy-time information to the servlet (data you do not want to hard code into the servlet, e.g. the DB name);
– the names are specified in the DD.
• Parameters are set in a server-specific manner, e.g.
– in a file called web.xml (for Tomcat);
– in a file called resin.config (for Resin).
• Parameters do not change while servlet is deployed and running:
– like constants;
– if servlet changes, then need to redeploy.

6. Example: DD’s init parameters (web.xml for Tomcat)

<web-app xmlns=“http://java.sun.com/xml/ns/j2ee”
     xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
     xsi:schemaLocation=“http//java.sun.com/xml/ns/j2ee/web-app_2.4.xsd”
     version=“2.4”>
    <servlet>
        <servlet-name>Hello World Servlet</servlet-name>
        <servlet-class>S1</servlet-class>
        <init-param>
            <param-name>lecturersEmail</param-name>
            <param-value>paula.fonseca@qmul.ac.uk</param-value>
        </init-param>
        //Container reads these & gives them to ServletConfig object.
    </servlet>
</web-app>

7. Creating a servlet: ServletConfig and init(…)

六、Thread Safety And Putting Things Together

1. Instance Variables

public class ExampletServlet extends HttpServlet {
private int age;
public void init() { age = 0; }
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
IOException, ServletException {
age = Integer.parseInt(request.getParameter(“age”));
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
out.println(“<HTML><BODY>You are ” + age + “ weeks old”);
out.println(“</BODY></HTML>”);
out.close();
}
}

2. The 3 Threads access same Resources

• We don’t know whose age will be displayed!
• Solution 1:
– Never use instance variables in servlets (some books say you
can’t – what they mean is you shouldn’t!).
– Find a way to save information (state) about each user (i.e.
each request) – we’ll see how later …
• Solution 2:
Synchronisation – a lock that makes a variable thread-safe

3. Access – introducing the ServletContext object

Servlet
ServletConfig object – one per servlet (or JSP)
– contains init params
– all requests made to a servlet can access this object
• Web application
ServletContext object – one per web application
• Web applications normally have several servlets/JSPs.
– Used to access web application parameters that need to be seen by all servlets/JSPs in the application.
• A misnomer, as it relates not to a servlet but to the set of servlets and JSPs in the web application.
The web application’s DD specifies the context parameters

<web-app ...> ...
    <servlet>
        <servlet-name>...</servlet-name>
        <servlet-class>...</servlet-class>
    <init-param>
        <param-name>...</param-name>
        <param-value>...</param-value></init-param>
    </servlet> ... + other servlets
    <context-param>
        <param-name>HOP_Email</param-name>
        <param-value>g.tyson@qmul.ac.uk</param-value>
    </context-param>
...
</web-app>

Note: Not inside any servlet. These are parameter namevalue pairs: both are strings.

ServletContext object created and set up when web application is deployed.

4. To access web app parameters in servlet code

ServletContext ctx = getServletContext();
out.println(ctx.getInitParameter(“HOP_Email”));
Context parameters generally more commonly used than Config.
– Typical use (of former) is a DB lookup name.
• Can access ServletContext,
– directly: getServletContext().getInitParameter(…)
– from ServletConfig: getServletConfig().getServletContext().getInitParameter(…)
– Latter is useful if in a method of an auxiliary class e.g. a JavaBean, and only the ServletConfig object has been passed as a parameter.
Same name for get method as when accessing ServletConfig object.

5. ServletContext also has attributes

• Parameters are name-value pairs, where both name and value are strings.
• Attributes are name-value pairs where the name is a String, but the value is an object (that may not be a String).
– accessed by getAttribute(String);
– set by setAttribute(String,Object).
• Running code prior to invoking any servlet in the application:
– E.g. to turn sets of parameters into attribute objects,
• so all servlets only need to deal with objects;
• and don’t have to read the context parameters.
– Implement a ServletContextListener (out of scope here)

6. Servlets – The Basics: Key Points & What we can’t do yet

7. Extracting unknown parameters and multiple values

8. Example: A Big Form

//BigForm.html
<form action="http://localhost:8080/servlet/elem004.ProcessBigForm"method="post">
    Please enter: <br><br>
    Your login: <input type="text" name="Login"> <br><br>
    Your favourite colour:
    <input type="radio" name="Colour" value="blue">Blue
    <input type="radio" name="Colour" value="red">Red
    <input type="radio" name="Colour" value="green">Green <br><br>
    //Single-value parameters.
    Which of these courses you are taking: <br>
    <input type="checkbox" name="Course" value="elem001">ELEM001 <br>
    <input type="checkbox" name="Course" value="elem002">ELEM002 <br>
    <input type="checkbox" name="Course" value="elem003">ELEM003 <br>
    <input type="checkbox" name="Course" value="elem004">ELEM004 <br>
    <input type="submit" value="Send to Servlet">
    //Multiple-value parameter.
</form>
//After BigForm is processed.getParameterNames() returns parameters in no particular order.

//ProcessBigForm.java
//More code here ...
    out.println("<table border=1>");
    // Obtain all the form’s parameters from the request object.
    Enumeration paramNames = req.getParameterNames();
    while (paramNames.hasMoreElements()) {
        String paramName = (String) paramNames.nextElement();
        // Obtain values for this parameter and check how many there are.
        String[] paramValues = req.getParameterValues(paramName);
        if (paramValues.length == 1) { // a single value
            String paramVal = req.getParameter(paramName);
            out.println("<tr><td>" + paramName +"</td><td>"+ paramVal + "</td></tr>");
        }else { // If several values print a list in the table.
            out.println("<tr><td>" + paramName +"</td><td><ul>");
            for (int i = 0; i < paramValues.length; i++)
                out.println("<li>" + paramValues[i] + "</li>");
                out.println("</ul></td></tr>");
        }
    }
    out.println("</table>");
    out.close();
}
11-25 16:07