Servlets by Example. Joe Howse 7 June 2011

Similar documents
Introduction to Servlets. After which you will doget it

Accessing EJB in Web applications

Session 8. Introduction to Servlets. Semester Project

Kamnoetvidya Science Academy. Object Oriented Programming using Java. Ferdin Joe John Joseph. Java Session

Servlet for Json or CSV (or XML) A servlet serving either Json or CSV (or XML) based on GET parameter - This version uses org.json

ServletConfig Interface

Integrate JPEGCAM with WaveMaker

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

Getting started with Winstone. Minimal servlet container

CIS 3952 [Part 2] Java Servlets and JSP tutorial

Advanced Internet Technology Lab # 4 Servlets

Session 9. Introduction to Servlets. Lecture Objectives

JAVA SERVLET. Server-side Programming INTRODUCTION

Servlet. 1.1 Web. 1.2 Servlet. HTML CGI Common Gateway Interface Web CGI CGI. Java Applet JavaScript Web. Java CGI Servlet. Java. Apache Tomcat Jetty

Develop an Enterprise Java Bean for Banking Operations

Université Antonine - Baabda

Lab session Google Application Engine - GAE. Navid Nikaein

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1

CREATE A SERVLET PROGRAM TO DISPLAY THE STUDENTS MARKS. To create a servlet program to display the students marks

CS 112 Introduction to Programming

Chapter 2 How to structure a web application with the MVC pattern

UIMA Simple Server User Guide

Web based Applications, Tomcat and Servlets - Lab 3 -

Servlet Fudamentals. Celsina Bignoli

Distributed Computing

To create a view for students, staffs and courses in your departments using servlet/jsp.

Introduction. This course Software Architecture with Java will discuss the following topics:

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003

SSC - Web applications and development Introduction and Java Servlet (I)

A.1 JSP A.2 JSP JSP JSP. MyDate.jsp page contenttype="text/html; charset=windows-31j" import="java.util.calendar" %>

LAB 1 PREPARED BY : DR. AJUNE WANIS ISMAIL FACULTY OF COMPUTING UNIVERSITI TEKNOLOGI MALAYSIA

Servlets. An extension of a web server runs inside a servlet container

Demonstration of Servlet, JSP with Tomcat, JavaDB in NetBeans

Using Java servlets to generate dynamic WAP content

sessionx Desarrollo de Aplicaciones en Red A few more words about CGI CGI Servlet & JSP José Rafael Rojano Cáceres

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests

How to structure a web application with the MVC pattern

Appendix: Assorted Sweets

WWW Architecture I. Software Architecture VO/KU ( / ) Roman Kern. KTI, TU Graz

Penetration: from application down to OS

2. Follow the installation directions and install the server on ccc. 3. We will call the root of your installation as $TOMCAT_DIR

Introduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web

Life Without NetBeans

&' () - #-& -#-!& 2 - % (3" 3 !!! + #%!%,)& ! "# * +,

SDN Community Contribution

CE212 Web Application Programming Part 3

Implementation Architecture

Backend. (Very) Simple server examples

J2ME With Database Connection Program

Supplement IV.E: Tutorial for Tomcat For Introduction to Java Programming By Y. Daniel Liang

WHITE LABELING IN PROGRESS ROLLBASE PRIVATE CLOUD

Implementation Architecture

STRUTS 2 - HELLO WORLD EXAMPLE

Advanced Web Technology

Unit 4 - Servlet. Servlet. Advantage of Servlet

The Servlet Life Cycle

COMP9321 Web Application Engineering

Handout 31 Web Design & Development

COMP9321 Web Application Engineering

JAVA SERVLET. Server-side Programming ADVANCED FEATURES

Session 10. Form Dataset. Lecture Objectives

4.1 The Life Cycle of a Servlet 4.2 The Java Servlet Development Kit 4.3 The Simple Servlet: Creating and compile servlet source code, start a web

Database Applications Recitation 6. Project 3: CMUQFlix CMUQ s Movies Recommendation System

Advanced Topics in Operating Systems. Manual for Lab Practices. Enterprise JavaBeans

INTERNET PROGRAMMING TEST-3 SCHEME OF EVALUATION 1.A 3 LIFE CYCLE METHODS - 3M 1.B HTML FORM CREATION - 2 M

Java Servlets. Preparing your System

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

AJP. CHAPTER 5: SERVLET -20 marks

Welcome To PhillyJUG. 6:30-7:00 pm - Network, eat, find a seat 7:00-7:15 pm - Brief announcements 7:15-8:30 pm - Tom Janofsky's presentation

An implementation of Tree Panel component in EXT JS 4.0

Tutorial: Developing a Simple Hello World Portlet

Java Card 3 Platform. Peter Allenbach Sun Microsystems, Inc.

EXPERIMENT- 9. Login.html

Unit-4: Servlet Sessions:

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps.

Cloud Computing Platform as a Service

Connecting the RISC Client to non-javascriptinterfaces

ICOM 5016 Database Systems. Database Users. User Interfaces and Tools. Chapter 8: Application Design and Development.

Servlet. Web Server. Servlets are modules of Java code that run in web server. Internet Explorer. Servlet. Fire Fox. Servlet.

3.2 Example Configuration

Advantage of JSP over Servlet

Introduction to Server-Side Technologies

Component Based Software Engineering

Servlet Basics. Agenda

Stateless -Session Bean

A Servlet-Based Search Engine. Introduction

Construction d Applications Réparties / Master MIAGE

Servlet and JSP Review

Web Application Architecture (based J2EE 1.4 Tutorial)

Introduction. This course Software Architecture with Java will discuss the following topics:

JavaServer Pages (JSP)

Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets

Get the cookies from the service request: Cookie[] HttpServletRequest.getCookies() Add a cookie to the service response:

Administration Console Extension Developer's Guide

Configuring Tomcat for a Web Application

HTTP status codes. Setting status of an HTTPServletResponse

Module 4: SERVLET and JSP

Chettinad College of Engineering and Technology CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY

Transcription:

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 java.io.ioexception; import java.io.printwriter; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import 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.