JavaWeb简单的登录及互动功能-javaweb实现简单的登录功能.md

焦虑烧麦 151 2022-05-02

------->web.xml<--------->servlet类

在servlet中要如何获取jsp中提交过来的表单信息呢?

request.getParameter("userName");//userName是表单中,input标签中name属性的值,接收到的是string类型

登录页面如何在登录失败的时候给出提示信息呢?

实现思路是如果登录失败,则往request域对象中存入登录失败的提示信息,然后通过请求的转发的方式跳转回登录页面并显示,所以登录界面要嵌入一段脚本代码,用来判断当前是否有登录失败提示信息的对象,如果有则将该对象保存的信息打印出来,如果没有则什么都不显示。

request.getAttribute()和request.getParameter()区别是?

前者获取的是一个object对象,后者获取的是一个string字符串,所以前者使用的时候可能会碰到需要做一些类型转换的情况。

表单访问路径填写问题

在ation属性,或者请求的转发,重定向,一般采用绝对路径,可以避免路径访问出错,访问资源不存在等问题。
jsp表达式:<%=request.getContextPath()%>或者用EL表达式:$
可以获取当前web应用根目录路径。

代码:

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>登录界面</title>

  <style type="text/css">
    body{ background-color:#d0e4fe; }
    *{margin: 0;padding: 0;}
    form{margin: 0 auto;padding:15px; width: 300px;height:300px;text-align: center;}
    #submit{padding: 15px}
    #submit input{width: 50px;height: 24px;}
  </style>

</head>

<body>
<!-- login -->
<div class="wrapper">
  <div align="center">用户名:Liu 密码:123</div>

  <form action="<%=request.getContextPath()%>/login" method="post">
    <label>用户名:</label>
    <input type="text" name="userName" value="${param.userName}"/><br><br>
    <label>密&nbsp码:</label>
    <input type="password" name="password"/><br>

    <font color="red">
      <%
        if(request.getAttribute("message")!= null){
          out.print(request.getAttribute("message"));
        }
      %>
    </font>

    <div id="submit">
      <input type="submit" value="登录"/>
    </div>

  </form>
</div>
</body>
</html>

loginSuccess.jsp

记得导入jQuery-3.5.1; 跟.jsp文件同一目录下

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>登录成功</title>

    <script src="jquery-3.5.1.js"></script>

    <script>
        $(function() {
            //toRight
            $("#toRight").click(function() {
                //获取右边的下拉列表对象,append(左边下拉列表选中的option)
                $("#rightName").append($("#leftName > option:selected"));
            });
        });
    </script>
    <style>
        #leftName, #btn, #rightName {
            width: 100px;
            height: 150px;
        }
        #toRight {
            margin-top: 100px;
            margin-left: 30px;
            width: 50px;
        }
        .border {
            height: 400px;
            padding: 100px;
        }
    </style>


</head>
<body>
Hello:<br>
<font color="green" size="22">
    <%
        out.print(request.getParameter("userName")+"<br>");
    %>
</font>
<a href="<%=request.getContextPath()%>/index.jsp">点击这里重新登录</a>

</div>

<div>
    <form action="${pageContext.request.contextPath}/HeroSelect" method="post" >
        <div class="border">
            英雄:
            <select id="leftName" multiple="multiple">
                <option value="葫芦娃">葫芦娃</option>
                <option value="一只耳">一只耳</option>
                <option value="美国队长">美国队长</option>
                <option value="黑猫警长">黑猫警长</option>
                <option value="唐老鸭的情妇">唐老鸭的情妇</option>
            </select>
            </select> <input type="button" id="toRight" value="-->"> 败类:

            <select id="rightName" name="bailei" multiple="multiple">

            </select>
            <br/>
            <input type="submit" value="提交">
        </div>
    </form>
</div>

</body>
</html>

LoginServlet.java

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

public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        System.err.println(userName+";"+password);
        String myUser = "Liu";
        String myPwd = "123";
        if(userName.equals(myUser)&&password.equals(myPwd)) {
            request.getSession().setAttribute("username",userName);
            response.sendRedirect(request.getContextPath()+"/loginSuccess.jsp?userName="+userName);
        }else {
            request.setAttribute("message", "账密错误,请重新登录<br>");
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }

    }
}

AfterSelect.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<html>
<head>
    <title>选择结果</title>
</head>
<body>

欢迎:<br>
<font color="green" size="22">

    <%
        String UserName = (String)request.getAttribute("UserName");
        out.print("Liu");
    %>
</font>
<br>

发现了混入革命队伍的败类:<br>
<%
    String [] s1 = (String [])request.getAttribute("s");
    for (String s : s1) {
        out.print(s + "<br>");
    }
%>

<a href="<%=request.getContextPath()%>/index.jsp">点击这里重新登录</a>

</body>
</html>

HeroSelect.java

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 javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/HeroSelect")
public class HeroSelect extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        //获取选择败类的String数组
        String[] bailei = request.getParameterValues("bailei");

        HttpSession session=request.getSession();
        String username = (String)session.getAttribute("userName");
        System.out.println(username);

        request.setAttribute("userName",username);
        request.setAttribute("s" , bailei);
        request.getRequestDispatcher("AfterSelect.jsp").forward(request , response);
    }

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

最后配置一下.xml文件

20201215_114246.jpg