Ajax与JSP一些区别

1 JSP直接使用表单的action属性发送请求,而Ajax则是通过js添加事件,再通过Axios来发送请求。

<form action="/demo/Servlet" method="post">
<input @click="add()" type="submit" value="提交">
---------------------------------------------------------
<script src="js/axios-0.18.0.js"></script>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el:"#app",
        method:{
            add(){
                axios({
                //点击提交后,发送ajax请求,请求参数为表单中数据。
                    method:"post",
                    url:"http://localhost:8080/demo/Servlet",
                    data:this.brand
                }).then(function (resp){
                     alert(resp.data)
                });
            }
        }
    })
</script>

2 servlet通过getParameter()方法获取JSP的请求体,通过request.getReader()获取Ajax请求的请求体,再将请求体中的JSON字符串转化为Java对象。

前端发送复杂数据时,比如对象,会使用post请求发送JSON字符串;不过若前端通过Ajax发送简单的数据时,可以通过get方式,即url?参数&参数的方式,此时后端获取数据仍使用getParameter()方法。

//接收表单提交的数据
String brandName = request.getParameter("brandName");
String companyName = request.getParameter("companyName");
String ordered = request.getParameter("ordered");
String description = request.getParameter("description");
String status = request.getParameter("status");
//封装为一个Brand对象
Brand brand = new Brand(null, brandName, companyName, Integer.parseInt(ordered), description, Integer.parseInt(status));
//获取请求体。
BufferedReader br = request.getReader();
String params = br.readLine();
//将json字符串转化为java对象。
Brand brand = JSON.parseObject(params, Brand.class);

3 JSP通过request域和请求转发来接受servlet数据,而Ajax则是通过response响应体来servlet接受数据。

//将数据加入request域中。
request.setAttribute("brands",brands);
//将请求转发到jsp页面。
request.getRequestDispatcher("/showBrands.jsp").forward(request,response);
//将java对象转化为json字符串。
String jsonStr = JSON.toJSONString(brands);
//通过response转发json字符串。
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(jsonStr);

 

posted @ 2023-04-04 16:23  10kcheung  阅读(139)  评论(0)    收藏  举报