Download Lecture Notes for SSC2 part C

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
Client Server Systems
Lecture 28
Introduction to Web applications
Introduction
HTTP
Servlets
JSP
Session Tracking
Security issues
Application
Installed on local machine
Runs on local machine
Accesses resources on local machine
[Of course - it’s never as simple as this!]
Consider
Application
Applet
Client-Server
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 back-end processing
Classic business model is 3 tier - client/server/DB
Examples
File-server
Name server
Web server
Display server e.g. Xwindows
Mail server
DB server
etc etc
Web services
... And usually:
Requests
Web Browser
Requests
Web Server
HTTP
Web Browser
resources
HTTP
Web Server
DataBase
Server
resources
... And usually:
HTTP
Firewall
Protocol
Actually more complex than this, but aim
is to restrict access to critical components
Requests:
JDBC
?
Requests
get, post, put, head, delete, trace, options, connect
URL
Parameters
Web Browser
HTTP
Web Server
resources
Mechanisms are general – not just http
and browsers
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
DataBase
Server
Deliver resources:
Text (e.g. HTML)
Images
Javascript
Etc
Again, it is usually more complex than this
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
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]
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
What happens when servlet is
invoked?
So, it’s lightweight:
little overhead for each request
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()
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 …
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
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:
Interface Servlet
void init (ServletConfig config)
ServletConfig getServletConfig()
String getServletInfo()
void service (ServletRequest request, ServletResponse
response)
void destroy()
Parameters
HttpServletRequest interface has
methods to obtain parameters
Enumeration getParameterNames()
String getParameter(String name)
String[] getParameterValues (String name)
over ride implementations of request handler(s)
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()
}
}
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>");
HTML Form
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
This specifies
the URL and
method
<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>
<HEAD>
<TITLE>A Sample FORM using GET
Type and name
</TITLE>
of parameter
</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>
Submit
button
Lecture 30
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
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>
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
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
Example with a simple scriptlet
Example with a simple scriptlet
Generated Servlet
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@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() %>
<html> out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n");
\"http://www.w3.org/TR/html4/loose.dtd\">\n");
<head> out.write("
out.write("\n");
out.write("\n");
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
out.write(" \n");
<title>JSP
Page</title>
out.write("
<html>\n");
</head> out.write(" <head>\n");
out.write("
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
<body> out.write("
<title>JSP Page</title>\n");
out.write(" </head>\n");
<h1>Hello
World!</h1>
out.write(" <body>\n");
out.write("
<h1>Hello
World!</h1>\n");
<%= new
java.util.Date()
%>
</body>
</html>
</body>
</html>
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");
Scriptlet in fragment of JSP
Scriptlets
<% ……….%>
encloses a fragment of Java code
this code is copied into the _jspService
method
can include arbitrary Java (but obviously
must be correct!)
<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>
Scriptlets in fragment of JSP
Scriptlet 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 %>
<body>
out.write(" <body>\n");
out.write("
");
Is A greater than B? out.write("\n");
out.write("
");
out.write("\n");
The value of A is <%= a %>
out.write("Is A greater than B? <br> <br>\n");
out.write("The
The value of B is <%=
b %>value of A is ");
out.print( a );
A is
<% if (a<=b) { %>
not
<% } %>
greater than b
</body>
out.print( b );
A is
out.write("<br>\n");
out.write("<br>\n");
<% if (a<=b) { %> out.write("A is\n");
if (a<=b) {
out.write("\n");
not
out.write("not\n");
}
<% } %>
out.write("\n");
out.write("greater than b\n");
greater than b
out.write("</body>\n");
out.write("</html>\n");
</body>
out.write("<br>\n");
out.write("The value of B is ");
Fix it!
Scriptlets
<%! ………..%>
encloses a Java declaration
Variables are declared as instance variables of
the servlet class
Methods belong to the servlet class
Directives
Comments
<%-- ……….. --%>
JSP comments
Java comments can be used inside
scriptlets
HTML comments can be used to generate
comments within output page
Directives
At compile time!
These are like compiler directives
They control translation time options
Indicated by
<%@ …….. %>
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
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>
……..
Jsp:include
Dynamically at execution time
Includes dynamic content
<jsp:include page=URL flush=true/>
This will include the content returned
from the specified resource
E.g. a servlet
jsp:param
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
Parameters
Supplies parameters to the tag
<jsp:param name=“ParamName”
value=“ParamValue”/>
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:forward page=“foo.jsp”>
<jsp:param name=“mode”
value=“brief” />
</jsp:forward>
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
Lecture 31
Session Tracking
Hidden forms
URL rewriting
Cookies
Session Tracking
HTTP
HTTP is a stateless protocol
No session – each request is independent
Appropriate when just retrieving resources:
Request
Response
Efficient and simple:
Server (and client) do not need to manage
connections
A good solution for web browsing!
Requirements for more
sophisticated systems
How?
Need to track a user within a session:
Four main options
Transaction requires multiple requests
Need to pass state between requests
e.g.
[Hidden] forms
URL rewriting
Cookies
[Sessions]
User login
Non-trivial transactions
shopping basket
Need to track a user across sessions:
Personalise
Track usage
Notes:
only first two are guaranteed to work
This is not Java specific
JavaScript, Applets, images and many other techniques can
also be used to track users
For example:
Registration & Login
Used to:
Provide some security
Identify user
Can be counter productive:
Reluctance to register
Not (necessarily) secure
Really needs user tracking over session
We don’t want to login to every page
URL rewriting
Embed state information in the URL of links
of the response:
Usually include parameters to carry state
Can use Address in simple cases
e.g. language
Reliable - doesn’t rely on protocol version,
browser, security settings
Cumbersome, session only, some problems
(e.g. back)
Hidden forms
Embed state in hidden form in
response:
This information is submitted with next
request
Reliable - should (nearly) always work
Session only
Again, some problems with e.g. back,
cumbersome, session only
Cookies
A cookie is stored with:
Domain
Normally the domain that set the cookie
Path
By default, the path that set the cookie
A cookie will be sent with requests that
match its domain and path
Java support for cookies
Servlets and JSP provide convenient
support for cookies
Accessible through HTTPServletRequest
Cookies
Cookies are embedded in the HTTP
request and response
Cookies are stored on the client
Cookies are transmitted with each
request from the client (e.g. browser)
Cookies are name value pairs
The value is a string
Cookies
Convenient
May not always work:
Security concerns:
Browser, proxy, firewall
Stored locally – so machine specific
Requires cookie support
So should allow for failure
Can work across sessions
Java support for cookies
Cookie myCookie (“Language”,
“English”)
response. addCookie(myCookie)
To get cookies
Accessible through
HTTPServletResponse
To set cookies
Cookie[] myCookies = request.getCookies()
Methods for Cookies
getName()
getValue()
getDomain()
getPath()
getMaxAge()
setName(String)
setValue(String)
setDomain(String)
setPath(String)
setMaxAge(int)
…...
……….
Java support for sessions
Sessions are manipulated through an
HttpSession object
HttpSession mySession=request.getSession()
Attributes can be objects (not just strings)
setAttribute(name, value)
getAttribute(name)
getAttributeNames()
Lecture 32
Security & concurrency in web applications
Security:
Password on HTML forms
HTTPS
SQL Injection
Concurrency:
Threads
Transactions
Sessions
Sessions provide a reliable abstraction
to support session tracking:
Normally implemented through cookies
Fallback to URL re-writing
Session is identified by a session ID
Using Sessions and Cookies
HttpSession session = request.getSession(true);
ShoppingCart currentItems = (ShoppingCart)session.getValue(“currentItems");
Sessions have a finite life
For ‘standard’ applications (e.g. Shopping
Carts) you should probably use a class library
rather than implementing your own
Security
There are many security concerns:
Control access to sensitive resources
authentication
Secure transmission of sensitive data
eavesdropping
Security of applications
.....
Authentication
Password type in HTML forms:
<INPUT TYPE="password" NAME="testparam">
Declares that field is a password
http://........../TestPasswd?testparam=mypassword
.... Ooops!
So, it inhibits echo - but that’s all!
..... In general
We must secure sensitive data:
Authentication data, CC details, ......
HTTPS provides encrypted channel:
Secure against eavesdropping
Cost:
Computation & bandwidth of encryption
Session
SQL Injection
Remedy
If SQL command is constructed from a
string input from user, then we are
vulnerable to attack:
Input studentID:
“123 or 1==1”
SELECT * FROM modules WHERE id=123 or 1=1
“123;drop table modules;”
SELECT * FROM modules WHERE id=123;drop table modules;
Pre-compile commands:
PreparedStatement in Java
Filter string to remove dangerous characters:
unreliable
Concurrency
There are two main areas of concern:
Threads
Transactions
Threads
Multiple calls to the same servlet can
run concurrently in separate threads:
Ensure implementation is threadsafe
Enforce single thread execution:
Reduces responsiveness
Transactions
Database can handle multiple requests
Independent of whether servlet is threadsafe:
From same or multiple servlets
Implement transactions to ensure atomic
operations are implemented atomically:
E.g. Bank transfers
Guard against:
Interference
failure