سؤال

How to use Struts2 token in jQuery Ajax?

Here is my sample code but it returns empty value.

<body>
<s:token />
<script>
    var strutsToken = "<s:property value="#session['struts.tokens.token']" />";

    var token = {
        "struts.token.name": "token",
        "token": strutsToken
    };

    alert(token.token);
</script>

<s:if test="hasActionErrors()">
    <s:actionerror />
</s:if>
<br>
<s:form action="UpdateUser">
    <s:textfield name="name" label="User Name"></s:textfield>
    <s:textfield name="address" label="Address"></s:textfield>
    <s:submit name="submit" value="Update"></s:submit>
    <s:token />
</s:form>

هل كانت مفيدة؟

المحلول

You need to generate a token before you make Ajax call.

The s:token tag merely places a hidden element that contains the unique token.

You need to put this hidden element inside the form, so it to be included among other fields that are submitted. Check the usage of the <s:token> tag. If you want to make an Ajax call you can do it in many ways, so you can check this answer too for Struts token interceptor. One way is to use jQuery plugin and its <sj:submit> tag.

<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
<html>
  <head>
    <sj:head/>
  </head>
  <body>

<s:form action="UpdateUser">
    <s:textfield name="name" label="User Name"></s:textfield>
    <s:textfield name="address" label="Address"></s:textfield>
    <sj:submit name="submit" value="Update"></s:submit>
    <s:token />
</s:form>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top