Aplikacja WWW - projekt - serwlety - Java Server Pages - AJAX
Zadanie
1) Dołączyć do projektu serwlet Display_Data
2) Utworzyć stronę startową wyświetlającą dostępne książki
3) Skopiować do katalogu Web plik ajax.js
SERVLET DISPLAY_DATA
package pss;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Display_Data extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print("<html><head>");
out.print("</head><body>");
out.print("<form action=\"");
out.print( req.getRequestURI() );
out.print("\" method=\"post\">");
out.print("<input type=\"submit\" ");
out.print("value=\" \"> ");
out.print("Display Records</form>");
out.print("</body></html>");
out.close();
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print("<html><head>");
out.print("</head><body>");
out.print("<code><pre>");
out.print("<font color=green>ID\tFirst ");
out.println("Name\tLast Name\n</font>");
// debugging info
long time1 = System.currentTimeMillis();
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:a");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM PRODUCTS");
// rs = stmt.executeQuery("SELECT DESCRIPTION FROM PRODUCTS WHERE ID =" + req.getParameter("ID")"");
// displaying records
while(rs.next()) {
out.print(rs.getObject(1).toString());
out.print("\t");
out.print(rs.getObject(2).toString());
out.print("\t\t");
out.print(rs.getObject(3).toString());
out.print("\n");
}
out.println("Selected object ID = " + req.getParameter("ID"));
} catch (SQLException e) {
throw new
ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new
ServletException("JDBC Driver not found.", e);
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
// debugging info
long time2 = System.currentTimeMillis();
out.print("</pre></code>");
out.print("<p>Search took : ");
out.print( (time2 - time1) );
out.print(" ms.</p>");
out.print("<p\"><a href=\"");
out.print( req.getRequestURI() );
out.print("\">Back</a></p>");
out.print("</body></html>");
out.close();
}
STRONA
PRODUCT INFO
<%@ page language="java" import="java.util.*" %>
<%@ page import="pss.*" %>
<html>
<head>
<style type="text/css">
body{
background-repeat:no-repeat;
font-family: Trebuchet MS, Lucida Sans Unicode, Arial, sans-serif;
font-size:0.9em;
line-height:130%;
text-align:center;
height:100%;
background-color: #E2EBED;
}
#contentContainer h2{ /* No margins above <h2> tags */
margin-top:0px;
}
#mainContainer{
width:755px;
margin:0 auto;
text-align:left;
padding:5px;
margin-top:20px;
border:1px solid #000;
background-color: #FFF;
}
#contentContainer{
float:left;
border:1px solid #000;
background-color: #E2EBED;
overflow:auto;
margin-right:10px;
padding:10px;
/* CSS HACK */
width: 497px; /* IE 5.x */
width/* */:/**/480px; /* Other browsers */
width: /**/480px;
/* CSS HACK */
height: 412px; /* IE 5.x */
height/* */:/**/390px; /* Other browsers */
height: /**/390px;
}
#contentContainer .openingText{
color:red;
}
#articleListContainer{ /* <ul> container for article list */
float:left;
height:410px;
overflow:auto;
width:240px;
border:1px solid #000;
background-color:#FFF;
}
.articleList{
margin:0px;
padding:2px;
}
.articleList li{ /* General layout article in list */
list-style-type:none;
border:1px solid #999;
background-color:#EEE;
height:50px;
margin:1px;
padding:2px;
color:#333;
cursor:pointer;
}
.articleList li.articleMouseOver{ /* Mouse over article in list - layout */
border:1px solid #000;
color:#000;
}
.articleList li.articleClick{ /* Active article in list - layout */
border:1px solid #000;
color:#000;
background-color:#317082;
color:#FFF;
}
.keyText{ /* Just a column I use for key text inside articles - the one with the light blue bg and dotted border */
background-color:#FFF;
border:1px dotted #000;
float:right;
margin-top:5px;
margin-left:5px;
margin-bottom:5px;
width:150px;
padding:3px
}
.clear{
clear:both;
}
</style>
<script type="text/javascript" src="ajax.js"></script>
<script type="text/javascript">
/************************************************************************************************************
Ajax dynamic articles
************************************************************************************************************/
var ajax = new does();
var articleListObj;
var activeArticle = false;
var clickedArticle = false;
var contentObj // Reference to article content <div>
function mouseoverArticle() // Highlight article
{
if(this==clickedArticle)return;
if(activeArticle && activeArticle!=this){
if(activeArticle==clickedArticle)
activeArticle.className='articleClick';
else
activeArticle.className='';
}
this.className='articleMouseOver';
activeArticle = this; // Storing reference to this article
}
function showContent() // Displaying content in the content <div>
{
contentObj.innerHTML = ajax.response; // ajax.response is a variable that contains the content of the external file
}
function showWaitMessage()
{
contentObj.innerHTML = 'Finding article.....<br>Please wait';
}
function getAjaxFile(fileName)
{
ajax.requestFile = fileName; // Specifying which file to get
ajax.onCompletion = showContent; // Specify function that will be executed after file has been found
ajax.onLoading = showWaitMessage; // Action when AJAX is loading the file
ajax.runAJAX(); // Execute AJAX function
}
function selectArticle() // User have clicked on an article
{
/*getAjaxFile('http://localhost:8080//PSS_Project//Display_Data'); */
if(clickedArticle && clickedArticle!=this)clickedArticle.className='articleMouseOver';
this.className='articleClick';
clickedArticle = this;
var E = this.getElementsByTagName('BUTTON');
getAjaxFile('http://localhost:8080//PSS_Project//Display_Data?ID='+ E[0].id);
}
function initAjaxProcedure()
{
articles = document.getElementsByName('articleList');
for(var no=0;no<articles.length;no++){
articles[no].onmouseover = mouseoverArticle;
articles[no].onclick = selectArticle;
}
contentObj = document.getElementById('contentContainer');
}
window.onload = initAjaxProcedure;
</script>
<title>Book list page</title>
</head>
<body>
<table border="1">
<tbody> <tr>
<td>ID</td>
<td>Author</td>
<td>Book name</td>
<td>Available</td>
<td> </td>
<td> </td>
</tr>
<%
HttpSession S = request.getSession();
ArrayList arrayList = (ArrayList)S.getAttribute("bookDB");
int i = 0;
if(arrayList != null)
for (Iterator iter = arrayList.iterator(); iter.hasNext();)
{
Book element = (Book) iter.next();
out.println("<tr id=articleList>");
out.println("<td>" + element.getId()+ "</td>");
out.println("<td>" + element.getAuthor() + "</td>");
out.println("<td>" + element.getTitle() + "</td>");
if(element.isAvailable())
out.println("<td><input type=checkbox name=available value=true disabled checked></td>");
else
out.println("<td><input type=checkbox name=available value=true disabled></td>");
out.println("<td><a href=BookEdit?do=edit&id=" + element.getId() + ">Edit</a></td>");
out.println("<td> <a href=BookEdit?do=delete&id=" + element.getId() + ">Delete</a></td>");
out.println("<td> <button id=" + i + ">This is PRODUCT</button></td>");
out.println("</tr>");
i++;
}
%>
</tbody>
</table>
<div id="mainContainer">
<div id="header">
<img src="/images/heading3.gif">
</div>
<div id="contentContainer">
<h2 class="openingText">Wcisnij przycisk myszy na jednym z opisow produktu.</h2>
<p>Opis produktu zostanie wyswietlony w ponizszej sekcji DIV</p>
</div>
<div class="clear"></div>
</div> <br>
<a href="BookEdit?do=add" method=post>Add a new book</a>
</body></html>
/* Simple AJAX Code-Kit*/
function does(file) {
this.xmlhttp = null;
this.resetData = function() {
this.method = "POST";
this.queryStringSeparator = "?";
this.argumentSeparator = "&";
this.URLString = "";
this.encodeURIString = true;
this.execute = false;
this.element = null;
this.elementObj = null;
this.requestFile = file;
this.vars = new Object();
this.responseStatus = new Array(2);
};
this.resetFunctions = function() {
this.onLoading = function() { };
this.onLoaded = function() { };
this.onInteractive = function() { };
this.onCompletion = function() { };
this.onError = function() { };
this.onFail = function() { };
};
this.reset = function() {
this.resetFunctions();
this.resetData();
};
this.createAJAX = function() {
try {
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
try {
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
this.xmlhttp = null;
}
}
if (! this.xmlhttp) {
if (typeof XMLHttpRequest != "undefined") {
this.xmlhttp = new XMLHttpRequest();
} else {
this.failed = true;
}
}
};
this.setVar = function(name, value){
this.vars[name] = Array(value, false);
};
this.encVar = function(name, value, returnvars) {
if (true == returnvars) {
return Array(encodeURIComponent(name), encodeURIComponent(value));
} else {
this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
}
}
this.runResponse = function() {
eval(this.response);
}
this.runAJAX = function(urlstring) {
if (this.failed) {
this.onFail();
} else {
this.urlString=urlstring;
if (this.element) {
this.elementObj = document.getElementById(this.element);
}
if (this.xmlhttp) {
var self = this;
if (this.method == "GET") {
totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
this.xmlhttp.open(this.method, totalurlstring, true);
} else {
this.xmlhttp.open(this.method, this.requestFile, true);
try {
this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
} catch (e) { }
}
this.xmlhttp.onreadystatechange = function() {
switch (self.xmlhttp.readyState) {
case 1:
self.onLoading();
break;
case 2:
self.onLoaded();
break;
case 3:
self.onInteractive();
break;
case 4:
self.response = self.xmlhttp.responseText;
self.responseXML = self.xmlhttp.responseXML;
self.responseStatus[0] = self.xmlhttp.status;
self.responseStatus[1] = self.xmlhttp.statusText;
if (self.execute) {
self.runResponse();
}
if (self.elementObj) {
elemNodeName = self.elementObj.nodeName;
elemNodeName.toLowerCase();
if (elemNodeName == "input"
|| elemNodeName == "select"
|| elemNodeName == "option"
|| elemNodeName == "textarea") {
self.elementObj.value = self.response;
} else {
self.elementObj.innerHTML = self.response;
}
}
if (self.responseStatus[0] == "200") {
self.onCompletion();
} else {
self.onError();
}
self.URLString = "";
break;
}
};
this.xmlhttp.send(this.URLString);
}
}
};
this.reset();
this.createAJAX();
}
Zadanie:
Na podstawie opracowanego kodu, wyświetlić informacje (opis produktu) z tabeli PRODUCT.
Utworzyć nowe pole DESCRIPTION w tabeli PRODUCT
Plik AJAX