使用jquery 的ajax 与 Java servlet的交互

时间:2021-09-11 16:23:43

由于是使用jquery的 所以别忘记导入jq 

下面是jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <script src="js/jquery-3.3.1.js"></script>
    <script type="text/javascript">
        function ajaxFun(){
            $.ajax({
                type: "POST",                            //传数据的方式
                url: "user",                             //servlet地址

                data: $('#form').serialize(),            //传的数据  form表单 里面的数据
                success: function(result){               //传数据成功之后的操作   result是servlet传过来的数据  这个函数对result进行处理,让它显示在 输入框中
                    $("#results").val(result);           //找到输入框 并且将result的值 传进去
                }
            });
        }

    </script>
</head>
<body>
<H1 align="center">请输入两个字符串</H1>
<div align="center">
    <form id="form">
        first:<input type="text" name="first" id="first">
        second:<input type="text" name="second" id="second">
     //点击按钮的时候触发属性 <button type="button" onclick="ajaxFun()">button</button> //提交 按钮 </form> <input type="text" id="results"> // 用来 显示 result </div> </body> </html>

  然后是 servlet 文件

  

package com.java.servlet;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * Ajax 训练
 * */
public class UserServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        String first = request.getParameter("first");           //从前端获取数据first
        String second = request.getParameter("second");         //从前端获取数据second
        String result=first+second;
        System.out.println(result);                                      //用于测试 ,判断是否成功获取到数据;
        out.println(result);                                                 //将数据传到前端


    }
}