aJax提交——服务端不能用request存储数据,session存数据客户端可以接收到

aJax提交与普通提交是两种迥异的提交方式,这两种提交方式决定了客户端与服务端交互时存储、传输数据的方式也不同。

aJax提交,客户端的请求数据存储在data中,服务端用request.getParameter("xxx");接收;服务端调用PrintWriter的write或print方法写出数据至aJax请求的回调函数,回调函数有一个参数data接收服务端写出的数据。

而普通提交一般是将请求数据存储在表单中或在请求路径中,服务端用request.getParameter("xxx");接收;服务端用request、session、application的setAttribute方法存储数据,然后返回客户端,客户端调用request、session、application的getAttribute方法或用EL表达式接收服务端存储在request、session、application中的数据。

示例:

客户端:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="/demo/js/jquery-1.11.2.js"></script>
    <script type="text/javascript">
        function   ajaxTest(){
            $.ajax({
                type: "POST",
                url: "/mytest/test",
                data: "name=John&location=Boston",
                success: function(data){
                    alert( "Data Saved: " + data );//获取服务端写出的数据
                }
            });
        }

    </script>
</head>
<body>
<a href="/mytest/test" >test</a>
reqArrt:<%=request.getAttribute("tttt")%>&nbsp;sessionAttr:<%=session.getAttribute("tttt")%>
EL:${tttt}
<br>
<input id="test" value="testname" > <input value="ajax" type="button" onclick="ajaxTest();">
</body>
</html>

服务端:注:采用springMVC

package com.shyy.web.controller.anntation;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by Administrator on 15-12-6.
 * 测试:1.控制器的方法用request、map、model存储数据,客户端页面用EL/request.getAttribute("tttt")均可获取。
 * 2.前台用ajax提交,控制器的方法用request、map、model存储数据,客户端页面用EL/request.getAttribute("tttt")均获取不到数据。
 * 用session.getAttribute("tttt")可获取存储在session中的数据。
 */
@Controller
@RequestMapping("/mytest")
public class Test {
    @RequestMapping("/test")
    public void test(HttpServletRequest request,Map<String,Object> map,Model model,HttpServletResponse response) throws IOException {
//        map.put("tttt",8888);//ajax提交--客户端页面不可接受到存储在map中的数据
//        model.addAttribute("tttt",7777);//ajax提交--客户端页面不可接受到存储在model中的数据
//        request.setAttribute("tttt",9999);//ajax提交--客户端页面不可接受到存储在request中的数据
//        request.getSession().setAttribute("tttt",11111);//ajax提交--客户端页面可接受到存储在session中的数据

        //获取ajax请求的数据
        String name = request.getParameter("name");
        String location = request.getParameter("location");
        PrintWriter writer =  response.getWriter();
        writer.print(name+"; "+location);

//        return "demo/test";//非ajax提交返回客户端页面的方式--该方法的返回值要改成String
    }
}

此外,如果客户端用aJax提交,并不能用${pageContext.request.contextPath}获取根路径,应该用js的方法(http://www.cnblogs.com/wql025/p/5022725.html)获取。

原文地址:https://www.cnblogs.com/wql025/p/5022831.html