JavaWeb学习笔记——开发动态WEB资源(五)servlet身份验证

本工程的功能是实现Javaweb的servlet身份验证

一下是login.html文件中的代码

<!DOCTYPE html>
<html>
  <head>
    <title>login.html</title>
    
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=GBK">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

    <script type="text/javascript">
        function check(){
            //获取控件内容
            var loginname = document.getElementById("loginname").value;
            if(loginname == ""){
                alert("用户名不能为空");
                document.getElementById("loginname").focus();//获取焦点
                return false;
            }
            
            var password = document.getElementById("password").value;
            if(password == ""){
                alert("密码不能为空");
                document.getElementById("password").focus();
                return false;
            }  
            
            //验证成功
            document.loginform.submit();
        }
    </script>

  </head>
  
  <body>
    <center>
        <h2>登陆页面</h2>
        <br>
        <!-- html数据由两种传输方式 1.get 从地址栏传递 2.form表单传输 
            form代表表单
                --action属性代表提交的url
                    action="login.do",那么在web.xml里面定义<servlet-mapping>的<url-pattern>
                    的时候也是login.do
                --method属性代表提交表单的方式,http里面重点是get和post,默认get方式提交
                --name属性给表单其名字
                --id属性代表唯一标示该表单的名字,主要是javascript脚本使用
        -->
        <form action="login.do" method="get" name="loginform" id="loginform">
            <table>
                <tr>
                    <td>登录名:</td>
                    <td><input type="text" name="loginname" id="loginname"/></td>
                </tr>
                <tr>
                    <td>密码:</td>
                    <td><input type="password" name="password" id="password"/></td>
                </tr>
            </table>
            <table>
                <tr>
                    <td><input type="button" value="提交" onclick="check();"></td>
                    &nbsp;&nbsp;
                    <td><input type="reset" value="重置"></td>
                </tr>
            </table>
        </form>
        
    </center>
  </body>
</html>

以下代码是LoginServlet.java中的代码

package org.common.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public LoginServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        System.out.println("执行 doGet 方法...");
//        //1.接收前台传递过来的参数
//        Enumeration enums = request.getParameterNames();
//        while(enums.hasMoreElements()){
//            System.out.println(enums.nextElement());
//            
//        }
        
        //转换编码的第2种方式,配合doPost()方法使用
        request.setCharacterEncoding("GBK");
        
        //提交的name可以在后台使用request.getParameter("loginname")获取值
        String loginname = request.getParameter("loginname");
        System.out.println("转换前loginname:" + loginname);
        //String password = request.getParameter("password");
        
        //把loginname这个字符串转成GBK,前提你要确定编码
        loginname = new String(loginname.getBytes("iso-8859-1"),"GBK");
        System.out.println("转换后loginname:" + loginname);
        String password = request.getParameter("password");
        
        //properties文件是java的默认配置文件,以key-value的形式存储数据
        //增加了一个user.properties文件存储用户名密码
        Properties pro = new Properties();
        //load方法从输入流中读取属性列表(键和元素对)
        pro.load(this.getClass().getResourceAsStream("/user.properties"));
        //System.out.print(pro);
        
        response.setContentType("text/html;charset=GBK");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        
        //out.print(" loginname: " + loginname);
        //out.print(" password: " + password);
        if(loginname.equals(pro.getProperty("loginname")) 
                && password.equals(pro.getProperty("password"))){
            out.println(" 欢迎["+pro.getProperty("username")+"]登陆");
        }else{
            out.println("用户名密码错误");
        }
        
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doGet(request, response);
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

doGet()方法不安全,所以尽量使用doPost()方法

原文地址:https://www.cnblogs.com/tonglin0325/p/4621068.html