Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
Introductory Databases 2016-17
SSC Introduction to DataBases 1
Lecture 17 & 18
Introduction to Web applications
Introduction
HTTP
Servlets
JSP
Session Tracking
Security issues
Client Server Systems
Consider running Java programs:
Application
Applet
Client-Server models
Application
Installed on local machine
Runs on local machine
Accesses resources on local machine
[Of course - it’s never as simple as this!]
Applet
Runs in ‘Browser’
Runs on local machine
Downloaded from server
Accesses remote resources [and possibly local ones]
Once held up as the paradigm for delivering applications
Appropriate when need local processing and interactivity
Issues when [local or remote] data must be manipulated (e.g. security)
Client Server Systems
Split applications Client
user of services
Server provider of services
At its simplest Client interacts with user
Server provides services
Classic business model is 3 tier - client/server/DB
Examples
File-server
Name server
Web server
Display server e.g. Xwindows etc.
Mail server
DB server
Etc. etc.
Introductory Databases 2016-17
SSC Introduction to DataBases 2
Web services
Web Browser Web Server HTTP
Requests
resources
... And usually:
Web Browser Web Server HTTP
Requests
resources
DataBase
Server
... And usually:
Web Browser Web Server HTTP
Requests
resources
DataBase
Server
JDBC
?
Firewall
Actually more complex than this, but aim is to restrict access to critical components
Mechanisms are general – not just http and browsers
HTTP
Protocol Requests:
get, post, put, head, delete, trace, options, connect
URL
Parameters
Deliver resources: Text (e.g. HTML)
Images
Javascript
Etc
Again, it is usually more complex than this
Webserver
Receives requests: Parses request
Processes request
Returns response: Deliver local resources
Re-direct
Error
Often there is complex processing: Build response:
Computation
DB access
Presentation
Webserver
Initially delivered static resource
File – HTML, Images etc
Need to be able to generate dynamic content:
dependent on state
for efficiency
Need to process input
Introductory Databases 2016-17
SSC Introduction to DataBases 3
Server side processing
Historically, CGI provided a mechanism to integrate server side processing Web server could invoke arbitrary programs
Typically used a scripting language – e.g. Perl
Could integrate with databases etc
But this is expensive: Load & start application for each request
Request is, typically, very small
Java server side processing
Java provides two primary mechanisms for implementing server side processing
Servlets
JSP
These are actually just different views on the same mechanism
Provide full power of Java
Classes to support this application
Efficient for light weight processing
[Note: there are many alternatives – both in Java and other frameworks]
Servlets
Java code that implements server side functions
Invoked by web server to handle requests
Specified by URL
Access to parameters of HTTP request
Performs processing
(Typically) generates a page as response
[Actually much more general than this]
What happens when servlet is invoked?
Lifecycle:
[Initialise] init (ServletConfig config)
called once to initialise servlet
Call servlet to service request service (ServletRequest request, ServletResponse response)
typically runs in a new thread
[Cleanup and close] destroy()
So, it’s lightweight:
little overhead for each request
So …..
The servlet is initialised once - typically when first invoked
Each request is handled within a separate thread So code should be thread safe!
See SingleThreadModel
Cleanup takes place when servlet no longer required
The aim:
To create a lightweight mechanism
With the full power of Java
To create a general mechanism
Easy to build standard applications:
Framework
Handling of low-level details provided:
Request loop, dispatching, io objects …
Parameter parsing …
Introductory Databases 2016-17
SSC Introduction to DataBases 4
So, how do we do it?
Create a class to implement the servlet This must extend one of:
GenericServlet
HttpServlet
These implement the interface Servlet
These two (abstract) classes provide default implementations of methods
Over-ride the definition of some methods to implement required function
Interface Servlet
void init (ServletConfig config)
ServletConfig getServletConfig()
String getServletInfo() void service (ServletRequest request, ServletResponse response)
void destroy()
HttpServlet
Provides default implementations of methods
Methods to handle requests void doGet(HttpServletRequest request, HttpServletResponse response)
void doPut(HttpServletRequest request, HttpServletResponse response)
etc
At its simplest:
over ride implementations of request handler(s)
Parameters
HttpServletRequest interface has methods to obtain parameters
Enumeration getParameterNames()
String getParameter(String name)
String[] getParameterValues (String name)
and many more ……..
Output
HttpServletResponse interface provides methods to handle the response from the servlet void setContentType (String type)
PrintWriter getWriter()
ServletOutputStream getOutputStream()
and many more ……..
Skeleton for servlet
import javax.servlet.*
import javax.servlet.http.*
import java.io.*
public class myServlet extends HttpServlet
{
void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType (“text/html”);
PrintWriter out =response.getWriter();
.
.
out.close()
}
}
Introductory Databases 2016-17
SSC Introduction to DataBases 5
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public final class Hello extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html>");
writer.println("<head>");
writer.println("<title>Test Servlet</title>");
writer.println("</head>");
writer.println("<body>");
writer.println("<h1>Test Servlet</h1>");
writer.println("This is a minimal test servlet.");
writer.println("</body>");
writer.println("</html>");
}
}
Output
<html>
<head>
<title>Test Servlet</title>
</head>
<body>
<h1>Test Servlet</h1>
This is a minimal test servlet.
</body>
</html>
Test Servlet
This is a minimal test servlet.
Accessing ServletRequest object
public class HelloDB extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html>");
writer.println("<head>");
writer.println("<title>Test Parameter Servlet</title>");
writer.println("</head>");
writer.println("<body>");
writer.println("<h1>Test Parameter Servlet</h1>");
writer.println("This is a servlet to test getParameter.");
writer.println("<br><br>It outputs the value of a parameter (testparam)");
writer.println("<br> <br> Parameter: " + request.getParameter("testparam") + "<br>");
Simple Pattern: Request-response cycle
User calls URL
Web page is delivered including HTML form
User fills and submits form to servlet address
Servlet processes request and generates web page as a response
HTML Form
<HTML>
<HEAD>
<TITLE>A Sample FORM using GET
</TITLE>
</HEAD>
<BODY>
<H1 ALIGN="CENTER">A sample form</H1>
<FORM ACTION=“TestForm“ METHOD="GET">
Student Id: <INPUT TYPE="TEXT" NAME=“FirstParameter">
<BR>
<CENTER>
<INPUT TYPE="SUBMIT" VALUE="Submit Lookup">
</CENTER>
</FORM>
</BODY>
</HTML>
HTML Form
<HTML>
<HEAD>
<TITLE>A Sample FORM using GET
</TITLE>
</HEAD>
<BODY>
<H1 ALIGN="CENTER">A sample form</H1>
<FORM ACTION=“TestForm“ METHOD="GET">
Student Id: <INPUT TYPE="TEXT" NAME=“FirstParameter">
<BR>
<CENTER>
<INPUT TYPE="SUBMIT" VALUE="Submit Lookup">
</CENTER>
</FORM>
</BODY>
</HTML>
This specifies the URL and
method Type and name
of parameter
Submit button
Introductory Databases 2016-17
SSC Introduction to DataBases 6
Lecture 18
JSP
Scriptlets
Directives
Tags
JSP
Underlying mechanism is the same as servlets
JSP is translated into a servlet before execution
Oriented towards output rather than algorithms Output (e.g. html) with embedded code
rather than code generating output
What happens when JSP is invoked?
Translate into servlet
Initialise
jspInit
Call servlet to service request
_jspService
Cleanup and close
jspDestroy
So what is in a JSP?
Unless special action is signalled contents of page are output
Scriptlets provide a mechanism to execute java code
Directives instruct JSP container to perform actions
Tags provide a higher level mechanism to access java functionality
A minimal JSP
<html>
<head>
<title>Test JSP</title>
</head>
<body>
<h1>Our first JSP</h1>
This is a minimal (and pointless) JSP.
</body>
</html>
Scriptlets
<%= ……….%> encloses a Java expression
the expression is evaluated at execution time and its string representation is output
<%= new java.util.Date() %>
This creates a new date object and outputs its string representation as part of the page
Introductory Databases 2016-17
SSC Introduction to DataBases 7
Example with a simple scriptlet
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<%= new java.util.Date() %>
</body>
</html>
Example with a simple scriptlet Generated Servlet
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<%= new java.util.Date() %>
</body>
</html>
out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n");
out.write(" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
out.write("\n");
out.write("\n");
out.write(" \n");
out.write(" <html>\n");
out.write(" <head>\n");
out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
out.write(" <title>JSP Page</title>\n");
out.write(" </head>\n");
out.write(" <body>\n");
out.write(" <h1>Hello World!</h1>\n");
out.write(" ");
out.print( new java.util.Date() );
out.write("\n");
out.write("\n");
out.write(" </body>\n");
out.write("</html>\n");
out.write("\n");
Scriptlets
<% ……….%>
encloses a fragment of Java code
this code is copied into the _jspService method
can include arbitrary Java (but obviously must be correct!)
Scriptlet in fragment of JSP
<body>
Is A greater than B?
The value of A is <%= a %>
The value of B is <%= b %>
A is
<% if (a<=b) { %>
not
<% } %>
greater than b
</body>
Scriptlet in fragment of JSP
<body>
Is A greater than B?
The value of A is <%= a %>
The value of B is <%= b %>
A is
<% if (a<=b) { %>
not
<% } %>
greater than b
</body>
Fix it!
Scriptlets in fragment of JSP generated fragment of servlet
<body>
Is A greater than B?
The value of A is <%= a %>
The value of B is <%= b %>
A is
<% if (a<=b) { %>
not
<% } %>
greater than b
</body>
out.write(" <body>\n");
out.write(" ");
out.write("\n");
out.write(" ");
out.write("\n");
out.write("Is A greater than B? <br> <br>\n");
out.write("The value of A is ");
out.print( a );
out.write("<br>\n");
out.write("The value of B is ");
out.print( b );
out.write("<br>\n");
out.write("<br>\n");
out.write("A is\n");
if (a<=b) {
out.write("\n");
out.write("not\n");
}
out.write("\n");
out.write("greater than b\n");
out.write("</body>\n");
out.write("</html>\n");
Introductory Databases 2016-17
SSC Introduction to DataBases 8
Scriptlets
<%! ………..%>
encloses a Java declaration
Variables are declared as instance variables of the servlet class
Methods belong to the servlet class
Comments
<%-- ……….. --%>
JSP comments
Java comments can be used inside scriptlets
HTML comments can be used to generate comments within output page
Directives
These are like compiler directives
They control translation time options
Indicated by
<%@ …….. %>
Directives
page set attributes of this JSP e.g. errorpage, isErrorPage, contentType
include substitute the contents of the file
<%@ include file = “ foo.html” %>
taglib specifies additional tag libraries to use
At compile time!
Tags
Provide a convenient mechanism to support common actions
There are standard tag libraries to support standard actions
A programmer can define their own tag libraries
Use eg. <jsp:action> …….. </jsp:action>
Tag library - jsp
<jsp:include>
<jsp:forward>
<jsp:param>
<jsp:useBean>
……..
Introductory Databases 2016-17
SSC Introduction to DataBases 9
Jsp:include
Includes dynamic content
<jsp:include page=URL flush=true/>
This will include the content returned from the specified resource
E.g. a servlet
Dynamically at execution time jsp:forward
Forwards the request to the specified URL
<jsp:forward page=URL/>
Terminates the current JSP and transfers the request to the specified resource
jsp:param
Supplies parameters to the tag
<jsp:param name=“ParamName”
value=“ParamValue”/>
Parameters
<jsp:forward page=“foo.jsp”>
<jsp:param name=“mode”
value=“brief” />
</jsp:forward>
Implicit objects
There are a several objects which are implicitly created and which the jsp can access
application
config, exception, out, response …
request
session
JSP vs Servlets
Use Servlets when you are mostly writing algorithms
Use JSP when mostly generating output
A typical application will utilise both Servlets and JSP Separate logic and presentation
Model 2
Example of MVC pattern