ajax 用户名密码登陆验证 java jsp

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="prc" value="${pageContext.request.contextPath}"></c:set>
<!DOCTYPE html> 
<html> 
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script type="text/javascript" src="${prc}/js/jquery-3.2.1.min.js"></script>
    	<script type="text/javascript" src="${prc}/js/testjs.js"></script>
    </head>
    <body>
         
        <form action="">
            <table border="0">
                <tr><td>用户名:</td><td><input type="text" name="name"/></td></tr>
                <tr><td>密码:</td><td><input type="password" name="pwd"/></td></tr>
                <tr><td></td><td><input type="button" id="btnSubmit" value="提交"/></td></tr>
            </table>
        </form>
        <div id="show"></div>
        
<%-- JSP EL隐含对象
pageScope	page 作用域
requestScope	request 作用域
sessionScope	session 作用域
applicationScope	application 作用域
param	Request 对象的参数,字符串
paramValues	Request对象的参数,字符串集合
header	HTTP 信息头,字符串
headerValues	HTTP 信息头,字符串集合
initParam	上下文初始化参数
cookie	Cookie值
pageContext	当前页面的pageContext
您可以在表达式中使用这些对象,就像使用变量一样。接下来会给出几个例子来更好的理解这个概念。

pageContext对象
pageContext对象是JSP中pageContext对象的引用。通过pageContext对象,您可以访问request对象。比如,访问request对象传入的查询字符串,就像这样:

${pageContext.request.queryString}
Scope对象
pageScope,requestScope,sessionScope,applicationScope变量用来访问存储在各个作用域层次的变量。

举例来说,如果您需要显式访问在applicationScope层的box变量,可以这样来访问:applicationScope.box。

param和paramValues对象
param和paramValues对象用来访问参数值,通过使用request.getParameter方法和request.getParameterValues方法。

举例来说,访问一个名为order的参数,可以这样使用表达式:${param.order},或者${param["order"]}。

接下来的例子表明了如何访问request中的username参数: --%>
<%-- <%@ page import="java.io.*,java.util.*" %>
<%
    String title = "Accessing Request Param";
%> --%>
<%-- <html>
<head>
<title><% out.print(title); %></title>
</head>
<body>
<center>
<h1><% out.print(title); %></h1>
</center>
<div align="center">
<p>${param["username"]}</p>
</div>
</body>
</html> --%>
<%-- param对象返回单一的字符串,而paramValues对象则返回一个字符串数组。

header和headerValues对象
header和headerValues对象用来访问信息头,通过使用 request.getHeader方法和request.getHeaders方法。

举例来说,要访问一个名为user-agent的信息头,可以这样使用表达式:${header.user-agent},或者${header["user-agent"]}。

接下来的例子表明了如何访问user-agent信息头: --%>

<%-- <%@ page import="java.io.*,java.util.*" %>
<%
    String title = "User Agent Example";
%> --%>
<%-- <html>
<head>
<title><% out.print(title); %></title>
</head>
<body>
<center>
<h1><% out.print(title); %></h1>
</center>
<div align="center">
<p>${header["user-agent"]}</p>
</div>
</body>
</html>
运行结果如下: --%>

<%-- <c:set var="aaa" value="${request.getContextPath() }"></c:set>
<c:set var="prc" value="${pageContext.request.contextPath}"></c:set> --%>
<%-- aaa:${aaa }<br/> --%> <!-- 没有输出  -->
<%-- prc:${prc }<br/> --%> <!-- 输出:/ajaxtest  -->
<%-- 
<% out.println(request.getContextPath()); %> --%>  <!-- 输出:/ajaxtest  -->

<%-- <%= request.getContextPath() %>  --%> <!-- 输出:/ajaxtest  -->

<%-- <c:out value="${request.getContextPath() }"></c:out><br/>  --%> <!-- 没有输出  -->
<%-- <c:out value="request.getContextPath()"></c:out><br/>  --%> <!-- 输出 request.getContextPath() -->
<%-- <c:out value="${pageContext.request.contextPath}"></c:out> --%><!-- 输出:/ajaxtest  -->
<%-- <c:out value="sss"></c:out><br/>   --%> <!-- 输出:sss  -->
<%-- <jsp:setProperty name="box" property="perimeter" value="100"/>
${expr} --%>
<%-- <jsp:setProperty name="box" property="perimeter" 
                 value="${2*box.width+2*box.height}"/> --%>
    </body>
</html>

Testservlet.java

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>
}

testjs.js

/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
 
    $(document).ready(function(){
        //$("[value=GETsubmit]").click(function(){
    	$("#btnSubmit").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("==信息不符合,1秒后自动跳入登陆页面!==")
                        //window.onload("index.jsp");
                        //sendRedirect(index.jsp);
                       /* window.onload(){
                        	sendRedirect(index.jsp);
                        }*/
                        //window.location.href="https://www.baidu.com";
                        //window.location.href="index.jsp";
                        function countDown(){
                        	setTimeout("window.location.href='index.jsp'",1000);
                        }
                        //执行1秒后跳转函数
                        countDown();
                        
                    }
                },
                error: function(){
                    $("#show").html("Error XMLHttpRequest");
                }
            });
        });
    });

猜你喜欢

转载自blog.csdn.net/huawuque004/article/details/82811264