programs that run on a web server acting as middle layer between HTTP request and databases or other applications. |
Used for client requests that cannot be satisfied using pre-built (static) documents. |
Used to generate dynamic web pages in response to client. |
Web Browser | Sending Requests to a Web Server |
Web Server | hold/return static web pages – e.g. index.html does not respond to user input. |
Server Side Programs | different technologies written in various languages – e.g. CGI scripts, Java Servlets (and JSPs – later), PHP scripts
– Call to http://localhost:8080/servlet/myhelloservlet.HelloServlet
– Not web-browsing but executing program (servlet)
|
Dynamic response | – database lookup, calculation etc. |
We’ll look at the Java solution | how to write servlets; how the container (Tomcat) works. |
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(“Hello!”);
out.close();
}
}
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(“Hello”);
if (userName != null)
out.println(userName);
else
out.println(“mystery person”);
out.println(“”);
out.close();
}
}
//Page that asks for weight (kg) and height (cm) :Write the HTML and the HTTP Request (GET)
- 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(“
”);
out.println(“Your BMI is: ” + weight/ht_squared + “”);
out.close();
}
}
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("
");
out.println("Hello,"+name);
out.println("Your salary is"+salary);
out.println("");
out.close();
} // end of method
} // end of class
NO main method | public static void main(String[] args) |
NO constructor | There is one (default) constructor but the developer should never write an explicit constructor – Why——servlet lifecycle |
Two key (service) methods | doGet(); doPost() |
Tracing the user data |
– e.g. name attribute inside an HTML element
– name in HTTP request message
– argument in request.getParameter(...)
|
String(int/double required) | then have to use appropriate method on this String to convert - Integer.parseInt(); - Double.parseDouble(); |
Finding the servlet |
– tag action attribute e.g.
– Used by deployment descriptor, web.xml (see later), to map to the corresponding servlet class.
|
Although a servlet can be a completely self-contained program, to ease server-side programming, generating content should be split into |
The business logic (content generation), which governs the relationship between input, processing, and output.
|
The presentation logic (content presentation, or graphic design rules), which determines how information is presented to the user. | |
controller | the servlet handles the HTTP protocol and coordination of which other servlets and auxiliary class methods to call |
model | Java classes/JavaBeans handle the business logic |
view | Java Server Pages handle presentation logic |
Efficient |
– Servlets run in the JVM. Each request is serviced using a thread rather than a new process (so lower overhead).
- Though some scripting languages, e.g. perl on certain web servers do this now.
|
Convenient | – Provides infrastructure that parses and decodes HTML forms. |
Powerful |
– Can communicate directly with web server.
– Multiple servlets can share database connections.
– Simplifies session tracking.
|
Portable | – Written in Java and follows standard API. |
Secure |
– CGI often executed using O/S shells, which can cause many security breaches.
– Array checking & exception handling is automatic in Java.
|
Inexpensive |
– Many Java web servers are freely available.
|
request | Read any data sent by the user |
Look up information embedded in HTTP request | |
Generate results.
|
|
response |
Format results inside a document (e.g. HTML, XML, GIF, EXCEL).
|
Set appropriate HTTP response parameters.
|
|
Send the document back to the client.
|
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.
}
GET /myServlet/BMIInfo height=156&name=paula+fonseca HTTP/1.1
public class BMIServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throwsIOException, ServletException {// ...String ht = request.getParameter(“height”);// ...}}
Constructor (no arguments) |
– not written or called by a developer
– called by the container
|
public void init() |
– called after constructor
– called once, at the beginning (so potentially useful for initialisation of, e.g. databases)
– can be overridden by the developer
|
public void service(…) |
– rarely overridden by thedeveloper
– called everytime
|
public void doGet() / public void doPost() |
– must be written by the developer
– must match the HTTP method in in the HTML
|
public void destroy() | – must be written by the developer |
//For each servlet in the web application.
//Internal name of servlet can be “anything” following XML rules.
…
//maps internal name to fully qualified class name (except without .class)
…
//maps internal name to public URL name e.g. /makebooking
…
…
...
- HTML:- Server (webapps):WEB-INF/classes/Echo.class...... ..... ...... ....... - HTML:- Server (webapps):WEB-INF/classes/foo/Name.class...... ..... ...... .......
//SmallForm.html
Sending Form Information to a Servlet
//the Deployment Descriptor (web.xml) and the servlet
smallForm
SmallFormServlet
smallForm
/servlet/elem004.ProcessSmallForm
Level 1 | WEB-INF (folder) and .html, .jsp |
Level 2 | (inside WEB-INF folder): web.xml and classes (folder) |
Level 3 | (inside classes folder): servlet .class files (and other “business” class files e.g. JavaBeans) |
Hello World Servlet
S1
lecturersEmail
[email protected]
//Container reads these & gives them to ServletConfig object.
out.println(getServletConfig().getInitParameter(“lecturersEmail”));Returns the servlet’s ServletConfig object (all servlets have this method).Getting a parameter value from the ServletConfig object; this code is in servlet.
Step 1 | container reads the deployment descriptor |
Step 2 | container creates new ServletConfig object |
Step 3 |
container creates name/value pair (Strings) for each servlet init-param
|
Step 4
|
container passes references to these to the ServletConfig object
|
Step 5 | container creates new instance of the servlet class |
Step 6 |
container calls servlet’s init() method passing in reference to the ServletConfig object
|
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(“You are ” + age + “ weeks old”);
out.println(“”);
out.close();
}
}
...
...
...
...
...
... + other servlets
HOP_Email
[email protected]
...
Note: Not inside any servlet. These are parameter namevalue pairs: both are strings.
How to call a servlet in an HTML form | What a deployment descriptor does |
How to write a servlet | Where to deploy files |
How to access client information | Servlet life-cycle |
Initialisation |
– ServletConfig
– ServletContext
|
Have a conversation with a client |
– Shopping basket
– Session object
|
Run any code before a servlet starts |
– E.g. Database set up
– Listeners
|
Send client information, or control, to another servlet/JSP |
– Could be in another web server
– Redirect and forward
|
String getParameter(String) |
parameter name is known:
– returns null if unknown parameter;
– returns "" (i.e. empty string) if parameter has no value.
|
Enumeration getParameterNames() | obtain parameter names |
String[] getParameterValues(String) | obtain an array of values for each one: – returns null if unknown parameter;
– returns a single string ("") if parameter has no values. Case sensitive.
|
//BigForm.html
//After BigForm is processed.getParameterNames() returns parameters in no particular order.
//ProcessBigForm.java
//More code here ...
out.println("");
// 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("" + paramName +" "+ paramVal + " ");
}else { // If several values print a list in the table.
out.println("" + paramName +" ");
for (int i = 0; i < paramValues.length; i++)
out.println("- " + paramValues[i] + "
");
out.println("
");
}
}
out.println("
");
out.close();
}