Download Servlets by Example

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Servlets by Example
Joe Howse
7 June 2011
What is a servlet?
● A servlet is a Java application that receives HTTP requests as input and
generates HTTP responses as output.
○ As the name implies, it runs on a server.
○ Dependency: A "servlet container" such as Jetty or Apache Tomcat.
● A servlet is not similar to an applet.
○ An applet's access to server-side files is unprivileged and slow
(requiring downloads) because the applet itself runs client-side.
● Let's consider a step-by-step approach to setting up a simple servlet:
1. Get and configure Jetty.
2. Create the necessary directory tree for the servlet.
3. Write a webpage as a front-end.
4. Write a config file.
5. Write, compile and deploy the Java code.
6. Test it!
Setting up Jetty
● Follow the instructions at:
○ http://docs.codehaus.org/display/JETTY/Quick+Start
○ At the download step, you want the latest stable version from:
■ http://download.eclipse.org/jetty/
● On Dalhousie's bluenose server, adapt the instructions as follows:
○ $JETTY_HOME should be some web-accessible folder.
■ ex. ~/public_html/jetty
○ You should choose an unused port number between 4001 and 4030.
■ I am using 4020 right now, so choose something else.
○ Your test servlet can be accessed at:
■ http://bluenose.cs.dal.ca:####/
■ (Here, #### should be replaced by your port number.)
Directory tree
$JETTY_HOME/webapps/MyServlet/
index.html
WEB-INF/
web.xml
classes/MyServlet/
*.class
*.java
build.sh
lib/
*.jar
● A servlet must include:
○ statically linked code (.class)
○ configuration (.xml)
● Optionally, it may include:
○ dynamically linked code (.jar)
○ front-end website scripts (.html, .
php, etc.) and content (.jpg, etc.)
● Just for convenience, we are putting our
source code (.java) and build script
(build.sh) inside the servlet directory
tree too.
○ These are not used at run-time.
index.html
<html><body>
<form method="get"
action="MyServlet">
<input type="text"
id="query"
name="query"
size="50"/>
<input type="submit"
value="Submit"/>
</form>
</body></html>
● Our webpage is an input
form that sends to our
servlet a get request with a
field called query.
● Our servlet is called
MyServlet.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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">
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
● Our web.xml config file specifies the servlet name, paths, etc.
MyServlet.java (1/2)
package MyServlet;
import
import
import
import
import
import
import
java.io.IOException;
java.io.PrintWriter;
javax.servlet.ServletException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
javax.servlet.ServletConfig;
public class MyServlet extends HttpServlet {
// Initialize servlet and any back-end model it uses.
@Override public void init(ServletConfig config) throws ServletException {
super.init();
// Initialize back-end model here.
}
// Respond to GET request.
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String query = request.getParameter("query");
out.println("<html><body>Your query was \"" + query + "\"!</body></html>");
}
// Continued on next slide. ...
MyServlet.java (2/2)
// ... Continued from previous slide.
// Respond to POST request.
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response); // Here, POST is handled the same as GET.
}
// Return description of servlet.
@Override public String getServletInfo() {
return "MyServlet is a minimal example, echoing back a query string.";
}
}
● Our MyServlet.java source file defines the mapping from requests to
responses.
● Our simple example could be extended to:
○ Handle errors.
○ Initialize and use an instance of another class as its back-end.
build.sh
#!/bin/sh
# Configuration variable.
# The path to Jetty.
JETTY_HOME=~/public_html/jetty
# Build command.
javac -cp $JETTY_HOME/lib/servlet-api-2.5.jar MyServlet.java
● Our build script compiles MyServlet.java and links it with the required
library in Jetty.
● Do not forget to set executable permission for the script.
○ chmod +x build.sh
Testing MyServlet
● Run the build script!
○ ./build.sh
● Navigate to $JETTY_HOME and run:
○ java -jar start.jar
● Direct your Web browser to:
○ http://bluenose.cs.dal.ca:####/MyServlet
■ (Here, #### should be replaced by your port number.)
Summing up
● Writing and deploying a minimal servlet involves just a few steps.
● The complexity is not much greater than scripting solutions, such as:
○ PHP, CherryPy (Python), Ruby on Rails (Ruby)
● A servlet can integrate seamlessly with other back-end Java code.