无法通过 XMLHttpRequest 在 Action 中获取 Request-scoped 属性

Not able to get Request-scoped attribute in Action through XMLHttpRequest

我正在 jsp 页面中设置 receiverid。我正在使用 ajax 发送 textarea 值 并以相同的方法获得正常工作的客户端 Ip。 我还想获取在 jsp 页面中设置的 receiverid。 但这是显示 NullPointerException.

在jsp

<s:set var="receiverid" value="1" scope="request"/>
<form action="" id="post_message_form">
 <s:textarea name="message"></s:textarea>
 <button type="submit" id="submit_status_button">Submit</button>
</form>


 $(document).on('submit', '#post_message_form', function(f) {
        f.preventDefault();
        var formData = $("#post_message_form").serialize();
        console.log(formData);
        $.ajax({
            type: 'POST',
            url: 'PostIt',
            data: formData,
            dataType: "text html",
            success: function(data) {

            }
        })
    });

在行动

public class UserMessageInsert extends ActionSupport implements ModelDriven<PostMessages> {
    PostMessages pm = new PostMessages();
    private long aid;
    public String insert() {
             HttpServletRequest request = ServletActionContext.getRequest();
            String ipAdd = request.getHeader("X-FORWARDED-FOR");
            if (ipAdd == null) {
                ipAdd = request.getRemoteAddr();
                long l=(Long) request.getAttribute("receiverid");//NulllPointer Exception
                System.out.println("Ip is "+ipAdd+" l is "+getAid());
            }
}

我想问题是 AJAX 调用忽略了您的请求范围的属性,因为它创建了一个全新的 XMLHttpRequest 而不是经典的 HttpRequest。

只需将您的属性作为隐藏参数添加到表单中,除非您有理由不这样做:

<s:set var="receiverid" value="1" scope="request"/>
<form action="" id="post_message_form">

    <s:hidden value="%{#request.receiverid}" name="receiverid" />

    <s:textarea name="message"></s:textarea>
    <button type="submit" id="submit_status_button">Submit</button>
</form>

然后它将被序列化并提交,您将使用 setter 或 getParameter() 访问它,而不是 getAttribute()