No cache version.

Caching disabled. Default setting for this page:enabled (code LNG204)
If the display is too slow, you can disable the user mode to view the cached version.

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

Astuces de l’Infobrol (Java)Article publié le 04/01/2007 13:18:42


Pour 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 :

  1. try {
  2. httpservletrequest.setCharacterEncoding("iso-8859-1");
  3. // TODO Auto-generated catch block
  4. e.printStackTrace();
  5. }


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


  1. ‹%@ page
  2. contentType="text/html; charset=iso-8859-1"
  3. language="java"
  4. isErrorPage="false"
  5. errorPage="errorpage.jsp"
  6. %›
  7. ‹%@ taglib uri="/struts-bean" prefix="bean" %›
  8. ‹%@ taglib uri="/struts-html" prefix="html" %›
  9. ‹%@ taglib uri="/struts-logic" prefix="logic" %›
  10. ‹jsp:include page="/content/pages/testLogin.jsp"/›
  11. ‹html xmlns="http://www.w3.org/1999/xhtml"›
  12. ‹html:base/›
  13. ‹head›
  14. ‹title›Regions Requests - Weather Impact Matrix‹/title›
  15. ‹link rel="stylesheet" type="text/css" href="../../style/design.css" media="screen"/›
  16. ‹link rel="stylesheet" type="text/css" href="../../style/sortabletable.css" media="screen" /›
  17. ‹script type="text/javascript" src="../../scripts/sortabletable.js"›‹/script›
  18. ‹/head›
  19.  
  20. ‹body id="wholeDocument"›
  21. ‹div id="container"›
  22. ‹div id="header"›‹h1 class="header"›WIM : Regions Requests‹/h1›
  23. ‹/div› ‹!-- End of "header" div --›
  24. ‹div id="introduction"›
  25. ‹div id="one"›
  26. ‹h2›1. Flow of Events‹/h2›
  27. ‹p›
  28. 1.1 DOEM3p to WIM
  29. 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
  30. 1.2 WIM to DOEM3p
  31. 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)
  32. 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)
  33. 3. DOEM3p HAS TO pull the necessary data from WIM to be ready for subPara 1.3
  34. 1.3 DOEM3p to AMI
  35. 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.
  36. 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?
  37. 3. AMI HAS TO pull the data concerned when feasible at its discretion.
  38. ‹/p›
  39.  
  40. ‹h3›2. Elaboration Points‹/h3›
  41. ‹p›
  42. 3. Special Requirements
  43. 3.1 Stability of data at CommitDate
  44. 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.
  45.  
  46. ‹/p›
  47. ‹/div› ‹!-- End of "overview" div --›
  48. ‹/div› ‹!-- End of "introduction" div --›
  49.  
  50. ‹div id="mainBody"›
  51. ‹div id="regReq"›
  52. ‹h1›Region requests to do‹/h1›
  53. ‹table border="1" cellspacing="0" align="center" class="sort-table" id="rrTable" width="100%" ›
  54. ‹col /›
  55. ‹col /›
  56. ‹col /›
  57. ‹col /›
  58. ‹thead›
  59. ‹tr›
  60. ‹td›N°‹/td›
  61. ‹td›Request Date‹/td›
  62. ‹td›Country/Sea‹/td›
  63. ‹td›Comment‹/td›
  64. ‹td align="center"›Reply‹/td›
  65. ‹/tr›
  66.  
  67. ‹/thead›
  68. ‹tbody›
  69. ‹logic:empty name="rrForm" property="regionRequests"›
  70. ‹tr›‹td colspan="5"›Nothing Found‹/td›‹/tr›
  71. ‹/logic:empty›
  72. ‹logic:notEmpty name="rrForm" property="regionRequests"›
  73. ‹logic:iterate id="regionRequest" name="rrForm" property="regionRequests" indexId="index"›
  74. ‹bean:define id="rrItem" name="regionRequest" type="be.mil.wim.model.RegionRequest"/›
  75. ‹tr›
  76. ‹td›‹%=index.intValue()+1%›‹/td›
  77. ‹td id="‹%=index.intValue()%›rDte"›
  78. ‹bean:write name="rrItem" property="requestDate" format="dd/MM/yy"/›
  79. ‹/td›
  80. ‹td id="‹%=index.intValue()%›rcs"›
  81. ‹logic:notEmpty name="rrItem" property="geoEntity"›
  82. ‹bean:write name="rrItem" property="geoEntity.name"/›
  83. ‹/logic:notEmpty›
  84. ‹logic:empty name="rrItem" property="geoEntity"›Not defined‹/logic:empty›
  85. ‹/td›
  86. ‹td id="‹%=index.intValue()%›rco"›‹bean:write name="rrItem" property="comment"/›‹/td›
  87. ‹td align="center" class="nosort"› 
  88. ‹input type="button" value="Write response" onclick="getResponseForm(‹%=index.intValue()%›);" /›
  89. ‹span id="‹%=index.intValue()%›rui" class="h"›‹bean:write name="rrItem" property="userRoleID"/›‹/span›
  90. ‹/td›
  91. ‹/tr›
  92. ‹/logic:iterate›
  93. ‹/logic:notEmpty›
  94. ‹/tbody›
  95. ‹/table›
  96. ‹/div›
  97. ‹div id="respFrm" class="h"›
  98. ‹form action="#"›
  99. ‹fieldset align="center"›
  100. ‹legend›Write a response...‹/legend›
  101. ‹div id="rrInfos"›‹/div›
  102. ‹div align="center"›
  103. ‹textarea name="doemMsgTxt" rows="5" cols="40"›‹/textarea›
  104. ‹br /›‹br /›
  105. ‹input type="button" value="Send response" onclick="sendDoemMsg();" /› 
  106. ‹input type="button" onclick="showResponseForm(false);" value="Return to region requests" /›
  107. ‹/div›
  108. ‹/fieldset›
  109. ‹/form›
  110. ‹/div›
  111. ‹script type="text/javascript"›
  112. var st1 = new SortableTable(document.getElementById("rrTable"),
  113. ["Number", "Date", "String", "CaseInsensitiveString", "None"]);
  114.  
  115. function showResponseForm(show){
  116. if(!show)document.getElementById("doemMsgTxt").innerHTML ="";
  117. document.getElementById("regReq").className=(show)?"h":"v";
  118. document.getElementById("respFrm").className=(show)?"v":"h";
  119. }
  120. function getResponseForm(selectedIndex){
  121. disp = "‹p›Selected Region request : ‹span id=\"sRR\"›"+selectedIndex+"‹/span›‹/p›";
  122. disp += "‹p›RequestDate : " + document.getElementById(selectedIndex+"rDte").innerHTML;
  123. disp += "‹/p›‹p›Country/Sea : "+document.getElementById(selectedIndex+"rcs").innerHTML;
  124. disp += "‹/p›‹p›Comment : "+document.getElementById(selectedIndex+"rco").innerHTML+"‹/p›";
  125. document.getElementById("rrInfos").innerHTML = disp;
  126. showResponseForm(true);
  127. }
  128.  
  129. function sendDoemMsg(){
  130. var xhr_object = null;
  131.  
  132. if(window.XMLHttpRequest) // Firefox
  133. xhr_object = new XMLHttpRequest();
  134. else if(window.ActiveXObject) // Internet Explorer
  135. xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
  136. else { // XMLHttpRequest non supported
  137. alert("Your browser does not support XMLHTTPRequest objects...");
  138. return;
  139. }
  140.  
  141. xhr_object.open("GET", "/wim/xhrCreateDoemMsg.do", true);
  142. selectedRRIndex = document.getElementById("srr").innerHTML;
  143. xhr_object.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  144. xhr_object.setRequestHeader("If-Modified-Since","Sat, 1 Jan 2000 00:00:00 GMT");
  145. xhr_object.send("rui="+document.getElementById(selectedRRIndex+"rui").innerHTML+"&msg="+encodeURIComponent(document.getElementById("doemMsgTxt").value));
  146. xhr_object.onreadystatechange = function() {
  147. if(xhr_object.readyState == 4) {
  148. alert(xhr_object.responseText);
  149. showResponseForm(false);
  150. }
  151. }
  152.  
  153. xhr_object.send(null);
  154.  
  155. }
  156. ‹/script›
  157.  
  158. ‹div id="footer"›WIM Version ‹bean:write name="loginForm" property="version"/›‹/div›
  159. ‹/div› ‹!-- End of "mainBody" div --›
  160. ‹jsp:include page="/content/pages/menu.jsp"/›
  161. ‹/div› ‹!-- End of "container" div" --›
  162.  
  163. ‹/body›
  164. ‹/html›


Et l'action Java



  1. /**
  2.  *
  3.  */
  4. package be.mil.wim.web.utils;
  5.  
  6. /**
  7.  *
  8.  *
  9.  */
  10. public class XhrUtils {
  11. public static String unescape(String s) {
  12. StringBuffer sbuf = new StringBuffer () ;
  13. int l = s.length() ;
  14. int ch = -1 ;
  15. int b, sumb = 0;
  16. for (int i = 0, more = -1 ; i ‹ l ; i++) {
  17. /* Get next byte b from URL segment s */
  18. switch (ch = s.charAt(i)) {
  19. case '%':
  20. ch = s.charAt (++i) ;
  21. int hb = (Character.isDigit ((char) ch)
  22. ? ch - '0'
  23. : 10+Character.toLowerCase((char) ch) - 'a') & 0xF ;
  24. ch = s.charAt (++i) ;
  25. int lb = (Character.isDigit ((char) ch)
  26. ? ch - '0'
  27. : 10+Character.toLowerCase ((char) ch)-'a') & 0xF ;
  28. b = (hb ‹‹ 4) | lb ;
  29. break ;
  30. case '+':
  31. b = ' ' ;
  32. break ;
  33. default:
  34. b = ch ;
  35. }
  36. /* Decode byte b as UTF-8, sumb collects incomplete chars */
  37. if ((b & 0xc0) == 0x80) { // 10xxxxxx (continuation byte)
  38. sumb = (sumb ‹‹ 6) | (b & 0x3f) ; // Add 6 bits to sumb
  39. if (--more == 0) sbuf.append((char) sumb) ; // Add char to sbuf
  40. } else if ((b & 0x80) == 0x00) { // 0xxxxxxx (yields 7 bits)
  41. sbuf.append((char) b) ; // Store in sbuf
  42. } else if ((b & 0xe0) == 0xc0) { // 110xxxxx (yields 5 bits)
  43. sumb = b & 0x1f;
  44. more = 1; // Expect 1 more byte
  45. } else if ((b & 0xf0) == 0xe0) { // 1110xxxx (yields 4 bits)
  46. sumb = b & 0x0f;
  47. more = 2; // Expect 2 more bytes
  48. } else if ((b & 0xf8) == 0xf0) { // 11110xxx (yields 3 bits)
  49. sumb = b & 0x07;
  50. more = 3; // Expect 3 more bytes
  51. } else if ((b & 0xfc) == 0xf8) { // 111110xx (yields 2 bits)
  52. sumb = b & 0x03;
  53. more = 4; // Expect 4 more bytes
  54. } else /*if ((b & 0xfe) == 0xfc)*/ { // 1111110x (yields 1 bit)
  55. sumb = b & 0x01;
  56. more = 5; // Expect 5 more bytes
  57. }
  58. /* We don't test if the UTF-8 encoding is well-formed */
  59. }
  60. return sbuf.toString() ;
  61. }
  62.  
  63. }


Exemple d’utilisation :

  1. public ActionForward execute(ActionMapping actionmapping, ActionForm actionform,
  2. HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse) {
  3. /*Enumeration e = httpservletrequest.getParameterNames();
  4. while(e.hasMoreElements()){
  5. String name = (String)e.nextElement();
  6. String[]vals = httpservletrequest.getParameterValues(name);
  7. str.append("\n"+name+" : ");
  8. for(int i = 0;i‹vals.length;i++){
  9. str.append(vals<span class="i">);
  10. if(i&#139;vals.length-1) str.append(", ");
  11. }
  12. }*/
  13. try {
  14. httpservletrequest.setCharacterEncoding("iso-8859-1");
  15. // TODO Auto-generated catch block
  16. e.printStackTrace();
  17. }
  18. String msg = XhrUtils.unescape(httpservletrequest.getParameter("msg"));
  19. int userRoleID = Integer.parseInt(httpservletrequest.getParameter("rui"));
  20. DoemMessage doemMsg = RegionRequestManager.getInstance().createDoemMessage(userRoleID);
  21. doemMsg.setMessageText(msg);
  22. doemMsg.setMessageDateTime(new Date());
  23.  
  24. StringBuilder str = new StringBuilder("\n\nParameters send :\n");
  25. str.append("\nUserGroupID : "+userRoleID);
  26. str.append("\nMessage : "+msg);
  27. str.append("\nDate : "+doemMsg.getMessageDateTime());
  28.  
  29. RegionRequestManager.getInstance().saveDoemMessage(doemMsg);
  30. try {
  31. out = httpservletresponse.getWriter();
  32. out.println(str.toString());
  33. out.flush();
  34. } catch (IOException ioe) {
  35. ioe.printStackTrace();
  36. }
  37. return null;
  38. }


PLus d'infos : http://www.w3.org/International/O-URL-code.html

Avatar :: Steph 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).
Sélection, tri et recherche d'articles
FILTRER :
TRIER :1er critère : 2e critère :
CHERCHER : Dans les titres Dans le contenu


[Afficher les liens en fonction des critères du formulaire ci-dessus]

English translation

You have asked to visit this site in English. For now, only the interface is translated, but not all the content yet.

If you want to help me in translations, your contribution is welcome. All you need to do is register on the site, and send me a message asking me to add you to the group of translators, which will give you the opportunity to translate the pages you want. A link at the bottom of each translated page indicates that you are the translator, and has a link to your profile.

Thank you in advance.

Document created the 13/09/2004, last modified the 26/10/2018
Source of the printed document:https://www.gaudry.be/en/ast-rf-376.html

The infobrol is a personal site whose content is my sole responsibility. The text is available under CreativeCommons license (BY-NC-SA). More info on the terms of use and the author.