包含JavaScript登陆时校验和服务器端的校验
JSP校验意义
客户端验证:使用JavaScript验证
好处:降低服务器端负担 不足: 不安全,可以跳过只能进行格式验证,无法进行业务验证(用户名是否存在)
服务器端验证:使用JSP验证
好处: 安全 可以进行格式验证和业务验证
不足:增加了服务器端的负担 建议:同时进行服务器端和客户端验证
导包(Jquery包)
Login.jsp(登录界面)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录界面</title>
<script type="text/javascript" src="js/jquery-1.12.3.min.js"></script>
<script type="text/javascript">
$(function () {
$("#uname").blur(function () {
//进行用户名的非空校验
var val =$("#uname").val();
if(val==null||val==""){
$("#uname_span").text("用户名不能为空").css("color","red");
}else {
$("#uname_span").text("用户名合法").css("color","green");
}
})
$("#pwd").blur(function () {
//进行密码的非空校验
var val =$("#pwd").val();
if(val==null||val==""){
$("#pwd_span").text("密码不能为空").css("color","red");
}else {
$("#pwd_span").text("密码合法").css("color","green");
}
})
})
</script>
</head>
<body>
<h3>用户登录</h3>
<form action="DoLoginServlet" method="post">
<p>
账号:<input type="text" name="uname" id="uname"/>
<span id="uname_span">
<%
Object msg= request.getAttribute("msg");
if(msg!=null){
out.print(msg);
}
%>
</span>
</p>
<p>
密码:<input type="password" name="pwd" id="pwd">
<span id="pwd_span">
</span>
</p>
<p>
<input type="submit" value="提交"/>
</p>
</form>
</body>
</html>
success.jsp(登录成功界面)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>成功登录</title>
</head>
<body>
<h1>成功登录</h1>
</body>
</html>
fa.jsp(非法登录拦截)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>警告</title>
</head>
<body>
<h1>滚</h1>
<h4>好好登┗|`O′|┛ 嗷~~</h4>
<h4>想啥呢</h4>
<h4>滚去正常登陆去</h4>
</body>
</html>
DoLoginServlet.java(servlet流程控制)
package com.java.servlet;
import com.sun.net.httpserver.HttpServer;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = "/DoLoginServlet")
public class DoLoginServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接收数据
String uname = req.getParameter("uname");
String pwd = req.getParameter("pwd");
//服务端校验
if(uname==null||"".equals(uname)){
req.getRequestDispatcher("fa.jsp").forward(req,resp);
return;
}
//处理数据
boolean flage= false;
if ("sxt".equals(uname)&&"123".equals(pwd)){
flage= true;
}
//做出响应
if (flage){
req.getRequestDispatcher("success.jsp").forward(req,resp);
}else{
req.setAttribute("msg","用户名和密码不匹配");
req.getRequestDispatcher("Login.jsp").forward(req,resp);
}
}
}