1 servlet/jsp miscellaneous representation and management of data on the web

21
1 Servlet/JSP Servlet/JSP Miscellaneous Miscellaneous Representation and Management of Data on the Web

Post on 20-Dec-2015

217 views

Category:

Documents


0 download

TRANSCRIPT

1

Servlet/JSP MiscellaneousServlet/JSP Miscellaneous

Representation and Management of

Data on the Web

2

Uploading Files with Uploading Files with ServletsServlets

3

Handling Uploads with Package Handling Uploads with Package Commons FileUploadCommons 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

4

Handling Uploads with Package Handling Uploads with Package Commons FileUploadCommons 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

5

Example 1Example 1

<html> <head> <title>Upload Files and Parameters</title> </head> <body> <form action="upload1" method="post" enctype="multipart/form-data">

<h2>File:<input type="file" name="file1"/></h2><h2><input type="submit" value="send" /></h2> </form> </body></html>

upload1.htmlupload1.html

6

public class Upload1 extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

DiskFileUpload upload = new DiskFileUpload(); upload.setSizeThreshold(1000); upload.setSizeMax(60000); try { List items = upload.parseRequest(request); Iterator it = items.iterator(); FileItem item = (FileItem) it.next(); response.setContentType(item.getContentType()); response.setContentLength((int)item.getSize());

Upload1.javaUpload1.java

7

InputStream is = item.getInputStream(); OutputStream os = response.getOutputStream(); byte[] buffer = new byte[4096]; int read = -1; while((read=is.read(buffer))>=0) os.write(buffer,0,read); } catch (FileUploadException exp) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><body><b>Error</b>: <i>" + exp.getMessage() + "</i></body></html>"); } }} Upload1.javaUpload1.java

8

Example 2Example 2

<html> <head> <title>Upload Files and Parameters</title> </head> <body> <form action="upload2" method="post" enctype="multipart/form-data"> <h2>Parameter x: <input type="text" name="x" /></h2> <h2>File: <input type="file" name="file1" /></h2> <h2>Parameter y: <input type="text" name="y" /></h2> <h2><input type="submit" value="send" /></h2> </form> </body></html>

upload2.htmlupload2.html

9

List items = upload.parseRequest(request); Iterator it = items.iterator(); out.println("<ol>"); while (it.hasNext()) { FileItem item = (FileItem) it.next(); if (item.isFormField()) out.println("<li><b>Field</b>: " + item.getFieldName() + " = " + item.getString() + "</li>"); else out.println("<li><b>File</b>" + ": parameter name: " + item.getFieldName() + ", file name: " + item.getName() + ", file size: " + item.getSize() + " bytes, file type: " + item.getContentType() + "</li>"); } out.println("</ol>"); Upload2.javaUpload2.java

10

Example 3Example 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

• The next example also uses JSTL

11

JSTLJSTL

• 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.

12

Example 3Example 3

<html> <head> <title>Upload Files and Parameters</title> </head> <body> <form action="upload3" method="post" enctype="multipart/form-data"> <h2>Parameter x: <input type="text" name="x" /></h2> <h2>File: <input type="file" name="file1" /></h2> <h2>Parameter y: <input type="text" name="y" /></h2> <h2><input type="submit" value="send" /></h2> </form> </body></html>

upload3.htmlupload3.html

13

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.setAttribute("formParams",formParams);request.setAttribute("files",files);

this.getServletContext().getRequestDispatcher ("/WEB-INF/jsp/upload3.jsp").forward(request,response);

Upload3.javaUpload3.java

14

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%@ page isELIgnored="false" %><html><head><title>Submitted Parameters</title></head> <body><h1>Submitted Parameters:</h1><ol>

<c:forEach var="item" items="${formParams}"> <li><b>Parameter</b>: name:<i>${item.fieldName}</i>, value:<i>${item.string}</i></li> </c:forEach> <c:forEach var="item" items="${files}"> <li><b>File</b>: name:<i>${item.name}</i>, length:<i>${item.size}</i>, size:<i>type:${item.contentType}</i></li> </c:forEach> </ol></body></html> /WEB-INF/jsp/upload3.jsp/WEB-INF/jsp/upload3.jsp

15

A QuestionA Question

What is the advantage of redirecting to JSP pages

that are under WEB-INF?

16

Managing User Managing User Authentication with Authentication with

TomcatTomcat

17

A ReminderA 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)

);

18

In server.xmlIn server.xml<Realm

className="org.apache.catalina.realm.JDBCRealm"

driverName="oracle.jdbc.driver.OracleDriver"

connectionURL="jdbc:oracle:thin:snoopy/snoopy@sol4:1521:stud"

userTable="users"

userNameCol="username"

userCredCol="pass"

userRoleTable="users_roles"

roleNameCol="role"/>

19

User TablesUser 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

20

Creating ViewsCreating 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);

21

Fixing server.xmlFixing server.xml<Realm

className="org.apache.catalina.realm.JDBCRealm"

driverName="oracle.jdbc.driver.OracleDriver"

connectionURL="jdbc:oracle:thin:snoopy/snoopy@sol4:1521:stud"

userTable="up"

userNameCol="u"

userCredCol="p"

userRoleTable="ur"

roleNameCol="r"/>