1. 程式人生 > >jsp用ajax傳值給servlet並返回

jsp用ajax傳值給servlet並返回

1、index.jsp

<%-- 
    Document   : index
    Created on : 2017-9-26, 22:27:13
    Author     : Administrator
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script src="js/jquery-3.1.1.min.js"></script>
        <script src="js/testjs.js"></script>
    </head>
    <body>
        <form action="">
            <table border="0">
                <tr><td>name:</td><td><input type="text" name="name"/></td></tr>
                <tr><td>password:</td><td><input type="password" name="pwd"/></td></tr>
                <tr><td></td><td><input type="button" value="GETsubmit"/></td></tr>
            </table>
        </form>
        <div id="show"></div>
    </body>
</html>

2、test.js
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

    $(document).ready(function(){
        $("[value=GETsubmit]").click(function(){
            $.ajax({
                type: "POST",
                url: "testservlet?name="+$("[name=name]").val()+"&pwd="+$("[name=pwd]").val()+"&date="+new Date().getTime(),
                dataType: "text",
                success: function(data){
                    if(data=="true"){
                        $("#show").html("===ok==="+"<br/>"+"name="+$("[name=name]").val()+"<br/>"+"pwd="+$("[name=pwd]").val());
                    }else if(data=="false"){
                        $("#show").html("==資訊不符合==")
                        window.onload("index.jsp");
                    }
                },
                error: function(){
                    $("#show").html("Error XMLHttpRequest");
                }
            });
        });
    });


3、Testservlet.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Administrator
 */
@WebServlet(name = "Testservlet", urlPatterns = {"/testservlet"})
public class Testservlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Testservlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet Testservlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/text; charset=utf-8");
        PrintWriter out = response.getWriter();
        
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        System.out.println("name="+name+" pwd="+pwd);
        if(name.equals("admin") && pwd.equals("123456")){
            try {
                out.write("true");
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                out.close();
            }
        }else{
            try {
                out.write("false");
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                out.close();
            }
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}