Title: Servlets: Leftover Odds and Ends (Most apply to JSPs as well, duh
1ServletsLeftover Odds and Ends(Most apply to
JSPs as well, duh.)
- Representation and Management of Data on the
Internet, 2007 - CS Department, HUJI
2A Warning Dont Panic
- Many of the examples in this presentation are
using various features not discussed throughout
this course. - There is not need to understand them in a deeper
extent than the understanding of the relevant
examples. - They are there to give you a general idea of what
these feature names refer to and what can be done
with them. - Google these features if you want / ever need
to...
3Exceptions
- Exceptions are caught by the server
- You can find them in the log file
underCATALINA_BASE/logs/ - The result shown in the browser depends on the
buffer state - Check the example on the next slide
- Find the exceptions in the log
4public class ExceptionServlet extends HttpServlet
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException response.setConte
ntType("text/html") PrintWriter out
response.getWriter() int nLines
Integer.parseInt(request.getParameter("nlines"))
out.println("lthtmlgtltheadgtlt/headgtltbodygt") for
(int i 0 i lt nLines i) out.println("ltpgt
bla bla bla " i "lt/pgt") out.println("lt/bo
dygtlt/htmlgt") out.println(" " 1/0 " ")
This line causes an exception
Run http//localhost/dbi/exception?nlines10htt
p//localhost/dbi/exception?nlines1000
5Uploading Files with Servlets
Read more about the FileUpload API
6Handling Uploads with Package Commons FileUpload
- Commons FileUpload is a package of Apache for
handling uploaded files in the Servlet side - Files are sent in the body of post requests
- Using this package, uploaded files are
temporarily written into the memory or the disk
(depending on the file size) - You can set the size threshold beyond which files
are written to disk
This is not a configuration parameter in web.xml
but a part of the API as well see in the next
slides
7Handling Uploads with Package Commons FileUpload
- Servlets read the file from the disk or memory
- In Tomcat, the default temporary directory is
CATALINA_BASE/temp/ - However, you can specify a temporary directory of
your own (e.g., /tmp) - What if a very big file is uploaded?
- You can define the maximal size of uploaded files
- Exception is thrown for larger files
8Example 1
Sends the client the uploaded file
lthtmlgt ltheadgt lttitlegtUpload Files and
Parameterslt/titlegt lt/headgt ltbodygt ltform
action"upload1" method"post"
enctype"multipart/form-data"gt
lth2gtFileltinput type"file" name"file1"/gtlt/h2gt
lth2gtltinput type"submit" value"send" /gtlt/h2gt
lt/formgt lt/bodygt lt/htmlgt
This is the right encoding type for files
uploading
upload1.html
9import org.apache.commons.fileupload.disk. impor
t org.apache.commons.fileupload.servlet. import
org.apache.commons.fileupload. public class
Upload1 extends HttpServlet public void
doPost(HttpServletRequest request,
HttpServletResponse
response) throws ServletException,
IOException DiskFileItemFactory factory
new DiskFileItemFactory() //factory.setReposit
ory(new File("/tmp")) factory.setSizeThreshold
(1000) ServletFileUpload upload new
ServletFileUpload(factory) upload.setSizeMax(6
0000)
Sets the repository directory
Sets the memory vs. disk threshold (bytes)
Upload1.java
Sets the maximum file size (bytes). Bigger files
generate exceptions
10try List items upload.parseRequest(request
) Iterator it items.iterator()
FileItem item (FileItem) it.next()
response.setContentType(item.getContentType())
response.setContentLength((int)item.getSize())
InputStream is item.getInputStream()
OutputStream os response.getOutputStream()
byte buffer new byte4096 int read -1
while((readis.read(buffer))gt0)
os.write(buffer,0,read) catch
(FileUploadException exp)
response.setContentType("text/html")
PrintWriter out response.getWriter()
out.println("lthtmlgtltbodygtltbgtErrorlt/bgt ltigt"
exp.getMessage() "lt/igtlt/bodygtlt/htmlgt")
In our example, we expect a single parameter
Makes life much easier
We use an Output stream and not the out
PrintWriter (why?)
Upload1.java
11Example 2
Mixed parameter types
lthtmlgt ltheadgt lttitlegtUpload Files and
Parameterslt/titlegt lt/headgt ltbodygt ltform
action"upload2" method"post"
enctype"multipart/form-data"gt
lth2gtParameter x ltinput type"text" name"x"
/gtlt/h2gt lth2gtFile ltinput type"file"
name"file1" /gtlt/h2gt lth2gtParameter y ltinput
type"text" name"y" /gtlt/h2gt lth2gtltinput
type"submit" value"send" /gtlt/h2gt lt/formgt
lt/bodygt lt/htmlgt
upload2.html
12 List items upload.parseRequest(request)
Iterator it items.iterator()
out.println("ltolgt") while (it.hasNext())
FileItem item (FileItem) it.next() if
(item.isFormField()) out.println("ltligtltb
gtFieldlt/bgt " item.getFieldName()
" " item.getString() "lt/ligt")
else out.println("ltligtltbgtFilelt/bgt"
" parameter name "
item.getFieldName() ",
file name " item.getName()
", file size " item.getSize()
" bytes, file type "
item.getContentType()
"lt/ligt") out.println("lt/olgt")
This time we use a loop since there are several
parameters
Upload2.java
13Example 3
- The latter example reflected a common design
problem combining complex HTML code and Java
code in a Servlet or a JSP - Java code for processing parameters and uploaded
files - HTML code for generating the (dynamic) response
- An accepted solution is to process the parameters
in a Servlet, and forward the request to a JSP
for generating the response - Attributes can be sent to the JSP via the request
object. - The next example also uses JSTL
14JSTL
- JSTL stands for JSP Standard Tag Library
- This is a regular tag library that can be
imported to your page, like the ones we created
in the past - This library includes some standard actions that
are common in JSP, like iteration and conditions
over EL expressions, parsing/manipulation of XML
and database access - More details can be found in Sun's J2EE Tut.
15Example 3
lthtmlgt ltheadgt lttitlegtUpload Files and
Parameterslt/titlegt lt/headgt ltbodygt ltform
action"upload3" method"post"
enctype"multipart/form-data"gt
lth2gtParameter x ltinput type"text" name"x"
/gtlt/h2gt lth2gtFile ltinput type"file"
name"file1" /gtlt/h2gt lth2gtParameter y ltinput
type"text" name"y" /gtlt/h2gt lth2gtltinput
type"submit" value"send" /gtlt/h2gt lt/formgt
lt/bodygt lt/htmlgt
upload3.html
16Upload3.java
List formParams new LinkedList() List files
new LinkedList() List items
upload.parseRequest(request) Iterator it
items.iterator() while (it.hasNext())
FileItem item (FileItem) it.next()
if (item.isFormField())formParams.add(item)
else files.add(item) request.setAttrib
ute("formParams",formParams) request.setAttribute
("files",files) this.getServletContext().getRequ
estDispatcher ("/WEB-INF/jsp/upload3.jsp").fo
rward(request,response)
Well store parameters and fileitems in those
lists
Attach the lists to the request
17lt_at_ taglib uri"http//java.sun.com/jsp/jstl/core"
prefix"c" gt lt_at_ page isELIgnored"false"
gt lthtmlgtltheadgtlttitlegtSubmitted
Parameterslt/titlegtlt/headgt ltbodygtlth1gtSubmitted
Parameterslt/h1gtltolgt ltcforEach var"item"
items"formParams"gt ltligtltbgtParameterlt/b
gt nameltigtitem.fieldNamelt/igt,
valueltigtitem.stringlt
/igtlt/ligt lt/cforEachgt ltcforEach
var"item" items"files"gt
ltligtltbgtFilelt/bgt
nameltigtitem.namelt/igt,
lengthltigtitem.sizelt/igt,
sizeltigttypeitem.contentTypelt/igtlt/ligt
lt/cforEachgt lt/olgtlt/bodygtlt/htmlgt
/WEB-INF/jsp/upload3.jsp
18A Question
- What is the advantage of redirecting to JSP pages
that are under WEB-INF? - Pages under the WEB-INF are not accessible
- You can make sure no one invokes the JSP directly
- You can hide the implementation
19Programmatic Security with Servlets
20Programmatic-Security Methods
- The Servlet API contains several accessories for
handling programmatic security - getRemoteUser()
- isUserInRole(String role)
- getAuthType()
- These are all methods of HttpServletRequest
- To enable user authentication (even for public
URLs), provide a link to some protected page
Returns the authenticated user or null if none
exists
21An Example Security Constraints in web.xml
ltsecurity-constraintgt
ltweb-resource-collectiongt
ltweb-resource-namegtFirm Peoplelt/web-resource-namegt
lturl-patterngt/login.htmllt/url-patt
erngt lt/web-resource-collectiongt
ltauth-constraintgt
ltrole-namegtemployeeslt/role-namegt
ltrole-namegtmanagerslt/role-namegt
lt/auth-constraintgt lt/security-constraintgt
Some secured resources
Roles that can view those resources
web.xml
Roles, some users and their roles are defined in
/conf/tomcat-users.xml
22An Example Security Constraints in web.xml
ltlogin-configgt ltauth-methodgtFORMlt/a
uth-methodgt ltform-login-configgt
ltform-login-pagegt/loginlt/form-login-pagegt
ltform-error-pagegt/login?failfaillt/form-erro
r-pagegt lt/form-login-configgt
lt/login-configgt ltsecurity-rolegt
ltrole-namegtmanagerslt/role-namegt
lt/security-rolegt ltsecurity-rolegt
ltrole-namegtemployeeslt/role-namegt
lt/security-rolegt
Roles used in this application(not required)
web.xml
23public class FirmServlet extends HttpServlet
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException res.setContentType("text/html")
PrintWriter out res.getWriter()
out.println("lthtmlgtltheadgtlttitlegtFirmlt/headgtltbodygt"
) out.println("lth1gtHello.lt/h1gt") String
username req.getRemoteUser()
if(usernamenull) out.println("ltpgtltimg
src\"images/visitor.gif\"/gtlt/pgt")
out.println("lth3gtlta href\"login.html\"gtLoginlt/agtlt
/h3gt") out.println("lt/bodygtlt/htmlgt")
return
Returns the authenticated user or null if none
exists
FirmServlet
24 if(req.isUserInRole("employees"))
out.println("ltpgtltimg src\"images/employee.gif\"/gt
lt/pgt") out.print("lth2gtWelcome Employee "
username "!lt/h2gt")
if(req.isUserInRole("managers"))
out.println("ltpgtltimg src\"images/manager.gif\"/gtlt
/pgt") out.print("lth2gtExecutive average
salary 42764NIS!lt/h2gt")
out.print("lth3gtlta href\"endsession\"gtLog
Outlt/agtlt/h3gt") out.println("lt/bodygtlt/htmlgt")
This is ugly. This is why attributes in HTML can
be single- or double-quoted. Same goes for
strings in many scripting languages (watch out
for escaping differences, though!)
FirmServlet
25LoginServlet.java
public class LoginServlet extends HttpServlet
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException
res.setContentType("text/html") PrintWriter
out res.getWriter() out.println("lthtmlgtlthea
dgtlttitlegtLoginlt/titlegtlt/headgtltbodygt")
if(req.getParameter("fail")!null)
out.print("lth2gtLogin Failed. Try Again.lt/h2gt")
out.println("ltform action\"j_security_chec
k\" method\"post\"gt" "ltpgtLogin
ltinput type\"text\" name\"j_username\"/gtlt/pgt"
"ltpgtPassword ltinput type\"password\"
name\"j_password\"/gtlt/pgt" "ltpgtltinput
type\"submit\" value\"Log In\"/gtlt/pgt"
"lt/formgtlt/bodygtlt/htmlgt")
Notice that though this code contains no
getSession() calls, the server tries to put
session-cookie as a part of the FORM
authorization
26 public void doPost(HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException
this.doGet(req,res)
LoginServlet.java
ltservletgt ltservlet-namegtLoginlt/servlet-na
megt ltservlet-classgtLoginServletlt/servlet-cla
ssgt lt/servletgt ltservlet-mappinggt
ltservlet-namegtLoginlt/servlet-namegt
lturl-patterngt/loginlt/url-patterngt
lt/servlet-mappinggt
web.xml
27EndSession.java
public class EndSession extends HttpServlet
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException HttpSession
session req.getSession(false)
if(session!null) session.invalidate()
res.sendRedirect("firm")
Tomcats session implementation saves the user
details in the session but not as
attributes. Recovering this data is done by
calling the mentioned request methods, but of
course invalidating the session leads to logout
ltservletgt ltservlet-namegtEndSessionlt/servle
t-namegt ltservlet-classgtEndSessionlt/servlet-c
lassgt lt/servletgt ltservlet-mappinggt
ltservlet-namegtEndSessionlt/servlet-namegt
lturl-patterngt/endsessionlt/url-patterngt
lt/servlet-mappinggt
web.xml
28lthtmlgt ltheadgt lttitlegtLogged
Onlt/titlegt lt/headgt ltbodygt
lth1gtYou are logged on!lt/h1gt ltpgtlta
href"firm"gtBack to the firm page.lt/agtlt/pgt
lt/bodygt lt/htmlgt
login.html
29Managing User Authentication with Tomcat
30A Reminder
create table users ( username varchar(30) not
null primary key, pass varchar(30)
not null ) create table users_roles (
username varchar(30) not null, role
varchar(30) not null, primary key
(username,role), foreign key (username)
references users(username) )
31In tomcat-base/conf/server.xml
ltRealm className"org.apache.catalina.rea
lm.JDBCRealm" driverName"org.postgresql.
Driver" connectionURL"jdbcpostgresql//
dbserver/public?usersnoopy"
userTable"users" userNameCol"username"
userCredCol"pass"
userRoleTable"users_roles"
roleNameCol"role"/gt
32User Tables
- What if we do not have one table that stores
usernames and passwords? - What if we only have one role for the all users?
- What if we wanted the above information to be
stored in several tables (e.g., users and
administrators)? - The idea is to use views rather than real tables
33Creating Views
create view up as (select username u, pass
p from users union select u,p
from admin) create view ur as (select
username u, 'myRole' r from users union
select u, 'admin' r from admin)
Unifies the user/password data from 2 tables
Default role for simple users
Default role for admin users
34Fixing server.xml
ltRealm className"org.apache.catalina.rea
lm.JDBCRealm" driverName"org.postgresql.
Driver" connectionURL"jdbcpostgresql//
dbserver/public?usersnoopy"
userTable"up" userNameCol"u"
userCredCol"p" userRoleTable"ur"
roleNameCol"r"/gt
35Filters
36Filters in Servlet API
- Filters are used to dynamically intercept
requests and responses - A filter that applies to a URL u typically acts
as follows given a request for u - performs some actions before the processing of u
- passes the request handling to the next filter
- The last filter passes the request to u itself
- performs some actions after the processing of u
37(No Transcript)
38public class FilterExample implements Filter
public void init(FilterConfig filterConfig)
throws ServletException ...
public void destroy() ...
public void doFilter(ServletRequest req,
ServletResponse res, FilterChain chain) throws
IOException, ServletException ...
chain.doFilter(request, response)
...
Before other elements in way down
After other elements in way up
FilterExample.java
39Registering a Filter
ltfiltergt ltfilter-namegtExample
Filterlt/filter-namegt ltfilter-classgtFilterExa
mplelt/filter-classgt lt/filtergt
ltfilter-mappinggt ltfilter-namegtExample
Filterlt/filter-namegt lturl-patterngt/images/lt
/url-patterngt lt/filter-mappinggt
You can also add an ltinit-paramgt element like we
saw in servlets and JSPs.
web.xml
40What Can we Do with Filters?
- Examine and log requests
- Modify request headers and properties
- Modify the response headers and response data
- Block requests
- And more...
Open FilterExample.java. Check the result of
calling http//localhost/dbi/images/image1.gif in
the servers logs
41Notes About Filters
- The order of the filters in the chain is the same
as the order that filter mappings appear web.xml - The life cycle of filters is similar to that of
Servlets - Filters typically do not themselves create
responses, although they can - The request and response arguments of doFilter
are actually of type HttpServletRequest and
HttpServletResponse - The FilterConfig interface is used to read
initialization parameters - Those are set in web.xml
42public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException
HttpServletResponse res (HttpServletResponse)
response HttpServletRequest req
(HttpServletRequest)request String URI
req.getRequestURI() if (URI.endsWith(filterConfi
g.getInitParameter("type"))
(req.getParameter("nofilter") null))
res.setContentType("text/html") PrintWriter
out res.getWriter() out.println("lthtmlgtlthea
dgtlttitlegtImageFilterlt/titlegtlt/headgtltbodygt")
out.println("lth2gtImage filename " URI
"lt/h2gt\n") out.println("ltimg src\""
URI.substring(1 URI.lastIndexOf("/"))
"?nofilter\" /gt") out.println("lt/bodygtlt/htm
lgt")
URI is the part of the URL following the
http//hostport
Only for filetypes lttypegt with no nofilter
parameter in the query
We have to add the nofilter query so that the
filter wont work again on the ltimggt
ImageFilter.java
43Default filter chaining.This time next element
in the chain is not a filter but the original URL
else chain.doFilter(request, response)
ltfiltergt ltfilter-namegtfImageFilterlt/fil
ter-namegt ltfilter-classgtImageFilterlt/fil
ter-classgt ltinit-paramgt
ltparam-namegttypelt/param-namegt
ltparam-valuegt.giflt/param-valuegt
lt/init-paramgt lt/filtergt ltfilter-mappinggt
ltfilter-namegtfImageFilterlt/filter-namegt
lturl-patterngt/images2/lt/url-patterngt
lt/filter-mappinggt
The Filter applies only to .gif files in
/dbi/images/ but not for other files on the same
directory such as .txt
A url-pattern of /images2/.gif doesnt
work. Thats why we check the suffix in the Java
code
Open /images2/image1.gif Open /images2/joke1.txt
web.xml