首页 > 编程 > JSP > 正文

JSP - FAQ (2)

2024-09-05 00:19:06
字体:
来源:转载
供稿:网友
国内最大的酷站演示中心!
10) how do you invoke a jsp page from a servlet? toc



(contributed by: [email protected])

after scanning through archives of the jsp mailing list to no effect i finally remembered that i'd pasted this example into a document i wrote. it was originally sent by satish dharmaraj of sun to show the model 2 approach (as described in the 0.92 specification): how to pass data from a servlet
to a jsp.

create a directory called model1/ under the samples/ directory. place foo.jsp and foo.java inside this directory.

compile fooservlet.java and place fooservlet.class in top/servlets/directory.

then invoke using http://host:8080/servlet/fooservlet

in this example, fooservlet creates a list and then stores the result in foo.class. foo.class is then passed as a datasource to foo.jsp.

the sources are:

1) fooservlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import model1.foo;

public class fooservlet extends httpservlet
{
public void service(httpservletrequest req, httpservletresponse res)
throws servletexception, ioexception
{
string s[] = new string[] {"blue", "green", "red"};
foo f = new foo(s);
req.setattribute("foo", f);

getservletcontext().getrequestdispatcher("/samples/model1/foo.jsp").forward
(req, res);
}
}
2) foo.jsp

<html>
<usebean name=foo type=model1.foo lifespan=page>
</usebean>
<ul>
<loop property=foo:list propertyelement=x>
<li> <display property=x>
</loop>
</ul>
</html>
3) foo.java

package model1;

public class foo {
string s[];
public string[] getlist() { return s; }
public foo(string s[]) { this.s = s; }
}
(from "o碒are, thomas bernhard" <[email protected]>)
11) how do you pass data (including beans) to a jsp from a servlet? toc



there are actually three different ways to do it, depending on how long the reference should last, and which jsp pages (and servlets, for that matter) should be able to see it. in each of the cases, assume that "mybean" is a reference to the bean you want to send, and that "thebean" is the key i'm going to use to store the bean under (from the servlet perspective), and use as the identity of the bean in the jsp page.

these techniques are portable to any environment compliant with the servlet api 2.1 and jsp 1.0 specifications. in each case, the passing
works from servlet->jsp, servlet->servlet, jsp->jsp, or jsp->servlet transitions.

(1) request lifetime

use this technique to pass beans that are relevant to this particular request to a bean you are calling through a request dispatcher (using either "include" or "forward"). this bean will disappear after processing this request has been completed.

servlet:
request.setattribute("thebean", mybean);
requestdispatcher rd =
getservletcontext().getrequestdispatcher('/thepage.jsp");
rd.forward(request, response);
jsp page:
<jsp:usebean id="thebean" scope="request" class="....." />
(2) session lifetime

use this technique to pass beans that are relevant to a particular session (such as in individual user login) over a number of requests. this bean will disappear when the session is invalidated or it times out, or when you remove it.

servlet:
httpsession session = request.getsession(true);
session.putvalue("thebean", mybean);
/* you can do a request dispatcher here,
or just let the bean be visible on the
next request */
jsp page:
<jsp:usebean id="thebean" scope="session" class="..." />
(3) application lifetime

use this technique to pass beans that are relevant to all servlets and jsp pages in a particular app, for all users. for example, i use this to make a jdbc connection pool object available to the various servlets and jsp pages in my apps. this bean will disappear when the servlet engine is shut down, or when you remove it.

servlet:
getservletcontext().setattribute("thebean", mybean);
jsp page:
<jsp:usebean id="thebean" scope="application" class="..." />
craig mcclanahan

12) how can i pool connections to my database? toc



controlling connections to the database is a desirable thing - having to connect to the database for each page is is expensive, and keeping a connection in a session variable is far too expensive in terms of client connections to the database. thus, people often create pools for connections to the database that the client comes in and gets and then returns when complete (making sure a try/catch is used to ensure the connection is returned!).

my personal bias indicates that you shouldn't pool connections to your database inside jsp, you should be using a middleware layer and communicating to it (like rmi or corba). however, people do write entire applications in jsp and beans that reside in the web server, so how do you do it?

from: bradley wood <[email protected]>

probably instantiate this as a singleton in the global.jsa and then call it.

for more on this and how its called check the downloadable code examples for this book at www.ora.com

import java.sql.*;
import java.util.*;

public class connectionpool {
private hashtable connections;
private int increment;
private string dburl, user, password;

public connectionpool(string dburl,
string user,
string password,
string driverclassname,
int initialconnections,
int increment)
// int max?
throws sqlexception, classnotfoundexception {
// load the specified driver class
class.forname(driverclassname);
this.dburl = dburl;
this.user = user;
this.password = password;
this.increment = increment;
connections = new hashtable();

// put our pool of connections in the hashtable
// the false value indicates they're unused
for(int i = 0; i < initialconnections; i++) {
connections.put(drivermanager.getconnection(dburl, user, password),
boolean.false);
}
}

public connection getconnection() throws sqlexception {
connection con = null;
enumeration cons = connections.keys();
synchronized (connections) {
while(cons.hasmoreelements()) {
con = (connection)cons.nextelement();
boolean b = (boolean)connections.get(con);
if (b == boolean.false) {
// so we found an unused connection.
// test its integrity with a quick setautocommit(true) call.
// for production use, more testing should be performed,
// such as executing a simple query.
try {
con.setautocommit(true);
}
catch(sqlexception e) {
// problem with the connection, replace it.
con = drivermanager.getconnection(dburl, user, password);
}

// update the hashtable to show this one's taken
connections.put(con, boolean.true);
// return the connection
return con;
} // if
} // while
} // synchro

// if we get here, there were no free connections.
// we've got to make more.
for(int i = 0; i < increment; i++) {
connections.put(drivermanager.getconnection(dburl, user, password),
boolean.false);
}

// recurse to get one of the new connections.
return getconnection();
}

public void returnconnection(connection returned) {
connection con;
enumeration cons = connections.keys();
while (cons.hasmoreelements()) {
con = (connection)cons.nextelement();
if (con == returned) {
connections.put(con, boolean.false);
break;
}
}
} // returnconnection

} // class
from: andre richards <[email protected]>

a very good example on connection pooling when using servlets can be found at :

http://webdevelopersjournal.com/columns/connection_pool.html

i succesfully used it in jsp 0.91 as follows :

<script runat="server">
dbconnectionmanager connmgr = dbconnectionmanager.getinstance();
</script>

<%
connection con = connmgr.getconnection("freetds");
if (con == null) {
out.println("can't get connection");
return;
}
try {
statement stmt = con.createstatement();
resultset rs = stmt.executequery ("select hello from world");
while(rs.next()) {
out.println(rs.getstring("hello"));
}
stmt.close();
rs.close();}
catch (sqlexception e) {
e.printstacktrace(out)
}
connmgr.freeconnection("freetds", con);
%>
13) how do i use other languages in my jsp? toc



jsp is *java* server pages, and the tags for other languages were taken out in 0.92. that said, two implementations (as of writing) support other languages:

- polyjsp, 0.92, http://www.plenix.org/polyjsp, free + open source
- resin. a jsp 0.92 implementation for compiled javascript, http://www.caucho.com/, free for personal use

14) how can i set a cookie in jsp? toc



this should work:

response.setheader("set-cookie", "cookie string");
to give the response-object to a bean, write a method setresponse
(httpservletresponse response)
- to the bean, and in jsp-file:

<%
bean.setresponse (response);
%>
(from aapo kyr鰈?<[email protected]>)

15) can jsp and servlet share same session and beans? toc



example: i used beans and session with my servlet, jsp can use same beans and session or not?

from: robert hodges <[email protected]>

this can be done, but you are likely to run into problems with class loaders. for instance, we have apache/jserv which uses the adaptiveclassloader along with gnu-jsp which has a different class loader. if you just casually allocate objects in a servlet and then pick them up in jsp pages, you'll most likely get the dreaded classcastexception, which signals the vm's pleasure when you try to cast a class that was brought in by a different class loader.

note that there are sometimes problems even within jsp, as gnu-jsp drops the class loader every time you recompile a page, so if you allocated a class instance using one version of the page, then recompiled and tried to fish that instance back again, you would either (1) not find it or (2) get the classcastexception (but see para #1 above).

if you really need to pass information around, the best way for apache and gnu-jsp is to do the following:

have one server per person when developing.
make sure that all your java classes, including servlet code, load through the system class path. this means they load through the primordial loader, which does not go away or change.
make sure that your compiled jsp pages go to another location than your regular java classes. that way, the jsp loader will just pick them up through the primordial loader.
in this scheme, you will need to reboot the web server each time you make a change to the regular java classes or else great confusion will ensue. (and possibly outrage among your users, i might add.)

if you need to share a web server between multiple people, or cannot reboot whenever you make class changes, the solution is much more complex. i can post a treatise on one approach at a later time (big project, deadline friday) if there is interest.

16) how do i plug jsp into microsoft's iis web server? toc



ibm's websphere, livesoftware's jrun and new atlanta's servletexec all provide plug ins for iis 4.0.

tomcat, the "reference" implementation of jsp 1.1 from the jakarta project also has an isapi plug-in. tomcat does not (as of 3.1) support multi-homing.

resin also provides support for multi-homing (very well at that!)

17) are there any newsgroups that discuss jsp? toc



live software has a new newsgroup for jsp discussion at news://news.livesoftware.com/livesoftware.jsp

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表