Vous devez être membre et vous identifier pour publier un article.
Les visiteurs peuvent toutefois commenter chaque article par une réponse.
[Struts] JavaScript et Java : encodage d'URL
Article publié le 04/01/2007 13:18:42Pour une application Web utilisant Struts, je dois utiliser XmlHttpRequest pour effectuer des requêtes vers des actions Java au moyen de JavaScript.
Les paramètres envoyés doivent être encodés, et JavaScript nous propose les trois méthodes suivantes :
- escape()
- encodeURI()
- encodeURIComponent()
La dernière méthode étant celle qui me convenait le mieux.
Mais comment décoder côté serveur (action en Java) ce qui a été encodé côté client (en Javascript) ?
Nous pouvons déclarer dans notre action quel est l’encodage utilisé dans la page :
Code Java (6 lignes)
try { httpservletrequest.setCharacterEncoding("iso-8859-1"); // TODO Auto-generated catch block e.printStackTrace(); }
Si nous travaillons en UTF-8, cela suffit amplement, mais si nous utilisons un autre jeu de caractères, cela peut poser problème pour les caractères ASCII étendus.
En cherchant une solution, j’ai trouvé cette classe qui nous permet de décoder en Java ce qui a été encodé en JavaScript. Nous pouvons la placer dans une classe utilitaire, et y faire appel quand le besoin s’en fait sentir.
La page JSP
Code html4strict (164 lignes)
‹%@ page contentType="text/html; charset=iso-8859-1" language="java" isErrorPage="false" errorPage="errorpage.jsp" %› ‹%@ taglib uri="/struts-bean" prefix="bean" %› ‹%@ taglib uri="/struts-html" prefix="html" %› ‹%@ taglib uri="/struts-logic" prefix="logic" %› ‹jsp:include page="/content/pages/testLogin.jsp"/› ‹html xmlns="http://www.w3.org/1999/xhtml"› ‹html:base/› ‹head› ‹title›Regions Requests - Weather Impact Matrix‹/title› ‹link rel="stylesheet" type="text/css" href="../../style/design.css" media="screen"/› ‹link rel="stylesheet" type="text/css" href="../../style/sortabletable.css" media="screen" /› ‹script type="text/javascript" src="../../scripts/sortabletable.js"›‹/script› ‹/head› ‹body id="wholeDocument"› ‹div id="container"› ‹div id="header"›‹h1 class="header"›WIM : Regions Requests‹/h1› ‹/div› ‹!-- End of "header" div --› ‹div id="introduction"› ‹div id="one"› ‹h2›1. Flow of Events‹/h2› ‹p› 1.1 DOEM3p to WIM 1. The Actor in DOEM 3p cannot select a Region for one or more Countries he has selected when creating an activity, so DOEM3p sends the request to WIM 1.2 WIM to DOEM3p 1. WIM HAS TO reply to this request through notification of the Actor DOEM3p concerned (whether new Region has been created or not ? the original comment of the request has to be included in the reply) 2. At any [CommitDate ? 1] in DOEM3p, WIM HAS TO be ready to convey the WIM decision for the period (Begin to End Date) concerned (ventilated across one or more ?Type Maand? as stated in WIM) 3. DOEM3p HAS TO pull the necessary data from WIM to be ready for subPara 1.3 1.3 DOEM3p to AMI 1. At [CommitDate + 1], DOEM3p HAS TO be ready to convey to AMI : ActivityName, BeginDate, EndDate, one or more Countries and for each Country at least one Region. Be advised that some ActivityIterations for a ShipCampaign won?t have landbased Regions but a straightforward searegion. 2. Also ready to convey : per (sea)Region, for every CalendarDay within the ActivityPeriod, the formally confirmed danger and environment level, and the WIM decision. Be advised that danger and environment levels might differ over the entire Period (because of validity periods) and that the WIM decision also might differ additionnally because of the overlap of ?Type Maand? 3. AMI HAS TO pull the data concerned when feasible at its discretion. ‹/p› ‹h3›2. Elaboration Points‹/h3› ‹p› 3. Special Requirements 3.1 Stability of data at CommitDate Any modifications within use cases of WIM or DOEM3p, done AFTER the CommitDate of an Activity concerned DO NOT have any impact on data already transferred ? so NO rollback possibilities have to be withheld. ‹/p› ‹/div› ‹!-- End of "overview" div --› ‹/div› ‹!-- End of "introduction" div --› ‹div id="mainBody"› ‹div id="regReq"› ‹h1›Region requests to do‹/h1› ‹table border="1" cellspacing="0" align="center" class="sort-table" id="rrTable" width="100%" › ‹col /› ‹col /› ‹col /› ‹col /› ‹thead› ‹tr› ‹td›N°‹/td› ‹td›Request Date‹/td› ‹td›Country/Sea‹/td› ‹td›Comment‹/td› ‹td align="center"›Reply‹/td› ‹/tr› ‹/thead› ‹tbody› ‹logic:empty name="rrForm" property="regionRequests"› ‹tr›‹td colspan="5"›Nothing Found‹/td›‹/tr› ‹/logic:empty› ‹logic:notEmpty name="rrForm" property="regionRequests"› ‹logic:iterate id="regionRequest" name="rrForm" property="regionRequests" indexId="index"› ‹bean:define id="rrItem" name="regionRequest" type="be.mil.wim.model.RegionRequest"/› ‹tr› ‹td›‹%=index.intValue()+1%›‹/td› ‹td id="‹%=index.intValue()%›rDte"› ‹bean:write name="rrItem" property="requestDate" format="dd/MM/yy"/› ‹/td› ‹td id="‹%=index.intValue()%›rcs"› ‹logic:notEmpty name="rrItem" property="geoEntity"› ‹bean:write name="rrItem" property="geoEntity.name"/› ‹/logic:notEmpty› ‹logic:empty name="rrItem" property="geoEntity"›Not defined‹/logic:empty› ‹/td› ‹td id="‹%=index.intValue()%›rco"›‹bean:write name="rrItem" property="comment"/›‹/td› ‹td align="center" class="nosort"› ‹input type="button" value="Write response" onclick="getResponseForm(‹%=index.intValue()%›);" /› ‹span id="‹%=index.intValue()%›rui" class="h"›‹bean:write name="rrItem" property="userRoleID"/›‹/span› ‹/td› ‹/tr› ‹/logic:iterate› ‹/logic:notEmpty› ‹/tbody› ‹/table› ‹/div› ‹div id="respFrm" class="h"› ‹form action="#"› ‹fieldset align="center"› ‹legend›Write a response...‹/legend› ‹div id="rrInfos"›‹/div› ‹div align="center"› ‹textarea name="doemMsgTxt" rows="5" cols="40"›‹/textarea› ‹br /›‹br /› ‹input type="button" value="Send response" onclick="sendDoemMsg();" /› ‹input type="button" onclick="showResponseForm(false);" value="Return to region requests" /› ‹/div› ‹/fieldset› ‹/form› ‹/div› ‹script type="text/javascript"› var st1 = new SortableTable(document.getElementById("rrTable"), ["Number", "Date", "String", "CaseInsensitiveString", "None"]); function showResponseForm(show){ if(!show)document.getElementById("doemMsgTxt").innerHTML =""; document.getElementById("regReq").className=(show)?"h":"v"; document.getElementById("respFrm").className=(show)?"v":"h"; } function getResponseForm(selectedIndex){ disp = "‹p›Selected Region request : ‹span id=\"sRR\"›"+selectedIndex+"‹/span›‹/p›"; disp += "‹p›RequestDate : " + document.getElementById(selectedIndex+"rDte").innerHTML; disp += "‹/p›‹p›Country/Sea : "+document.getElementById(selectedIndex+"rcs").innerHTML; disp += "‹/p›‹p›Comment : "+document.getElementById(selectedIndex+"rco").innerHTML+"‹/p›"; document.getElementById("rrInfos").innerHTML = disp; showResponseForm(true); } function sendDoemMsg(){ var xhr_object = null; if(window.XMLHttpRequest) // Firefox xhr_object = new XMLHttpRequest(); else if(window.ActiveXObject) // Internet Explorer xhr_object = new ActiveXObject("Microsoft.XMLHTTP"); else { // XMLHttpRequest non supported alert("Your browser does not support XMLHTTPRequest objects..."); return; } xhr_object.open("GET", "/wim/xhrCreateDoemMsg.do", true); selectedRRIndex = document.getElementById("srr").innerHTML; xhr_object.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr_object.setRequestHeader("If-Modified-Since","Sat, 1 Jan 2000 00:00:00 GMT"); xhr_object.send("rui="+document.getElementById(selectedRRIndex+"rui").innerHTML+"&msg="+encodeURIComponent(document.getElementById("doemMsgTxt").value)); xhr_object.onreadystatechange = function() { if(xhr_object.readyState == 4) { alert(xhr_object.responseText); showResponseForm(false); } } xhr_object.send(null); } ‹/script› ‹div id="footer"›WIM Version ‹bean:write name="loginForm" property="version"/›‹/div› ‹/div› ‹!-- End of "mainBody" div --› ‹jsp:include page="/content/pages/menu.jsp"/› ‹/div› ‹!-- End of "container" div" --› ‹/body› ‹/html›
Et l'action Java
Code Java (63 lignes)
/** * */ package be.mil.wim.web.utils; /** * * */ public class XhrUtils { int l = s.length() ; int ch = -1 ; int b, sumb = 0; for (int i = 0, more = -1 ; i ‹ l ; i++) { /* Get next byte b from URL segment s */ switch (ch = s.charAt(i)) { case '%': ch = s.charAt (++i) ; ? ch - '0' ch = s.charAt (++i) ; ? ch - '0' b = (hb ‹‹ 4) | lb ; break ; case '+': b = ' ' ; break ; default: b = ch ; } /* Decode byte b as UTF-8, sumb collects incomplete chars */ if ((b & 0xc0) == 0x80) { // 10xxxxxx (continuation byte) sumb = (sumb ‹‹ 6) | (b & 0x3f) ; // Add 6 bits to sumb if (--more == 0) sbuf.append((char) sumb) ; // Add char to sbuf } else if ((b & 0x80) == 0x00) { // 0xxxxxxx (yields 7 bits) sbuf.append((char) b) ; // Store in sbuf } else if ((b & 0xe0) == 0xc0) { // 110xxxxx (yields 5 bits) sumb = b & 0x1f; more = 1; // Expect 1 more byte } else if ((b & 0xf0) == 0xe0) { // 1110xxxx (yields 4 bits) sumb = b & 0x0f; more = 2; // Expect 2 more bytes } else if ((b & 0xf8) == 0xf0) { // 11110xxx (yields 3 bits) sumb = b & 0x07; more = 3; // Expect 3 more bytes } else if ((b & 0xfc) == 0xf8) { // 111110xx (yields 2 bits) sumb = b & 0x03; more = 4; // Expect 4 more bytes } else /*if ((b & 0xfe) == 0xfc)*/ { // 1111110x (yields 1 bit) sumb = b & 0x01; more = 5; // Expect 5 more bytes } /* We don't test if the UTF-8 encoding is well-formed */ } return sbuf.toString() ; } }
Exemple d’utilisation :
Code Java (40 lignes)
public ActionForward execute(ActionMapping actionmapping, ActionForm actionform, HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse) { /*Enumeration e = httpservletrequest.getParameterNames(); while(e.hasMoreElements()){ String name = (String)e.nextElement(); String[]vals = httpservletrequest.getParameterValues(name); str.append("\n"+name+" : "); for(int i = 0;i‹vals.length;i++){ str.append(vals<span class="i">); if(i‹vals.length-1) str.append(", "); } }*/ try { httpservletrequest.setCharacterEncoding("iso-8859-1"); // TODO Auto-generated catch block e.printStackTrace(); } DoemMessage doemMsg = RegionRequestManager.getInstance().createDoemMessage(userRoleID); doemMsg.setMessageText(msg); str.append("\nUserGroupID : "+userRoleID); str.append("\nMessage : "+msg); str.append("\nDate : "+doemMsg.getMessageDateTime()); RegionRequestManager.getInstance().saveDoemMessage(doemMsg); PrintWriter out; try { out = httpservletresponse.getWriter(); out.println(str.toString()); out.flush(); ioe.printStackTrace(); } return null; }
PLus d'infos : http://www.w3.org/International/O-URL-code.html
Un article de Steph
Source : indéterminée
Seuls les membres peuvent laisser un commentaire pour cet article (mesure automatique temporaire due aux attaques de spam par robots dont cet article fait actuellement l'objet).
Deutsche Übersetzung
Sie haben gebeten, diese Seite auf Deutsch zu besuchen. Momentan ist nur die Oberfläche übersetzt, aber noch nicht der gesamte Inhalt.Wenn Sie mir bei Übersetzungen helfen wollen, ist Ihr Beitrag willkommen. Alles, was Sie tun müssen, ist, sich auf der Website zu registrieren und mir eine Nachricht zu schicken, in der Sie gebeten werden, Sie der Gruppe der Übersetzer hinzuzufügen, die Ihnen die Möglichkeit gibt, die gewünschten Seiten zu übersetzen. Ein Link am Ende jeder übersetzten Seite zeigt an, dass Sie der Übersetzer sind und einen Link zu Ihrem Profil haben.
Vielen Dank im Voraus.
Dokument erstellt 13/09/2004, zuletzt geändert 26/10/2018
Quelle des gedruckten Dokuments:https://www.gaudry.be/de/ast-rf-376.html
Die Infobro ist eine persönliche Seite, deren Inhalt in meiner alleinigen Verantwortung liegt. Der Text ist unter der CreativeCommons-Lizenz (BY-NC-SA) verfügbar. Weitere Informationen auf die Nutzungsbedingungen und dem Autor.