Write in JSP

Instructions and Manual

1 Getting a Request Parameter from a JSP URL

In a GET request, the request parameters are taken from the query string (the data following the question mark on the URL). For example, the URL http://hostname.com?p1=v1&p2=v2 contains two request parameters - - p1 and p2. In a POST request, the request parameters are taken from both query string and the posted data which is encoded in the body of the request.

This example demonstrates how to include the value of a request parameter in the generated output:

    Hello <b><%= request.getParameter("name") %></b>!

If the page was accessed with the URL:

    http://hostname.com/mywebapp/mypage.jsp?name=John+Smith

the resulting output would be:

    Hello <b>John Smith</b>!

If name is not specified on the query string, the output would be:

    Hello <b>null</b>!

This example uses the value of a query parameter in a scriptlet:

    <%
        if (request.getParameter("name") == null) {
            out.println("Please enter your name.");
        } else {
            out.println("Hello <b>"+request.getParameter(i)+"</b>!");
        }
    %>

2 Getting a Request Parameter in a JSP Page

Forms are, of course, the most important way of getting information from the customer of a web site. In this section, we'll just create a simple color survey and print the results back to the user.

First, create the entry form. Our HTML form will send its answers to form.jsp for processing.

For this example, the name="name" and name="color" are very important. You will use these keys to extract the user's responses.

form.html

<form action="form.jsp" method="get">

<table>
<tr><td><b>Name</b>
    <td><input type="text" name="name">

<tr><td><b>Favorite color</b>
    <td><input type="text" name="color">
</table>

<input type="submit" value="Send">

</form>

กก

Resin keeps the browser request information in the request object. The request object contains the environment variables you may be familiar with from CGI programming. For example, it has the browser type, any HTTP headers, the server name and the browser IP address.

You can get form values using request.getParameter object.

The following JSP script will extract the form values and print them right back to the user.

form.jsp
Name: <%= request.getParameter("name") %> <br>
Color: <%= request.getParameter("color") %> 

3 Redirect to other URL

<%

/** redirect to a more specific homepage if one is available */

String home_url = null;

String num = request.getParameter("Camera_Number");

if (num.equals("1")) {

home_url = "camera1.jsp";

} else if (num.equals("2")) {

home_url = "camera1.jsp";

} else if (num.equals("3")) {

home_url = "camera1.jsp";

}

if (home_url != null) {

home_url = response.encodeRedirectUrl(home_url);

response.sendRedirect(home_url);

return; // don't do any more of the page

}

%>

4 Real-time Communication between Server and Client

Jsp pages and servlets run in the web server, and produce HTML content, then send the HTML to the client. Commonly, for the web server, the client would be a web browser, such as Mozila, IE, and etc. If the web server wants to send something to the client, and needs the client to perform some action other then just showing the content of HTML, what should we do? A case in point is the project I am doing. I hope the web server generates a random key and encrypts video msgs with this key, then sends the key and cipher msgs to the web browser. After the browser receives them, it will take charge of decrypt the msgs with that key and show the result in the webpage.

The best method is to use applets as servlet front ends.

As we know, the difference between servlet and applet is that applet is downloaded by client from the web server and executes on the client's side and servlet is the oppsite. Thus naturally, we can design an applet and plug it in the jsp pages which communicates with the servlet.

1) an Example Procedure

<jsp:plugin
type="applet"
code="ShowQueries.class"
jreversion="1.2"
width="600"
height="400" >
<jsp:fallback>
Error: this example needs java!
</jsp:fallback>
</jsp:plugin>

Then we have input the java applet into the jsp file. When we visit this jsp page, java applet will execute. Please note that fallback element provides alternative text to browsers that do not support OBJECT or EMBED.

2) How does this Applet Work?

a) How does servlet sends packets?

In the servlet, there is a function called doPost. When applet sends a request, this servlet will post some information to this applet.

String contentType =
"application/x-java-serialized-object";
response.setContentType(contentType);ObjectOutputStream out =new ObjectOutputStream(response.getOutputStream());
DesEncryptor DesEntry = new DesEncryptor();
String[] queries = getQueries(useNumbering, DesEntry);
// If you send a nonstandard data structure, be
// sure it is defined with "implements Serializable".
out.writeObject(queries);
out.flush();

The servlet will keep posting msgs, there is a method to control whether to stop:

boolean useNumbering = true;
String useNumberingFlag =
request.getParameter("useNumbering");
if ((useNumberingFlag == null) ||
useNumberingFlag.equals("false")) {
useNumbering = false;
}

I am not so sure because I can't find explanation in the internet. But I think when the user clicks Start Button, "useNumbering" would be true. Otherwise, if the user clicks Stop Button or no Button at all, "useNumbering" would be false.

b) How does applet receives packets?

In showQueries.java, we define the position(URL) and name of servlet that this applet tries to connect with by private String address ="/servlet/cwp.QueryGenerator";

Which means that QueryGenerator.class is in <Tomcat_Home>\webapps\ROOT\WEB-INF\classes\cwp\ directory.

There is another java file QueryCollection.java who takes charge of sending requests. In order to use the function of QueryCollection.java in showQueries.java, we should initiate an entry to the QueryCollection class by 

private QueryCollection currentQueries;
private QueryCollection nextQueries;

and

currentQueries = new QueryCollection(address, currentPage);
nextQueries = new QueryCollection(address, currentPage);

In QueryCollection.java , following codes receives packets.

URLConnection connection = dataURL.openConnection();
// Make sure browser doesn't cache this URL, since
// I want different queries for each request.
connection.setUseCaches(false);
// Use ObjectInputStream so I can read a String[]
// all at once.
ObjectInputStream in =
new ObjectInputStream(connection.getInputStream());
try {
// The return type of readObject is Object, so
// I need a typecast to the actual type.
String[] queryStrings = (String[])in.readObject();
return(queryStrings);
} catch(ClassNotFoundException cnfe) {
return(null);
}

3) Encryption and Decryption

a) Method

I write two files to use in the servlet and applet separately. In the servlet side, the file is called DesEncryptor.java which produces the key and is able to encrypt a string. In the applet side, the file is called QueryCollection.java whose function is to retrieve the key from DesEncryptor.java and the decryption is performed in showQueries.java where I add a decryption function.

b) Produce the Key

We should import such packages:

import javax.crypto.*;
import java.security.*;
import javax.crypto.spec.*;
import java.math.*;

In fact, we can use following codes to randomly produce a key:

KeyGenerator kg = KeyGenerator.getInstance("DES");
Key key = kg.generateKey();

However, because everytime we use this function, it will generate different keys, and it is not good because we must use this function twice(encryption and decryption). So I set the function as definite.

public SecretKey GetKey (){
//generate the keys
//KeyGenerator kg = KeyGenerator.getInstance("DES");
//Key key = kg.generateKey();
try{
String Skey = "camera01";
//byte[] Bkey={64,64,64,64,64,64,64,64};
byte[] Bkey=Skey.getBytes();
DESKeySpec sks=new DESKeySpec(Bkey);
SecretKeyFactory skf=SecretKeyFactory.getInstance("DES");
SecretKey key=skf.generateSecret(sks);

return key;
} catch (Exception e) {
e.printStackTrace();
return (null);
}
}

Please note that we use try. In java, when we use some codes, we must use try-catch to handle exceptions. It is the same as in language C. The difference is that in C, we must know how to write exception codes ourselves, while in java, try-catch will solve every exception and is mandotory.

c) Encryption

public String Des(String input) {
byte[] output;
byte[] currentoutput;
byte[] newoutput;
byte[] iv={64,64,64,64,64,64,64,64};
try{
IvParameterSpec ivp=new IvParameterSpec(iv);
Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, GetKey(), ivp);
output=c.doFinal(input.getBytes());
String cipherStr = new String(output,"ISO-8859-1");

return cipherStr;
} catch (Exception e) {
e.printStackTrace();
return (null);
}
}

Please note, before and after the encryption, doFinal only handles and produces binary bytes. If we use String cipherStr = new String(output) only, we perhaps lose some unprintable strings. Normally, we encode the bytes with Hexcoding or base64 coding. Here, we just use "ISO-8859-1" and it works fine.

d) Decryption

private String DesDe(SecretKey key, String input) {
byte[] output;
byte[] iv={64,64,64,64,64,64,64,64};
try{
IvParameterSpec ivp=new IvParameterSpec(iv);
Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");

c.init(Cipher.DECRYPT_MODE, key, ivp);

output = c.doFinal(input.getBytes("ISO-8859-1"));
String decipherStr = new String(output);
return decipherStr;
} catch (Exception e) {
e.printStackTrace();
return (null);
}
}

The key should be the same as encryption key.

4) Dispatch Different Keys to Different Camera Users

The method is that when a user visits a particular webpage, the servlet assigns a corresponding key to that applet.

a) add a query string after the previous URL

dataURL = new URL(protocol, host, port, urlSuffix);
programURL = new URL(dataURL + "?" + currentPage.getFile());

and initiate the connection with programURL

URLConnection connection = programURL.openConnection();

Note: currentPage.getFile() returns path and filename of the webpage you visit, such as /login/camera1.jsp

b) retrieve the query string at the servlet part

keyStr = request.getQueryString();

So keyStr would be equal to currentPage.getFile().

c) use keyStr as index to retrieve corresponding key

public SecretKey GetKey (String index){
//generate the keys
//KeyGenerator kg = KeyGenerator.getInstance("DES");
//Key key = kg.generateKey();
try{
String Skey1 = "jjfu76u6";
String Skey2 = "34342234";
String Skey3 = "dsfgytry";
byte[] Bkey = {64,64,64,64,64,64,64,64};
if (index.endsWith("camera1.jsp"))
Bkey=Skey1.getBytes();
else if (index.endsWith("camera2.jsp"))
Bkey=Skey2.getBytes();
else
Bkey=Skey3.getBytes();
DESKeySpec sks=new DESKeySpec(Bkey);
SecretKeyFactory skf=SecretKeyFactory.getInstance("DES");
SecretKey key=skf.generateSecret(sks);

return key;
} catch (Exception e) {
e.printStackTrace();
return (null);
}
}

5) Applet Generates a Session Key to Server to Encrypt

a) Generates a random seed

SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte seed[] = random.generateSeed(8);

seedStr = seed.toString();

b) Send the string to server by adding a URL query

currentF = getDocumentBase();
currentFile = new URL(currentF + "?" + seedStr);

c) Server gets this string, generates a key with it, and encrypt data with this key

keyStr = request.getQueryString();
keyString = keyStr.substring(19);

private String Des(String input, String keyS) {
byte[] output;
byte[] currentoutput;
byte[] newoutput;
byte[] iv={64,64,64,64,64,64,64,64};
try{
DESKeySpec sks=new DESKeySpec(keyS.getBytes());
SecretKeyFactory skf=SecretKeyFactory.getInstance("DES");
SecretKey key=skf.generateSecret(sks);

IvParameterSpec ivp=new IvParameterSpec(iv);
Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, key, ivp);
output=c.doFinal(input.getBytes());
String cipherStr = new String(output,"ISO-8859-1");

return cipherStr;
} catch (Exception e) {
e.printStackTrace();
return (null);
}
}

d) The client generates a key also and decrypt all data from the server

DESKeySpec sks=new DESKeySpec(seedStr.getBytes());
SecretKeyFactory skf=SecretKeyFactory.getInstance("DES");
currentKey=skf.generateSecret(sks);

private String DesDe(SecretKey key, String input) {
byte[] output;
byte[] iv={64,64,64,64,64,64,64,64};
try{
IvParameterSpec ivp=new IvParameterSpec(iv);
Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");

c.init(Cipher.DECRYPT_MODE, key, ivp);

output = c.doFinal(input.getBytes("ISO-8859-1"));
String decipherStr = new String(output);
return decipherStr;
} catch (Exception e) {
e.printStackTrace();
return (null);
}
}