Date post: | 11-Jan-2016 |
Category: |
Documents |
Upload: | elwin-potter |
View: | 229 times |
Download: | 2 times |
Text file with a .jsp extension Contains HTML tags and elements Also contain embedded Java commands JSPs are compiled into servlets
Easier to deploy (no special privileges needed) Compiled into a servlet before page is accessed
for first time◦ This servlet remains in web server's main memory◦ Doesn't have to be recompiled when accessed from then
on◦ Adds code for page directives (import statements etc)
All of the html and text outside of <%... %> tags is put in a function and wrapped in out.println statements (or equivalent)◦ The function sets up the out, session, request and
response objects – this allows your JSP page to access any of these objects
Deploy JSPs in either source or compiled form If source form
◦ JSP engine translates page into a servlet◦ Stores it in the server’s memory (not as a file)◦ Depending on implementation of JSP engine
Translation can occur at any time between initial deployment and the receipt of the first request
As long as the JSP remains unchanged, subsequent requests reuse the servlet class, reducing the time required for those requests.
If deployed as a compiled servlet◦ Eliminates the time required to compile the JSP when the first
request is received◦ Eliminates the need to have the Java compiler on the server.
Anything done in a JSP can be done with a servlet
But – is an ISP going to allow you access to the webapps folder servlets are auto-deployed to?◦ More on this near the end of the semester when you have
an admin lab
Or if not in the auto-deploy webapps folder, will they allow you to start and stop the server to install the servlet (if not directly in webapps it won't auto-deploy)?
Non-programming web designers can write the HTML for a JSP and call servlets (or tag libraries) as needed.◦ Allows the programmers to create class libraries, use
inheritance, etc. with servlets◦ Allows the page designers to do their work also◦ Common site structure:
JSPs for the interface Servlets for the back end More on this when we get to Struts and JSF
Caution – you likely won't use servlets at all – unless "your" organization runs the web server and someone (you or someone you can work with) is the site administrator
Therefore – JSPs are used more than servlets…(and of course PHP gets the most use...)
Web Programming Technologies
Server-sideprocessing
Client-sideprocessing
Compiledprograms
Server-side scripts
CGI programs
Java Servlets Active Server Pages ASP
Java Server Pages JSP
Compiled programs on client workstation
Java applets
Java Web Start
Client-sidescripts
JavaScript
VBScript
ASP.NET
Hypertext Preprocessor PHP
AJAX
Java Server Faces
Microsoft ClickOnce
ColdFusion CF
JSP Example
JSP Example - Code
;
JSP’s use a similar coding style to ASP, PHP, and Cold Fusion. If you know how to create a JSP, you won’t find it difficult to learn how to use one of these alternate technologies.
With a JSP, you can first create a static Web page, then add the commands for dynamic processing (same as ASP, PHP, Cold Fusion)
JSP pages are compiled into servlets
You are already familiar with Java/Javascript syntax A strongly typed language can be an advantage JSP's can access beans and servlets
Java Server Faces, ASP.NET, etc??◦ These are harder to learn than JSP, PHP, ASP or
ColdFusion.◦ But they don't mix the HTML code with the Server-side
code – which can be a big advantage.◦ The concepts you're learning working with JSPs (and
servlets) will apply to other technologies
◦ And – you get to use some of these other technologies in CS268
Use a dynamic web project as you did with servlets
If using mysql, remember to copy its jar file to WEB-INF/lib
Run your JSP pages as you did your servlets
Run As/Run on Server
Directives◦ Information used by the JSP processing engine
Scriptlets◦ Java code added to the page
Expressions◦ Includes dynamically generated text in the resulting HTML page
Actions◦ Allow including other files and provide additional control over
the JSP engine Declarations
◦ Inserted into body of servlet class, outside existing methods◦ Allows you to create methods and class level variables
Provide information about the JSP page to the JSP processing engineExamples:import <%@ page import="java.sql.*,java.util.*, java.io.*" %>
◦ Aside from wrapping this in a directive and slightly different syntax – this works identically to any Java import statement
◦ Note: PHP doesn't allow the programmer to import libraries – the web admin can add additional libraries – but not the coder.
include <%@ include file="library/checkLogin.jsp" %>
◦ Inserts contents of file in current file at the location the include directive is placed
fragments of code that are embedded within <% ... %> tags. They get executed whenever the JSP page is accessed
PHP also has <%= asa shortcut to using echo
Notice – no ; ending the line
Evaluated when the JSP page is accessed Its value gets printed in the resulting HTML page JSP expressions are within <%= ... %> tags and
do not include ending semicolons: <%= count %> The above expression prints out the value of the variable
count expression is always a single line of code (no ending ; )
Alternative from within a scriptlet <% …. %> <% out.println("count is: " + count); %> No need in a jsp to set out = response.getWriter();
Use out.println just as you did with servlets At the extreme, you could put just about
everything within a single scriptlet◦ But why… take advantage of what JSPs offer
JSP actions are instructions that control the behavior of the JSP’s server.
A few standard JSP actions are jsp:include Similar to a function, the JSP temporarily hands the request
and response off to the specified JavaServer Page. Control will always return to the current JSP, once the other JSP has finished.
jsp:forward forward processing of request to another servlet or JSP. Control does not return to the current JSP.
jsp:param Can be used inside a jsp:include or jsp:forward. Specifies a parameter that will be added to the request's current parameters.
<jsp:include page="scripts/login.jsp" />
<jsp:forward page="/accounting/menu.jsp/"><jsp:param name="username" value="jsmith" />
</jsp:forward>
Inserted into body of servlet class, outside existing methods
Allows you to create class level variables
<%! private int accessCount = 0; %>
Accesses to page since server reboot:
<%= ++accessCount %>
Allows creating methods For example:
Note: you can't directly use out.println from within a method as you can in a JSPscriptlet. You can use response.getWriter().println – if you pass response as a parameter to the method.
<%@ page import="java.sql.*" %> <html><head> <title>Candy Products</title></head><body><% //create the connectionClass.forName("com.mysql.jdbc.Driver"); Connection cn = DriverManager.getConnection("jdbc:mysql://dario.cs.uwec.edu/STUDENT", "STUDENT", "$5333"); //create the query statementStatement stmt = cn.createStatement();String sqlQuery = "SELECT prod_id, prod_desc, prod_price, prod_cost FROM candy_product";//create the resultset and execute the queryResultSet rs = stmt.executeQuery(sqlQuery);%><!-- display the data --><table> <tr><th>Product ID</th><th>Description</th><th>Price</th><th>Cost</th></tr><% while(rs.next() == true) { %> <tr><td><%= rs.getString("PROD_ID") %></td> <td><%= rs.getString("PROD_DESC") %></td> <td><%= rs.getString("PROD_PRICE") %></td> <td><%= rs.getString("PROD_COST") %></td> </tr><% } %> </table><% // close the connection cn.close();%></body></html>
<%@ page import="java.sql.*,java.io.IOException" %> <html><head> <title>Candy Products</title></head><body><%= showData() %></body></html><%! private String showData() throws IOException, SQLException, ClassNotFoundException { String data = ""; Class.forName("com.mysql.jdbc.Driver"); Connection cn = DriverManager.getConnection("jdbc:mysql://dario.cs.uwec.edu/STUDENT", "STUDENT", "S5333"); Statement stmt = cn.createStatement(); String sqlQuery = "SELECT prod_id, prod_desc, prod_price, prod_cost FROM candy_product"; ResultSet rs = stmt.executeQuery(sqlQuery);
data += "<table border=\"4\" cellpadding=\"\3\" cellspacing=\"1\">"; data += " <tr><th>Product ID</th><th>Description</th><th>Price</th><th>Cost</th></tr>"; while(rs.next() == true) { data += "<tr><td>" + rs.getString("PROD_ID") + "</td>"; data += " <td>" + rs.getString("PROD_DESC") + "</td>"; data += " <td>" + rs.getString("PROD_PRICE") + "</td>"; data += " <td>" + rs.getString("PROD_COST") + "</td>"; data += "</tr>"; } data += "</table>"; cn.close(); return data;}%>
<select name="categoryid" size="4">
<% while (rs.next()) { %>
<option value="<%= rs.getString("categoryid") %>">
<%= rs.getString("categorydescription") %>
</option>
<% } %>
</select>
What this generates (look in view/source):<select name="categoryid" size="4">
<option value="3">All Terrain Vehicles</option>and so on…
<% while (rs.next()) { %> <input type="radio" name="categoryid" value="<%= rs.getString("categoryid") %>">
<%= rs.getString("categorydescription") %>
<% } %>
What this generates (look in view/source):<input type="radio" name="categories" value="3">All Terrain Vehicles<input type="radio" name="categories" value="1">Appareland so on…
<% while (rs.next()) { %> <a href="displayCategories.jsp?categoryid=<%= rs.getString("categoryid")
%>"> <%= rs.getString("categorydescription") %></a><% } %>
What this generates (look in view/source):<a href="displayCategories.jsp?categoryid=3">All Terrain Vehicles</a><a href="displayCategories.jsp?categoryid=1">Apparel</a>and so on…
Notice that rs.getString(“categoryid”) puts in thecategoryid URL parameter
And notice that rs.getString(“categorydescription”)puts in the text the user sees
A. Clear out the Eclipse/Tomcat temporary files used to run a web project Close all open pages Delete the tomcat server Select Project from the top menu, then select Clean Refresh your project (right click the project in the project explorer select refresh) Try running your page again (usually fixes the problem)
B. Export current project as a war file (don't optimize for a tomcat server) Make a new workspace import the war file into it
C. Ask your instructor for helpD. Drop the class
Right click, select Delete
I’ve had students trying to debug code where doing the “resource out of sync” steps would have fixed their problems. In other words they had modified their code (could be html, javascript or java code) and the changes were being ignored due to Eclipse not properly updating the temporary files it creates when running the program.
Don’t assume this is the case – until you use the eclipse debugger and see that the
changes you made aren’t being reflected in what you see in the debugger. If that happens – delete the Tomcat server from your project, close all code windows, select Project/Clean and then refresh the project (right click the project in the Project Explorer then select Refresh). Run it again and see if the changes you made are properly being picked up by Eclipse.
Here’s another tip. You can view the select query for a prepared statement's query –
including the values assigned using pStmt.setString (.setInt etc) in the debugger’s variable’s window if you select it there and then horizontally scroll through what is displayed at the bottom of the variables window. Sometimes you might discover that the setString, etc. isn’t putting in there what you thought it was putting there (and thereby figure out what you need to do to correct the problem).
Create the selection list.◦ Interfaces choices are:
URL Parameters Select list Radio inputs ?? Others are possible
◦ The choices are often obtained from a database query This allows changing the items in the database and having this
automatically reflected in the application – without having to recode the HTML for the choices in the list
◦ Pass the user selected choice to the detail page Select lists and radio inputs do this by submitting a form URL Parameters do not require a form. The equivalent parameters (to
form parameters) are directly appended to an <a href= tag.
Write the query to retrieve the data and include a WHERE clause filtering the data by the selection passed from the master page
Display the data using a loop to read the retrieved data
A. The page will display with nothing shown in the detail section
B. An error page will be displayedC. It depends on how the details page is written
Better yet – use AJAX and display the detail in a div within the initial page(like what you did for assignment2)
Encrypting passwords Validating login Preventing access to pages requiring a login
if not logged in
HTML Form collects username and password◦ Sends them to JSP page validating the login
JSP page queries database for username and password◦ If found, stores their userid (customerid, or whatever is the primary key
identifying them) in a cookie or session variable and displays the next page◦ If not found, returns them to the initial login page
Passwords can be encrypted using any number of encryption algorithms – easy to use Java or .NET encryption class libraries◦ Better option – use an HTTPS server to encrypt everything between the browser and
server
Storing passwords◦ Typically stored in a database as a hash code◦ I'm not going to do this – for "real" applications this is needed
Session Variables, JSP/Servlet Cookie handling
JSP command to forward the user to a different page
Preventing a user from directly accessing a page that requires a login
Preventing a SQL Injection Attack??◦ Use parameter query (called a prepared statement in JDBC) –
(there are other ways)
A session is associated with a visitor to a Web site Data can be put in the session and retrieved from it A different set of data is kept for each visitor to the site
If you bring up two different browsers or run two browsers from two different machines, these will be assigned to different server sessions.
Session_Order.htm:
<center><h2>How many widgets do you want?</h2>
<form name=frmOrder action=Session_OrderSummary.jsp>
Quantity: <input type=text name=txtQty size=10> <input type=submit value=Submit>
</form></center>
Session_OrderSummary.jsp:
<% session.setAttribute("txtQty", request.getParameter("txtQty")); %>
You've requested <%= request.getParameter("txtQty") %>widgets<br>
<form name=frmConfirm action=Session_ProcessOrder.jsp>
<input type=submit value=Confirm?>
</form>
Session_ProcessOrder.jsp:
<center><h2>Your order for <%= session.getAttribute("txtQty") %>
widgets has been processed</h2></center>
When a user leaves the Web site and doesn’t return? What happens to session variables?◦ After 30 minutes with no activity from the user
The server discards the variables stored for the user (otherwise the server’s memory would eventually be
filled up with no longer needed session variables) For PHP the default timeout interval is 24 minutes
response.sendRedirect("newPage.jsp");◦ How was this done using PHP?
What does this command do?◦ From the Web server’s JSP page to the browser:
Sends a request to the user’s browser asking the user’s browser to in turn send back a request for the specified page
◦ From the browser to the Web server: Receives the request from the server and sends back to
the Web server a request for the specified page◦ And from the Web server to the browser:
Sends back the newly requested page
Create a session variable if a user successfully logs in
Variable is then checked by other pages requiring login◦ All of these pages redirect to the login page if this
variable isn’t found
Why use a session variable?◦ Con
times out in 30 minutes uses server memory
◦ Pro can’t be seen or read on the client computer easier syntax than that needed to read a cookie times out if user is inactive 30 minutes (might be desired for security)
To create a session variable:session.setAttribute("name", rs.getString("cid"));
To read a session variable:String varName = session.getAttribute("name");
To removesession.removeAttribute("name");
How to test for the existence of a session variable?
Put this code at the top of pages that shouldn't be accessed unless the user has logged in successfully
<%if(session.getAttribute("InstructorID") == null) { //if no session variable, send them to the login page response.sendRedirect("login.htm");}%>
Why use a temporary cookie?◦ Con
Takes more coding (than session variable) Doesn't time out Visible on client
◦ Pro Doesn't time out Doesn't use server memory
How to test for the existence of a cookie?
Put this code at the top of pages that shouldn't be accessed unless the user has logged in successfully
<% Cookie cookies[] = request.getCookies(); boolean found = false; if(cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if ("InstructorID".equals(cookie.getName())) { found = true; break; } } } if(!found) response.sendRedirect("login.htm");%>
How can you reuse the code – use one of the following techniques:◦ Copy the code at the start of every JSP
Previous slide
◦ Use an include statement to reference another file which contains the code Next slide
◦ Package the code in a JavaBean
This runs without error. If notlogged in, response.sendRedirectis called. But menu.jsp is stilldisplayed.
Do you know why?
This will successfullyredirect to login.htm
Do you know why?
A JavaBean is a POJO that is serializable, has a no-argument constructor, and allows access to properties using getter and setter methods.
Technically WebUtils isn't a JavaBeansince it doesn't have a getter or setter
Servlets and JavaBeans are cool◦ (cool beans, right?)
But – if your site is hosted by an ISP (Internet Service Provider) you probably can't use them.◦ ISPs typically don't provide access to Tomcat's
webapps folder*.
Use them if your organization has its own Web servers
*Tomcat is by default configured to automatically expand and start war files copied into webapps (but not subfolders of webapps) without starting and stopping the web server
This is a common situation:◦ User adds a new customer (or whatever)
◦ User uses browser's back button to return to previous page displaying customers (or whatever)
◦ Previous page does not show the newly added customer – a cached page is displayed
◦ So user tries to add the new customer again, and again…
HTML Equivalent (use meta tags – set a date in the past for expires):
<%response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");response.setHeader("Expires", "Thu, 19 Nov 1981 08:52:00 GMT");response.setHeader("Pragma", "no-cache"); %>
JSP:
<head><title>Whatever</title><meta http-equiv="Cache-Control" content="no-store, no-cache must-revalidate"> <meta http-equiv="Expires" content=" Thu, 19 Nov 1981 08:52:00 GMT "><meta http-equiv="Pragma" content="no-cache"> </head>
A form of attack on a database-driven Web site in which the attacker executes unauthorized SQL commands
Possible when a query is concatenated together from user inputs.
SQL injection attacks are prevented through input validation.
Incorrectly filtered escape characters statement = "SELECT * FROM users WHERE name = '" + userName + "';"; User enters: a' or 't'='t Rendered as: SELECT * FROM users WHERE name = 'a' OR 't'='t';
Incorrect query termination statement = "SELECT * FROM data WHERE id = " + a_variable + ";"; User enters: 1;DROP TABLE users Rendered as: SELECT * FROM DATA WHERE id=1;DROP TABLE users;
Magic String 'OR''=' When used at a login page, you will be logged in as the user on top of the SQL table.
And there are more…
Using Parameterized Statements◦ In some programming languages such as PHP, Java
and .NET parameterized statements are available. They will block sql injection attacks
Use Filtering◦ remove dangerous characters◦ Hard to anticipate all possible characters
Other techniques – but parameter queries make the problem go away
Does programming language support them?◦ PHP, .NET and Java support them
Java
.NET – C#
String sqlQuery = "SELECT InstructorID FROM UniversityInstructor " + "WHERE InstructorUserID = ? AND InstructorPIN = ?"; PreparedStatement pStmt = cn.prepareStatement(sqlQuery);
pStmt.setString(1, user);pStmt.setString(2, pin);ResultSet rs = pStmt.executeQuery();
//Create the SQL Command object as a parameter querysqlCommand.CommandText = "SELECT EmployeeID " + "FROM SportEmployee " + "WHERE EmployeeUsername = @eUsername AND " + "EmployeePassword = @ePassword";//Associate the parameters with form controlssqlCommand.Parameters.Add(new SD.SqlClient.SqlParameter("eUsername", txtUsername.Text));sqlCommand.Parameters.Add(new SD.SqlClient.SqlParameter("ePassword", txtPassword.Text));
Scenario HInput_Order.htm page has an input named txtQuantity
○ Action specifies OrderSummary.jsp
HInput_OrderSummary.jsp asks user to confirm the order○ If confirmed, Action specifies HInput_ProcessOrder.jsp○ txtQuantity is passed to HInput_ProcessOrder.jsp as a hidden input:
<input type="hidden" name="quantity" value="3">
○ The above input is written into the page by HInput_OrderSummary.jsp HInput_OrderSummary.jsp uses getParameter to read the value Then uses this value in the hidden input
HInput_ProcessOrder.jsp is able to read txtQuantity usinggetParameter since this is a form input (and cookies weren’t used to get the input from HInput_OrderSummary.jsp to HInput_ProcessOrder.jsp)
HInput_Order.htm:<center><h2>How many widgets do you want?</h2><form name=frmOrder action=HInput_OrderSummary.jsp>Quantity: <input type=text name=quantity size=10> <input type=submit
value=Submit></form></center>
HInput_OrderSummary.jsp:
You've requested <%= request.getParameter("quantity") %> widgets<br>
<form name=frmConfirm action=HInput_ProcessOrder.jsp><input type=hidden name=quantity value="<%= request.getParameter("quantity") %>">
<input type=submit value=Confirm?>
</form>
HInput_ProcessOrder.jsp:
<center><h2>Your order for <%= request.getParameter("quantity") %>
widgets has been processed</h2></center>
Can you think of potential problems with using hidden inputs to store a user’s shopping cart items?
Should hidden inputs be used instead of cookies?
Should hidden inputs be used instead of cookies? Sometimes
◦ Assume you have a page letting you select an item to be edited When the page doing the editing is generated, use a hidden input to store the id (primary
key) of the item being edited
The user has no need or reason to edit the primary key (id) but this information is going to be needed when the edit page is submitted and a SQL UPDATE query is created
You could store the id/primary key as a session variable or cookie, but in this case a hidden input is easier and reliable. However – if using method="get" this is visible in the address and might be a security concern
(however… hackers with http protocol skills can also compromise requests that are "post"ed) So – maybe a session variable would be the most secure option
Eclipse copies the contentsof WebContentinto its getRealPath() folder when it compilesthe project◦ This is why Web Projects
sometimes get out of sync…
Use this and clip/parsethe filename from thepath
Using eclipse, files copied into the WEB-INF folder can be accessed using this:◦ getServletContext().getRealPath("/") + "WEB-INF/filename"
This works while testing in Eclipse – how to deploy?◦ Create a WEB-INF folder in root folder where you intend to deploy the application
desired file is in WEB-INF
Any other issues you need to be aware of while testing file based code in Eclipse?
Not an issue if you don't use file access◦ Easier to store and retrieve data in a client/server
database!