将参数从javascript传递给JSP

时间:2015-03-05 10:48:00

标签: java javascript jsp encryption

我的表单在submit.jsp上使用加密的字符串提交,我在javascript中解密它,并希望解密的字符串从javascript返回jsp。

Submit.jsp

<%
try{

String str=request.getParameter("password2");

out.println("" +str);

String decPass="";

String res="";

String url_name="http://localhost:8086/date/decrypt.jsp";

 String charset="UTF-8";

String query=String.format("encryptedPassword=%s", 

URLEncoder.encode(str,charset));

URL url =  new URL(url_name+"?"+query);

URLConnection con = url.openConnection();

 HttpURLConnection httpConnection = (HttpURLConnection)con;

 httpConnection.setRequestMethod("POST");

 httpConnection.setDoInput(true);

 httpConnection.setDoOutput(true);

 httpConnection.setRequestProperty("Accept-Charset",charset);

 httpConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset="+charset);

 httpConnection.connect();

 OutputStreamWriter wr  = new    OutputStreamWriter(httpConnection.getOutputStream());

 wr.write("query : "+query);


if(httpConnection.getResponseCode()== HttpURLConnection.HTTP_OK )

 {
     String responseMessage = httpConnection.getResponseMessage();
     System.out.println(responseMessage);

     InputStream in = httpConnection.getInputStream();

     BufferedInputStream bufferReader = new BufferedInputStream(in);
     //res=kw.streamToString(in);
     //System.out.println(res);
     BufferedReader br = new BufferedReader(new InputStreamReader(bufferReader));

   while((decPass=br.readLine())!=null)
       {
       out.println(decPass);
       String dec = decPass;
        System.out.println(dec);
       }
  }
  wr.close();
 }
        catch(MalformedURLException me)
         {
            System.out.println("Error Message : "+me.getMessage());
}
        catch(IOException e)
                {
            System.out.println("Error Message : "+ e.getMessage());
            }
%>

这是decrypt.jsp,它解密字符串。它从submit.jsp到HttpUrlConnection获取加密字符串。

Decrypt.jsp

<script src="js/client.js"></script>

        <%
        String encyptPass=request.getParameter("encryptedPassword");

                %>

 <script type="text/javascript">

  var decryptStr = Aes.Ctr.decrypt('<%=encyptPass%>','',256);

document.writeln(decryptStr);


</script>

2 个答案:

答案 0 :(得分:0)

您可以使用<c:out><%out.print();%>将变量结果从JSP打印到JavaScript:

<script type="text/javascript">
  var jsEncyptPass="<c:out value="${encyptPass}"/>";
  // or you can use:   var jsEncyptPass="<%out.print(encyptPass);%>";
  var decryptStr = Aes.Ctr.decrypt(jsEncyptPass,'',256)
  document.writeln(decryptStr);
</script>

答案 1 :(得分:0)

在JSP文件中添加一个隐藏字段。

<input type="hidden" id="someId"/>

现在在js中使用输入id将所需值设置为隐藏字段。

var decryptedString = "decrypted string";

1)如果您使用的是JQuery,请使用以下代码。

    $("#someId").val(decryptedString);

2)使用纯javascript。

var elem = document.getElementById("someId");
elem.value = decryptedString;