Lecture 8 - Java Servlets
Lecture 8 - Java Servlets
{ Resp.SetContentType(“text/plain”);
}
HttpServlet
public class MyServlet extends
javax.servlet.http.HttpServlet {
public void doGet(ServletRequest req, ServletResponse
resp)throws ServletException, IOException {
resp.SetContentType(“text/plain”);
PrintWriter out = resp.getWriter();
out.println(“Hello, world”);
}
public void doPost(ServletRequest req, ServletResponse
resp)throws ServletException, IOException {
doGet(req, resp);
}
HttpServlet
doPost does three things
Set output type “text/plain” MIME type
getWriter() method for out stream
Print on out stream
getLastModified() method
To cache content if content delivered by a servlet has not
changed
Return Long =time content last changed
Default implementation returns a negative number – servlet
doesn’t know
getServletInfo() method
Returns String for logging purposes
Web Applications
Consists of a set of resources including
Servlets, Static content, JSP files, Class libraries
Servlet context:
a particular path on server to identify the web application
Servlets have an isolated, protected environment to operate in
without interference
ServletContext class where servlets running in same context can
use this to communicate with each other
Example servlet context: /catalog
request.getContextPath() + “/servlet/CatalogServlet”
Web App Structure
Directory tree
Static resources: /
getAuthType()
Forms and Interaction
<form method=get action=“/servlet/MyServlet”>
Username: <input type=text name=“userid” size=20>
/servlet/MyServlet?userid=Jeff&pass=1234
This is called a query string (starting with ?)
POST Method
<form method=post …
Post method does not append parameters to action URL:
/servlet/MyServlet
Instead, parameters are sent in body of request where the password is
not visible as in GET method
POST requests are not idempotent
From Mathematics – an idempotent unary operator definition:
whenever it is applied twice to any element, it gives the same result as if
it were applied once.
Cannot bookmark them
Are not safely repeatable
Can’t be reloaded
browsers treat them specially, ask user
HEAD, and Other Methods
HEAD – returns headers only
PUT, DELETE – create and remove resources from the web server
simultaneously
Threadsafe – not using class variables since one
session.setAttribute(“hits”,new Integer(34));
Server assigns unique session ID, stored in a cookie
JDBC
Database
Collection of data
DBMS
Database management system
Storing and organizing data
SQL
Relational database
Structured Query Language
JDBC
Java Database Connectivity
JDBC driver
JDBC Steps
1. Load the driver class
2. Get a connection
3. Create a statement
…
Processing Multiple ResultSets or
Update Counts
Execute the SQL statements
Identify the result type
ResultSets
Update counts
Obtain result
getResultSet
getUpdateCount
JDBC 2.0 Optional Package javax.sql
Package javax.sql
DataSource
ConnectionPoolDataSource
PooledConnection
RowSet