Java全栈(四)web网页技术:11.书城项目实战二:JSP练习及Servlet优化

前提:还是基于我们前面的书城项目

1.需求1:1.将所有HTML页面改为JSP页面

  • 在每一个HTML页面的第一行添加JSP的page指令:
    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>,然后将HTML页面的文件扩展名改为jsp,即将.html改为.jsp。注意:一定要先在HTML页面中添加jsp指令再修改扩展名,否则页面中会出现乱码现象。

    这里以index.html为例
    在这里插入图片描述

  • 将每一个jsp文件中路径为html文件的都改为jsp文件

    这里以index.jsp文件为例
    在这里插入图片描述
    运行项目,在界面点击看看,是不是每一个页面都能访问到

2.需求2:提取页面公共内容

我们的jsp页面,往往会有大量重复的代码。这时我们可以将其抽取为一个jsp文件,然后在需要的页面直接使用静态或动态包含,将公共的jsp文件引入到当前页面中

2.1 抽取所有页面公共的部分到base.jsp文件中

每个jsp文件都需要设置设置项目跟路径到base标签,也需要导入jQuery源码。我们可以把这些抽取到base,jsp文件中

  • 如下在WEB-INF目录下创建punlic_jsp/base.jsp文件在这里插入图片描述

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <base href="http://localhost:8080/bookStore2/"/>
    <script type="text/javascript" src="static/script/jquery-1.7.2.js"></script>
    
  • 在每个jsp文件中,引入base.jsp文件。原来的base标签和导入jQuery源码的script 标签可以删掉

    这里以login.jsp为例:
    在这里插入图片描述

3.需求3:注册登录显示错误消息及表单回显

  • 登录、注册失败时我们分别转发到了登录、注册页面,但是并没有给用户一个错误消息,用户体验差,现在我们分别为登录、注册失败时提供一个错误消息并在页面显示:
  • 登录、注册失败时我们将错误消息放到request域中,通过转发将错误消息带到登录、注册页面,然后在页面中通过request域对象获取错误消息。
  • 登录、注册失败时我们输入的用户名等信息会被清空,为了让用户有更好的体验,让用户看到之前输入的内容,需要对表单进行回显:
  • 给需要回显的表单项设置value属性,value值通过request.getParameter(“属性值”)来获取。

3.1 登录失败显示错误提示

在这里插入图片描述

  • 修改LoginServlet内容:
    package com.bookstore.servlet;
    
    import com.bookstore.bean.User;
    import com.bookstore.service.UserServices;
    import com.bookstore.service.impl.UserservicesImpl;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    import java.io.IOException;
    
    @WebServlet(name = "LoginServlet", value = "/login")
    public class LoginServlet extends HttpServlet {
        private UserServices userservices = new UserservicesImpl();
    
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //获取用户名,密码
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            // 检查用户名密码是否正确
            User userOld = new User();
            userOld.setUsername(username);
            userOld.setPassword(password);
            User loginUser = userservices.login(userOld);
            if (loginUser != null) {
                // 用户名密码正确
                response.sendRedirect("/bookStore2/pages/user/login_success.jsp");
            } else {
                // 用户名密码不正确
                request.setAttribute("msg","用户名或密码错误,请重新输入"); // 将提示内容写入request域中
                request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }
    
  • 修改login.jsp文件,获取并显示错误信息
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <!DOCTYPE html>
    <html>
      <head>
        <%@ include file="/WEB-INF/public_jsp/base.jsp"%>
        <!--base href="http://localhost:8080/bookStore2/"/-->
        <meta charset="UTF-8" />
        <title>尚硅谷会员登录页面</title>
        <link type="text/css" rel="stylesheet" href="static/css/style.css" />
        <!--script type="text/javascript" src="static/script/jquery-1.7.2.js"></script-->
        <script type="text/javascript" src="static/script/login.js"></script>
    
      </head>
      <body>
        <div id="login_header">
          <a href="index.jsp">
            <img class="logo_img" alt="" src="static/img/logo.gif" />
          </a>
        </div>
    
        <div class="login_banner">
          <div id="l_content">
            <span class="login_word">欢迎登录</span>
          </div>
    
          <div id="content">
            <div class="login_form">
              <div class="login_box">
                <div class="tit">
                  <h1>尚硅谷会员</h1>
                </div>
                <div class="msg_cont">
                  <b></b>
                  <!--根据request域中是否由msg,来判断要显示的内容-->
                  <span class="errorMsg"><%=request.getAttribute("msg")==null?"请输入用户名密码":request.getAttribute("msg")%></span>
                </div>
                <div class="form">
                  <form action="login">
                    <label>用户名称:</label>
                    <input
                      class="itxt"
                      type="text"
                      placeholder="请输入用户名"
                      autocomplete="off"
                      tabindex="1"
                      name="username"
                      id="username"
                    />
                    <br />
                    <br />
                    <label>用户密码:</label>
                    <input
                      class="itxt"
                      type="password"
                      placeholder="请输入密码"
                      autocomplete="off"
                      tabindex="1"
                      name="password"
                      id="password"
                    />
                    <br />
                    <br />
                    <input type="submit" value="登录" id="sub_btn" />
                  </form>
                  <div class="tit">
                    <a id = "submit" href="pages/user/regist.jsp">立即注册</a>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div id="bottom">
          <span>
            尚硅谷书城.Copyright &copy;2015
          </span>
        </div>
      </body>
    </html>
    

效果如下:
在这里插入图片描述

3.2 注册失败显示错误消息

在这里插入图片描述

  • 修改RegisteServlet内容,注册失败时,将错误信息添加到request域中
    package com.bookstore.servlet;
    
    import com.bookstore.bean.User;
    import com.bookstore.service.impl.UserservicesImpl;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    import java.io.IOException;
    
    @WebServlet(name = "RegisteServlet", value = "/register")
    public class RegisteServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String email = request.getParameter("email");
            User user = new User(null,username,password,email);
            UserservicesImpl userservices = new UserservicesImpl();
            boolean registFag = userservices.regist(user);
            if (registFag){
                response.sendRedirect("/bookStore2/pages/user/regist_success.jsp");
            }else {
                request.setAttribute("msg","用户名已存在");
                request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request,response);
        }
    }
    
  • 修改register.jsp文件,获取错误提示
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <!DOCTYPE html>
    <html>
      <head>
        <%@ include file="/WEB-INF/public_jsp/base.jsp"%>
        <meta charset="UTF-8" />
        <title>尚硅谷会员注册页面</title>
        <link type="text/css" rel="stylesheet" href="static/css/style.css" />
        <link rel="stylesheet" href="static/css/register.css" />
        <style type="text/css">
          .login_form {
            height: 420px;
            margin-top: 25px;
          }
        </style>
        <script type="text/javascript" src="static/script/regist.js"></script>
      </head>
      <body>
        <div id="login_header">
          <a href="index.jsp">
            <img class="logo_img" alt="" src="static/img/logo.gif" />
          </a>
        </div>
    
        <div class="login_banner">
          <div class="register_form">
            <h1>注册尚硅谷会员</h1>
            <form action="register">
              <div class="form-item">
                <div>
                  <label>用户名称:</label>
                  <input id="username" type="text" name="username" placeholder="请输入用户名"/>
                </div>
                <!--根据request域中是否有错误提示,来判断使用哪个内容-->
                <span class="errMess" id="userErrMess">
                  <%=request.getAttribute("msg")==null?"用户名、密码:只能是字母(大小写)、数字、_。6-18位":request.getAttribute("msg")%>
                </span>
              </div>
              <div class="form-item">
                <div>
                  <label>用户密码:</label>
                  <input type="password" id="password" name="password" placeholder="请输入密码" />
                </div>
                <span class="errMess" id="passErrMess">只能是字母(大小写)、数字、_。6-18</span>
              </div>
              <div class="form-item">
                <div>
                  <label>确认密码:</label>
                  <input type="password" id="rePassword" name="rePassword" placeholder="请输入确认密码" />
                </div>
                <span class="errMess" id="rePasswordErrMess">密码两次输入不一致</span>
              </div>
              <div class="form-item">
                <div>
                  <label>用户邮箱:</label>
                  <input type="text" id="email" name="email" placeholder="请输入邮箱" />
                </div>
                <span class="errMess" id="emailErrMess">请输入正确的邮箱格式</span>
              </div>
              <div class="form-item">
                <div>
                  <label>验证码:</label>
                  <div class="verify">
                    <input type="text" id="verify" placeholder="" />
                    <img src="static/img/code.bmp" alt="" />
                  </div>
                </div>
                <span class="errMess" id="verifyErrMess">请输入正确的验证码</span>
              </div>
              <button class="btn" id="register">注册</button>
            </form>
          </div>
        </div>
        <div id="bottom">
          <span>
            尚硅谷书城.Copyright &copy;2015
          </span>
        </div>
      </body>
    </html>
    

我们会发现,此时并没有效果。因为该<span>标签默认是隐藏的。我们需要在js代码中,实现当msg存在时,也将<span>标签设置为显示状态

  • 第一步:我们先将处理注册页面的js文件register.js修改为jsp文件,这样我们在该文件中也可以直接使用jsp相关的东西。而导入时直接使用jsp的包含动作,将对应的文件引入即可
    在这里插入图片描述
    在这里插入图片描述

  • 修改register.js.jsp文件,新增js代码,当页面刷新时,判断request域中是否有msg属性,有表示注册失败,需要将<span>标签设置为显示状态

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <script type="text/javascript">
        $(function () {
    
            /**
             * 校验request域中是否有msg属性
             */
            <%
                Object msg = request.getAttribute("msg");
                if (msg == null){
                    // request域中不存在对应错误信息
                }else {
                    // request域中存在对应错误信息
            %>
            $("#userErrMess").css("visibility", "visible"); // 显示对应错误信息
            <%}%>
    
            /**
             * 用户名校验
             */
            function checkUsername() {
                var reg = /^[a-zA-Z0-9_]{6,18}$/;
                var userVaule = $("#username").val();
                if (reg.test(userVaule) == false) {
                    $("#userErrMess").css("visibility", "visible");
                    return false;
                } else {
                    $("#userErrMess").css("visibility", "hidden");
                }
            }
    
            /**
             * 密码校验
             */
            function checkPassword() {
                var reg = /^[a-zA-Z0-9_]{6,18}$/;
                var passwordValue = $("#password").val();
                if (reg.test(passwordValue) == false) {
                    $("#passErrMess").css("visibility", "visible");
                    return false;
                } else {
                    $("#passErrMess").css("visibility", "hidden");
                }
            }
    
    
            /**
             * 确认密码
             */
            function checkrePassword() {
                var passwordValue = $("#password").val();
                var rePasswordValue = $("#rePassword").val();
                if (passwordValue != rePasswordValue) {
                    $("#rePasswordErrMess").css("visibility", "visible");
                    return false;
                } else {
                    $("#rePasswordErrMess").css("visibility", "hidden");
                }
            }
    
            /**
             * 检查邮箱
             */
            function checkEmail(){
                var reg = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
                var emailValue = $("#email").val();
                if (reg.test(emailValue) == false){
                    $("#emailErrMess").css("visibility", "visible");
                    return false;
                }else {
                    $("#emailErrMess").css("visibility", "hidden");
                }
            }
    
            function checkVerify(){
                var verifyValue = $("#verify").val();
                if (verifyValue == ""){
                    $("#verifyErrMess").css("visibility", "visible");
                    return false;
                }else {
                    $("#verifyErrMess").css("visibility", "hidden");
                }
            }
    
            // 注册栏内容改变后校验
            $("#username").change(checkUsername);
            $("#password").change(checkPassword);
            $("#rePassword").change(checkrePassword);
            $("#email").change(checkEmail);
            $("#verify").change(checkVerify);
    
            // 注册按钮后校验
            $("#register").click(checkUsername);
            $("#register").click(checkPassword);
            $("#register").click(checkrePassword);
            $("#register").click(checkEmail);
            $("#register").click(checkVerify);
        })
    </script>
    
    

效果如下:
在这里插入图片描述
但是现在还有一个问题,就是在这种情况下,当我们的重新输入的用户名校验不通过时,提示信息还是用户名已存在,这是不符合逻辑的。

  • 解决:就是在用户名change函数中,重置一下提示信息
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<script type="text/javascript">
    $(function () {

        /**
         * 校验request域中是否有msg属性
         */
        <%
            Object msg = request.getAttribute("msg");
            if (msg == null){
                // request域中不存在对应错误信息
            }else {
                // request域中存在对应错误信息
        %>
        $("#userErrMess").css("visibility", "visible"); // 显示对应错误信息
        <%}%>

        /**
         * 用户名校验
         */
        function checkUsername() {
            var reg = /^[a-zA-Z0-9_]{6,18}$/;
            var userVaule = $("#username").val();
            if (reg.test(userVaule) == false) {
                $("#userErrMess").text("用户名、密码:只能是字母(大小写)、数字、_。6-18位").css("visibility", "visible");
                return false;
            } else {
                $("#userErrMess").css("visibility", "hidden");
            }
        }

        /**
         * 密码校验
         */
        function checkPassword() {
            var reg = /^[a-zA-Z0-9_]{6,18}$/;
            var passwordValue = $("#password").val();
            if (reg.test(passwordValue) == false) {
                $("#passErrMess").css("visibility", "visible");
                return false;
            } else {
                $("#passErrMess").css("visibility", "hidden");
            }
        }


        /**
         * 确认密码
         */
        function checkrePassword() {
            var passwordValue = $("#password").val();
            var rePasswordValue = $("#rePassword").val();
            if (passwordValue != rePasswordValue) {
                $("#rePasswordErrMess").css("visibility", "visible");
                return false;
            } else {
                $("#rePasswordErrMess").css("visibility", "hidden");
            }
        }

        /**
         * 检查邮箱
         */
        function checkEmail(){
            var reg = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
            var emailValue = $("#email").val();
            if (reg.test(emailValue) == false){
                $("#emailErrMess").css("visibility", "visible");
                return false;
            }else {
                $("#emailErrMess").css("visibility", "hidden");
            }
        }

        function checkVerify(){
            var verifyValue = $("#verify").val();
            if (verifyValue == ""){
                $("#verifyErrMess").css("visibility", "visible");
                return false;
            }else {
                $("#verifyErrMess").css("visibility", "hidden");
            }
        }

        // 注册栏内容改变后校验
        $("#username").change(checkUsername);
        $("#password").change(checkPassword);
        $("#rePassword").change(checkrePassword);
        $("#email").change(checkEmail);
        $("#verify").change(checkVerify);

        // 注册按钮后校验
        $("#register").click(checkUsername);
        $("#register").click(checkPassword);
        $("#register").click(checkrePassword);
        $("#register").click(checkEmail);
        $("#register").click(checkVerify);
    })
</script>

3.3 注册失败后实现表单回显

即注册失败后,之前的数据不要清除。

  • 修改register.jsp文件,实现表单回显功能
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
  <head>
    <%@ include file="/WEB-INF/public_jsp/base.jsp"%>
    <meta charset="UTF-8" />
    <title>尚硅谷会员注册页面</title>
    <link type="text/css" rel="stylesheet" href="static/css/style.css" />
    <link rel="stylesheet" href="static/css/register.css" />
    <style type="text/css">
      .login_form {
        height: 420px;
        margin-top: 25px;
      }
    </style>
    <%@ include file="/static/script/regist.js.jsp"%>
    <!--script type="text/javascript" src="static/script/regist.js.jsp"></script-->
  </head>
  <body>
    <div id="login_header">
      <a href="index.jsp">
        <img class="logo_img" alt="" src="static/img/logo.gif" />
      </a>
    </div>

    <div class="login_banner">
      <div class="register_form">
        <h1>注册尚硅谷会员</h1>
        <form action="register">
          <div class="form-item">
            <div>
              <label>用户名称:</label>
              <!--根据请求参数中是否存在值,来判断是否需要回显-->
              <input id="username" value="<%=request.getParameter("username")==null?"":request.getParameter("username")%>" type="text" name="username" placeholder="请输入用户名"/>
            </div>
            <!--根据request域中是否有错误提示,来判断使用哪个内容-->
            <span class="errMess" id="userErrMess">
              <%=request.getAttribute("msg")==null?"用户名、密码:只能是字母(大小写)、数字、_。6-18位":request.getAttribute("msg")%>
            </span>
          </div>
          <div class="form-item">
            <div>
              <label>用户密码:</label>
              <input type="password" value="<%=request.getParameter("password")==null?"":request.getParameter("password")%>" id="password" name="password" placeholder="请输入密码" />
            </div>
            <span class="errMess" id="passErrMess">只能是字母(大小写)、数字、_。6-18</span>
          </div>
          <div class="form-item">
            <div>
              <label>确认密码:</label>
              <input type="password" value="<%=request.getParameter("rePassword")==null?"":request.getParameter("rePpassword")%>" id="rePassword" name="rePassword" placeholder="请输入确认密码" />
            </div>
            <span class="errMess" id="rePasswordErrMess">密码两次输入不一致</span>
          </div>
          <div class="form-item">
            <div>
              <label>用户邮箱:</label>
              <input type="text" value="<%=request.getParameter("email")==null?"":request.getParameter("email")%>" id="email" name="email" placeholder="请输入邮箱" />
            </div>
            <span class="errMess" id="emailErrMess">请输入正确的邮箱格式</span>
          </div>
          <div class="form-item">
            <div>
              <label>验证码:</label>
              <div class="verify">
                <input type="text" id="verify" placeholder="" />
                <img src="static/img/code.bmp" alt="" />
              </div>
            </div>
            <span class="errMess" id="verifyErrMess">请输入正确的验证码</span>
          </div>
          <button class="btn" id="register">注册</button>
        </form>
      </div>
    </div>
    <div id="bottom">
      <span>
        尚硅谷书城.Copyright &copy;2015
      </span>
    </div>
  </body>
</html>

效果如下:
在这里插入图片描述

4.需求4:Sevlet优化

现在我们的项目是一个请求对应一个Servlet,我们能不能将多个请求对应一个Servlet呢?比如用户登录、注册的LoginServlet、RegistServlet使用一个UserServlet代替。

4.1 将LoginServlet、RegistServlet合并

  • login.jsp文件和regist.jsp中添加一个隐藏的表单项,用来标识当前请求
    <form action="UserServlet">
      <input type="hidden" name="method" value="login"/> <!--用来标识当前请求-->
      <label>用户名称:</label>
      <input
        class="itxt"
        type="text"
        placeholder="请输入用户名"
        autocomplete="off"
        tabindex="1"
        name="username"
        id="username"
      />
      <br />
      <br />
      <label>用户密码:</label>
      <input
        class="itxt"
        type="password"
        placeholder="请输入密码"
        autocomplete="off"
        tabindex="1"
        name="password"
        id="password"
      />
      <br />
      <br />
      <input type="submit" value="登录" id="sub_btn" />
    </form>
    
    <form action="UserServlet">
      <input type="hidden" name="method" value="register"/>
      <div class="form-item">
        <div>
          <label>用户名称:</label>
          <!--根据请求参数中是否存在值,来判断是否需要回显-->
          <input id="username" value="<%=request.getParameter("username")==null?"":request.getParameter("username")%>" type="text" name="username" placeholder="请输入用户名"/>
        </div>
        <!--根据request域中是否有错误提示,来判断使用哪个内容-->
        <span class="errMess" id="userErrMess">
          <%=request.getAttribute("msg")==null?"用户名、密码:只能是字母(大小写)、数字、_。6-18位":request.getAttribute("msg")%>
        </span>
      </div>
      <div class="form-item">
        <div>
          <label>用户密码:</label>
          <input type="password" value="<%=request.getParameter("password")==null?"":request.getParameter("password")%>" id="password" name="password" placeholder="请输入密码" />
        </div>
        <span class="errMess" id="passErrMess">只能是字母(大小写)、数字、_。6-18位</span>
      </div>
      <div class="form-item">
        <div>
          <label>确认密码:</label>
          <input type="password" value="<%=request.getParameter("rePassword")==null?"":request.getParameter("rePpassword")%>" id="rePassword" name="rePassword" placeholder="请输入确认密码" />
        </div>
        <span class="errMess" id="rePasswordErrMess">密码两次输入不一致</span>
      </div>
      <div class="form-item">
        <div>
          <label>用户邮箱:</label>
          <input type="text" value="<%=request.getParameter("email")==null?"":request.getParameter("email")%>" id="email" name="email" placeholder="请输入邮箱" />
        </div>
        <span class="errMess" id="emailErrMess">请输入正确的邮箱格式</span>
      </div>
      <div class="form-item">
        <div>
          <label>验证码:</label>
          <div class="verify">
            <input type="text" id="verify" placeholder="" />
            <img src="static/img/code.bmp" alt="" />
          </div>
        </div>
        <span class="errMess" id="verifyErrMess">请输入正确的验证码</span>
      </div>
      <button class="btn" id="register">注册</button>
    </form>
    
  • 创建UserServlet来处理登录注册请求
    package com.bookstore.servlet;
    
    import com.bookstore.bean.User;
    import com.bookstore.service.UserServices;
    import com.bookstore.service.impl.UserservicesImpl;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    import java.io.IOException;
    
    @WebServlet(name = "UserServlet", value = "/UserServlet")
    public class UserServlet extends HttpServlet {
        private UserServices userservices = new UserservicesImpl();
    
        /**
         * 处理用户登录请求
         * @param request
         * @param response
         * @throws ServletException
         * @throws IOException
         */
        protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //获取用户名,密码
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            // 检查用户名密码是否正确
            User userOld = new User();
            userOld.setUsername(username);
            userOld.setPassword(password);
            User loginUser = userservices.login(userOld);
            if (loginUser != null) {
                // 用户名密码正确
                response.sendRedirect("/bookStore2/pages/user/login_success.jsp");
            } else {
                // 用户名密码不正确
                request.setAttribute("msg","用户名或密码错误,请重新输入"); // 将提示内容写入request域中
                request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
            }
        }
    
        /**
         * 处理用户注册请求
         * @param request
         * @param response
         * @throws ServletException
         * @throws IOException
         */
        protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String email = request.getParameter("email");
            User user = new User(null,username,password,email);
            UserservicesImpl userservices = new UserservicesImpl();
            boolean registFag = userservices.regist(user);
            if (registFag){
                response.sendRedirect("/bookStore2/pages/user/regist_success.jsp");
            }else {
                request.setAttribute("msg","用户名已存在");
                request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
            }
        }
    
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String method = request.getParameter("method");
            if (method.equals("login")){
                login(request,response);
            }else if (method.equals("register")){
                login(request,response);
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request,response);
        }
    }
    

4.2 使用反射取代if/else

  • 一中实现了多个请求对应一个Servlet的需求,但是我们在UserServlet中每添加一个方法就要在doGet方法中添加一个 else if语句!而且我们发现我们获取的请求参数的值正好是UserServlet中的方法名,那么我们能不能通过请求参数动态的调用对应的方法呢?
  • 通过反射的形式动态获取方法对象,这样我们再添加新的方法时就不需要再写if else语句了,但是新添加的方法的格式仍需要与doGet或者doPost的格式一致。

修改UserServlet来使用反射处理登录注册请求:

package com.bookstore.servlet;

import com.bookstore.bean.User;
import com.bookstore.service.UserServices;
import com.bookstore.service.impl.UserservicesImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends HttpServlet {
    private UserServices userservices = new UserservicesImpl();

    /**
     * 处理用户登录请求
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取用户名,密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 检查用户名密码是否正确
        User userOld = new User();
        userOld.setUsername(username);
        userOld.setPassword(password);
        User loginUser = userservices.login(userOld);
        if (loginUser != null) {
            // 用户名密码正确
            response.sendRedirect("/bookStore2/pages/user/login_success.jsp");
        } else {
            // 用户名密码不正确
            request.setAttribute("msg","用户名或密码错误,请重新输入"); // 将提示内容写入request域中
            request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
        }
    }

    /**
     * 处理用户注册请求
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        User user = new User(null,username,password,email);
        UserservicesImpl userservices = new UserservicesImpl();
        boolean registFag = userservices.regist(user);
        if (registFag){
            response.sendRedirect("/bookStore2/pages/user/regist_success.jsp");
        }else {
            request.setAttribute("msg","用户名已存在");
            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 获取请求的method参数值
            String method = request.getParameter("method");
            // 根据参数名获取方法对象
            Method declaredMethod = this.getClass().getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            declaredMethod.setAccessible(true);
            // 调用方法
            declaredMethod.invoke(this, request, response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}

4.3 提取公共的Servlet

  • 二中我们实现了动态调用对应方法的需求,但是以后每次创建Servlet的时候都需要将以上代码重写一遍,那么我们为何不把以上代码单独放到一个Servlet中,我们给它命名为BaseServlet,以后再创建Servlet时直接让它继承BaseServlet即可。
  • 创建一个专门用来被其他Servlet继承的BaseServlet
  • 但是不可以重写BaseServlet中的doGet和doPost方法

创建一个BaseServlet用来提供公共的doGet()doPost()方法:

package com.bookstore.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 公共的BaseServlet
 */
//@WebServlet(name = "BaseServlet", value = "/BaseServlet") // 该Servlet不需要注册url
public class BaseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 获取请求的method参数值
            String method = request.getParameter("method");
            // 根据参数名获取方法对象
            Method declaredMethod = this.getClass().getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            declaredMethod.setAccessible(true);
            // 调用方法
            declaredMethod.invoke(this, request, response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}

在UserServlet中集成BaseServlet即可,不需要再重新doGet()doPost()方法:

package com.bookstore.servlet;

import com.bookstore.bean.User;
import com.bookstore.service.UserServices;
import com.bookstore.service.impl.UserservicesImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends BaseServlet {
    private UserServices userservices = new UserservicesImpl();

    /**
     * 处理用户登录请求
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取用户名,密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 检查用户名密码是否正确
        User userOld = new User();
        userOld.setUsername(username);
        userOld.setPassword(password);
        User loginUser = userservices.login(userOld);
        if (loginUser != null) {
            // 用户名密码正确
            response.sendRedirect("/bookStore2/pages/user/login_success.jsp");
        } else {
            // 用户名密码不正确
            request.setAttribute("msg","用户名或密码错误,请重新输入"); // 将提示内容写入request域中
            request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
        }
    }

    /**
     * 处理用户注册请求
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        User user = new User(null,username,password,email);
        UserservicesImpl userservices = new UserservicesImpl();
        boolean registFag = userservices.regist(user);
        if (registFag){
            response.sendRedirect("/bookStore2/pages/user/regist_success.jsp");
        }else {
            request.setAttribute("msg","用户名已存在");
            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值