Servlet et InputStream

vsiguier Messages postés 22 Date d'inscription vendredi 5 octobre 2001 Statut Membre Dernière intervention 19 février 2003 - 30 nov. 2001 à 10:06
 GlopGlop -
Bonjour à tous !

Je cherche à effectuer un traitement sur la réponse à une requête Http, réponse contenu dans un objet HttpServletResponse.
Est-ce que quelqu'un sait comment obtenir le contenu d'un tel objet sachant qu'il ne possède pas de méthode du style getInputStream() ?

Toute idée ou proposition sera la bien venue...

5 réponses

je ne suis pas sur d'avoir compris la question mais si tu veux écrire dans l'objet réponse tu peux faire un
response.getOutputStream().write (tableau de bit);
ou pour du texte (ici un traitement d'erreur)
response.setContentType("text/html");
PrintWriter out = new PrintWriter (response.getOutputStream());
out.println("<html>");
out.println("<head><title>Error</title></head>");
out.println("<body>"+e.getMessage());
out.println("</body></html>");

je profite de la réponse pour te demander si tu sais comment invalider une page pour que l'utilisateur ne puisse pas utiliser le bouton back pour revenir sur une page précédement vue ?
0
vsiguier Messages postés 22 Date d'inscription vendredi 5 octobre 2001 Statut Membre Dernière intervention 19 février 2003
30 nov. 2001 à 12:01
Effectivement tu n'as pas compris mais c'est peut-être parce que je me suis mal expliqué.
La réponse renvoyée au browser (client) figure dans un objet du type HttpServletResponse et j'ai besoin d'accéder à cette réponse pour y opérer un traitement. A ma connaissance on peut demander un flux en écriture sur cet objet pour y écrire une réponse ( response.getOutputStream() ) mais on ne peut obtenir de flux en lecture pour lire la réponse.

Pour invalider le bouton back, sur l'evenement onload du tag BODY j'execute le code javascript suivant :
window.history.forward
0
merci pour le js, je vais esayer
A mon avis ton pb est surtout du un pb d'architecture dans ton appli. la lecture se fait nécessairement dans l'objet request. c'est le role des deux objets request/reponse. Je ne comprends pas le traitement à faire sur l'objet reponse (en l'état des emplications :-)
cependat HttpServeltReponse ou ServleReponse propose quelques méthodes de modif de l'objet reponse notament de la redirection voir la doc de sun javax pour plus de détail
0
vsiguier Messages postés 22 Date d'inscription vendredi 5 octobre 2001 Statut Membre Dernière intervention 19 février 2003
30 nov. 2001 à 13:57
Le pourquoi de la chose c'est que je veux pouvoir récupérer le code html généré par une JSP afin de l'écrire dans un fichier et ensuite le downloader pour que le client puisse visualiser la page hors connexion.
La solution que j'envisage est la suivante :
la requête http arrive sur une servlet qui fait un include de la JSP afin de récupérer le code html de la page dans l'objet HttpServletResponse de la servlet. Je pensais ensuite pouvoir lire cet objet (InputStream) pour ecrire le code html dans un nouveau fichier...

Voilà tu sais tout !
0
alors là , effectivement ...
mais si tu affiches la JSP et que tu provoques un "fichier/enregistrer sous" par JS en fin de page, ça le fait, mais certe très différement
ou alors si ta servlette utilise une page HTML template avec des tag WRB_INC tu peux composer dynamiquement ta page depuis la servlette et tu peux peut être récupérer le contenu pour l'ecrire dans un fichier ou le downloader directement; à voir; si tu n'as pas déjà essayer.
chao
0
vsiguier Messages postés 22 Date d'inscription vendredi 5 octobre 2001 Statut Membre Dernière intervention 19 février 2003
30 nov. 2001 à 16:18
Peux-tu m'en dire plus sur les tag WRB_INC ou as-tu des liens vers lesquels je pourrai trouver des renseignements ?
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
J'ai trouvé ça dans les exemples fournis par Oracle avec Oracle Wireless edition et WebToGo (qui permet de travailler sur l'intranet en mode déconnecté par une réplication de base de données et l'utilsiation d'un serveur JSP en local)

C'est une "ancienne" architecture, avant l'apparition des JSP, qui consiste à créer la page html en static avec des tag et a utiliser une servlet pour remplacer les tag par le résultat d'un calcul. Pour cela, la servelet "récupère" le fichier HTML, on doit donc pouvoir le lire dans son intégralité depuis la servelet.
Tu noteras au passage qu'une JSP n'est rien d'autre qu'une servelet d'ou les " sur "ancien".

ci joint un exemple de html
<HTML>
<HEAD>
<TITLE>Recording information</TITLE>
</HEAD>
<SCRIPT LANGUAGE="JavaScript">
function CloseWindow()
{
if (window.name != "")
window.name = "";

parent.close(self);
}
</SCRIPT>
<BODY>
<P ALIGN="RIGHT"><a href="">Home</a>&nbsp<a href="javascript:CloseWindow()">Exit</a></P>
<FORM ACTION="ProcessMasterDetailForm" METHOD="POST" ENCTYPE="application/x-www-form-urlencoded">
<br>
<P>Recording: </p>

<P>
<WRB_INC NAME="deleteMasterButton" VALUE="Error: No method found to create Delete Master Button">
</P>
<P>
<WRB_INC NAME="masterRecord" VALUE="Error: No method found to create master record">
</P>

<P>Tracks:</P>

<p>
<WRB_INC NAME="detailRecord" VALUE="Error: No method found to create detail record">
</p>
<center>
<input type=submit value="Commit">&nbsp&nbsp
<input type=reset value="Reset">
<center>
<WRB_INC NAME="onSuccess" VALUE="Error: No method found to create on success action">
</FORM>

</BODY>

</HTML>


et la servelet qui l'exploite
/*
* Copyright (c) 1999-2000 by Oracle Corporation
*/

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import oracle.lite.web.html.TemplateParser;
import oracle.lite.web.html.DBTable;
import oracle.lite.web.html.DBDetailTable;
import oracle.lite.web.html.DBColumn;
import oracle.lite.web.html.DBPrimaryKey;
import oracle.lite.web.html.DBForeignKey;
import oracle.lite.web.html.DBCompoundColumn;
import oracle.lite.web.html.OnSuccess;
import oracle.lite.web.servlet.OraUserProfile;
import oracle.lite.web.servlet.OraHttpServletRequest;
import oracle.html.Link;

/**
* This servlet displays a Master Detail form. One MASTER record is displayed
* with all its DETAIL records.
*/
public class DisplayMasterDetail extends TemplateParser
{
/**
* This method is called by the super class TemplateParser to
* determine the set of WRB_INC tags that need to be replaced in the HTML
* template. The 2-dimensional array that is returned, contains a
* mapping of the WRB_INC tag names and the corresponding methods.
* For each tag name in the array, the super class will call the corresponding
* method and replace the tag in the HTML file with the result of the method.
*
* @param request The Http Request
*
* @return String[][] array containing all the names of the WRB_INC tags and
* the name of the method that needs to be called to obtain the replacement
* text
*/
public String[][] getWRB_TAGS(HttpServletRequest request)
{
return new String[][]{
// tag name error message method
{"deleteMasterButton",res.getString("ErrorWithDeleteButton"), "DeleteMasterButton"},
{"masterRecord", res.getString("ErrorWithMasterRec"), "MasterRecord"},
{"detailRecord", res.getString("ErrorWithDetailRec"), "DetailRecord"},
{"onSuccess", res.getString("ErrorWithOnSuccess"),"OnSuccess"}};
}

/**
* This method is called by the super class TemplateParser to
* find the path to the HTML template file.
*
* @param request The Http Request
*
* @return String value containing the full path to the template
*/
public String getFileName(HttpServletRequest request)
{
return SampleProgram3.TEMPLATE_PATH+"DisplayMasterDetail.html";
}

///////////////////////////////////////////////////////////////////////////////
////////// Methods that generate the Dynamic content for the HTML page ////////
///////////////////////////////////////////////////////////////////////////////
/**
* Creates an HTML button to delete the master record
*
* @param request The Http Request
*
* @return String containing either the HTML for the delete Button, or an
* error message
*/
public String DeleteMasterButton(HttpServletRequest request)
{
String masterID = getSingleParameterValue(request, "rec_id");
if (masterID == null)
{
// No master ID is specified, do not show the Delete Button
// because the form is used to create a new record
return "";
}

// Create the correct URL to call the delete servlet which will delete
// the record.
// Note that we are using the variable name ID to pass the master ID
// value to the servlet, the base class DeleteRecords expects an HTTP
// variable with that name
//
// The class Link is part of the oracle.html.* package
Link l =
new Link("DeleteMasterDetail?id="+masterID,
res.getString("DeleteRecordingLabel"));

// Return the html for the link back to the browser
return l.toHTML();

}

/**
* Retrieves the master record from the database and displays it. When no
* master record identifier is specified in the HTTP request, an empty record
* is displayed, which can be used to insert a new master record in the database.
*
* @param request The Http Request
*
* @return String containing either the HTML for the master record, or an
* error message
*
* @exception SQLException When a database error occured
*/
public String MasterRecord(HttpServletRequest request) throws SQLException
{
// Identifier for the Master Record
String masterID = getSingleParameterValue(request, "rec_id");


// Get the User profile from the HTTP Request
OraUserProfile userProfile =
((OraHttpServletRequest)request).getUserProfile();

// Get the user code for this user
String userCode = userProfile.getValue("USERCODE").toString();


// Create a new DBTable associated with the database table RECORDINGS
DBTable masterRecord = new DBTable("RECORDINGS");

// Add the columns that are of interest

// Add a primary key column. The fourth argument indicates the source
// for the primary key. This is used when a new record is inserted into
// the database.
// Primary key columns are hidden by default
masterRecord.addColumn(
new DBPrimaryKey("id", // database column
java.sql.Types.NUMERIC, // database column type
res.getString("RecordingIDLabel"), // Not shown, column is hidden
"audiodb_seq.nextval") // for new records
);

// Add a regular column that is visible and updateable
masterRecord.addColumn(
new DBColumn("artist", // database column
java.sql.Types.VARCHAR, // database column type
res.getString("ArtistLabel") ) // label
.setUpdateable(true).setVisible(true)
);

// Add a regular column that is visible and updateable
masterRecord.addColumn(
new DBColumn("title", // database column
java.sql.Types.VARCHAR, // database column type
res.getString("AlbumTitleLabel") ) // label
.setUpdateable(true).setVisible(true)
);

// Add a regular column that is visible and updateable
masterRecord.addColumn(
new DBColumn("year", // database column
java.sql.Types.VARCHAR, // database column type
res.getString("YearLabel") ) // label
.setUpdateable(true).setVisible(true).setMaximumInputSize(4)
);

// Add an LOV column that is visible and updateable
// The LOV will create a drop down select list which can be used to insert
// or change a value for the selected column
// Note how the LOV is created from a database query itself
masterRecord.addColumn(
new DBColumn("ret_id", // database column
java.sql.Types.NUMERIC, // database column type
res.getString("RecordingTypeLabel") ) // label
.setUpdateable(true).setVisible(true)
.setLOV("select id, type from recording_types")
);

// Add a hidden column for the usercode column
masterRecord.addColumn(
new DBColumn("usercode", // database column
java.sql.Types.NUMERIC, // database column type
res.getString("UserCodeLabel") ) // label
.setUpdateable(false).setVisible(false)
.setDefaultValue(userCode)
);

// Orientation of this masterRecord is VERTICAL, which means that
// the columns of each database row are displayed underneath each
// other and database rows are displayed next to each other
masterRecord.setOrientation(DBTable.VERTICAL);


StringBuffer whereCondition = new StringBuffer(50);

// If a master ID is specified, the master record is displayed
// otherwize, an empty form is created, that can be used to insert
// a new master record into the database
if (masterID == null)
{
// No master ID specified.
// Create a record that can be used for insert of a new database record
// First, add a where condition that will not return any rows
// In this case, the ID column is the primary key column
// and the primary key will never be equal to NULL
whereCondition.append("id is null");

// Now, add one extra empty row to the masterRecord object. This row
// will be used to enter data for the row in the master database table
masterRecord.setExtraRows(1);
}
else
{
// Master ID is specified, limit the query results to that record only
// by adding the appropriate where condition
whereCondition.append("id = "+masterID);
}

// Add the usercode to the where clause so that we only
// return rows that belong to this user
whereCondition.append(" and usercode ="+userCode);

// Set the where condition for this record
masterRecord.setWhereCondition(whereCondition.toString());


// Draw a border around the data
masterRecord.setBorder(1);


// Retrieve data, format it and return it to the caller as an HTML string
// (who will replace the <WRB_INC> tag with this return string

// Retrieve the database connection from the super class
Connection conn = retrieveConnection(request);

//Fetch the data, format it in HTML and return this string to the caller
return FetchAndFormatData(conn, masterRecord);
}

/**
* Retrieves the detail records from the database and displays it. When no
* master record identifier is specified in the HTTP request, an empty
* record is displayed, which can be used to insert a new detail record in the
* database.
*
* @param request The Http Request
*
* @return String containing either the HTML for the detail record, or an
* error message
*
* @exception SQLException When a database error occured
*/
public String DetailRecord(HttpServletRequest request) throws SQLException
{

// Get the User profile from the HTTP Request
OraUserProfile userProfile =
((OraHttpServletRequest)request).getUserProfile();

// Get the user code for this user
String userCode = userProfile.getValue("USERCODE").toString();

// Create a new DBDetailTable associated with the database detail table
// TRACKS and database master table RECORDINGS
DBDetailTable detailRecord = new DBDetailTable ("TRACKS", "RECORDINGS");

// Add the columns that are of interest
// Add a primary key column. The fourth argument indicates the source
// for the primary key. This is used when a new record is inserted into
// the database.
// Primary key columns are hidden by default
detailRecord.addColumn(
new DBPrimaryKey("id", // database column
java.sql.Types.NUMERIC, // database column datatype
res.getString("TrackIDLabel"), // label, hidden for Primary Key
"audiodb_seq.nextval" // source for new record
)
);
// Add a regular column that is visible and updateable
detailRecord.addColumn(
new DBColumn("track_number",
java.sql.Types.NUMERIC,
res.getString("TrackLabel"))
.setUpdateable(true) // Set column to be updateable
.setVisible(true) // Set column to be visible
);

// Add a regular column that is visible and updateable
detailRecord.addColumn(
new DBColumn("title",
java.sql.Types.VARCHAR,
res.getString("TrackTitleLabel"))
.setUpdateable(true) // Set column to be updateable
.setVisible(true) // Set column to be visible
);

// Add a CompoundColumn that contains an identifier to the row and
// and HTTP Link to delete the row down
// CompoundColumns are always read-only
// Trying to create the SQL string:
// '<a href="Delete?id=||'id||'&rec_id='||rec_id||'">'||delete||'</a>'
String deleteAction =
"'<a href=\"DeleteDetail?id='||id||'&rec_id='||rec_id||'\">Delete</a>'";

detailRecord.addColumn(new DBCompoundColumn(deleteAction,
res.getString("ActionLabel") ) // label
.setVisible(true)
);

// Add a hidden foreign key column that refers to the primary key in the
// master. Foreign key columns are hidden by default
detailRecord.addColumn(
new DBForeignKey("rec_id", // database column
java.sql.Types.NUMERIC, // database datatype
"", // label, not used, column is hidden
"id") // corresponding database column in
// master table
);

// Add a hidden column for the usercode column
detailRecord.addColumn(
new DBColumn("usercode", // database column
java.sql.Types.NUMERIC, // database column type
res.getString("UserCodeLabel") ) // label
.setUpdateable(false).setVisible(false)
.setDefaultValue(userCode)
);

// Orientation of this detailRecord is HORIZONTAL, which means that
// the columns of each database row are displayed next to each other and
// subsequent database rows are displayed underneath each other
// Also, 4 empty rows are added which can be used to enter data to insert
// 4 more detail rows into the details database table
detailRecord.setOrientation(DBTable.HORIZONTAL).setExtraRows(4);

// String with the identifier for the Master record
String masterID = getSingleParameterValue(request, "rec_id");

// Create the where condition, only list details for the specified master
// record. If no master was specified, create a condition that causes
// no rows to be retrieved

if (masterID == null)
{
// No master. Add FALSE condition. Make sure no rows are returned from
// database
// ID is primary key and can never be NULL.
detailRecord.setWhereCondition("id is null");
}
else
{
// Make sure that we can only select detail records that belong to a
// master the current user has access to!
String subQuery =
"select rec.id from recordings rec where rec.id = "+masterID
+" and rec.usercode = "+userCode;
// Limit details to specified master record
detailRecord.setWhereCondition("rec_id in ("+subQuery+")");
}

// draw a border around the data
detailRecord.setBorder(1);

// Order the data by track number
detailRecord.addOrderCondition("track_number ASC");

// Retrieve the database connection from the super class
Connection conn = retrieveConnection(request);

// Retrieve data, format it and return it to the caller as an HTML string
// (who will replace the <WRB_INC> tag with this return string
return FetchAndFormatData(conn, detailRecord);
}


/**
* Create a hidden field with a URL that will be executed when the
* form is processed successfully.
*
* @param request The Http Request
*
* @return String containing either the HTML for the detail record, or an
* error message
*/
public String OnSuccess(HttpServletRequest request)
{
// This creates a hidden field with the value:
// 'DisplayMasterDetail?rec_id=$$ID$$'
// After processing the HTML form successfully, the servlet
// ProcessMasterDetailForm will do the following:
// - The String $$ID$$ is replaced with the primary key of the master record
// - The URL is called and the result is send to the browser
// The user will see that all the changes have been committed to the database
// and the new record is shown
return new OnSuccess("DisplayMasterDetail?rec_id=$$ID$$").toHTML();
}

// Handle to the resources
private static ResourceBundle res = SampleResources.getBundle();
}




Bon courage et tiens moi informé je suis intérrésé par le résultat. On a tous quelque chose à apprendre.
j'ai laissé mon email apparent cette fois ci.
0

Discussions similaires