jsp------实现MD5加密

摘要:
=null){loginFlag=md5Account.equals;}如果{//request.getRequestDispatcher.forward;//response.sendRedirect;%˃欢迎回来,欢迎登录以注销用户登录˂formaction=“foreverlogin?

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<%@page import="java.net.*" %>
<%@page import="comm.MakeMD5" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>MyIndex</title>
<meta http-equiv="imurl" content="no-cache">
</head>

<body>
    <%
        boolean loginFlag=false;
        String account=null;
        String md5Account=null;
        Cookie cookieArr[]=request.getCookies();
        if(cookieArr!=null&&cookieArr.length>0){
            for(Cookie cookie:cookieArr){
                if(cookie.getName().equals("account")){
                    account=cookie.getValue();
                    account=URLDecoder.decode(account,"utf-8");
                    //System.out.print(account);
                }
                if(cookie.getName().equals("md5Account")){
                    md5Account=cookie.getValue();
                    md5Account=URLDecoder.decode(md5Account,"utf-8");
                    //System.out.print(md5Account);
                }
            }
        }
        
        if(account!=null&&md5Account!=null){
            loginFlag=md5Account.equals(MakeMD5.getMD5(account));
        }
        
        if(loginFlag){
            //request.getRequestDispatcher("successlogin.jsp").forward(request, response);
            //response.sendRedirect("successlogin.jsp");
    %>
        <fieldset>
            <legend>欢迎您回来</legend>
            <table align="center">
                <tr>
                    <td><%=account %>,欢迎您登陆本网站</td>
                    <td align="center">
                        <a href="foreverlogin?action=logout">注销登陆</a>
                    </td>
                </tr>
            </table>
        </fieldset>
    <%
        }else{
    %>
        <fieldset>
            <legend>用户登录</legend>
            <form action="foreverlogin?action=login" method="post">
                <table>
                    <tr>
                        <td>&nbsp;&nbsp;号:</td>
                        <td><input type="text" name="account"></td>
                    </tr>
                    <tr>
                        <td>&nbsp;&nbsp;码:</td>
                        <td><input type="text" name="password"></td>
                    </tr>
                    <tr>
                        <td>有效期:</td>
                        <td>
                            <input type="radio" name="timeout" value="-1" checked="checked">
                            关闭浏览器即失效
                            <input type="radio" name="timeout" value="<%=30*24*60*60%>">
                            30天内有效
                            <input type="radio" name="timeout" value="<%=Integer.MAX_VALUE%>">
                            永久有效
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <input type="submit" value="登陆">&nbsp;
                            <input type="reset" value="重置">
                        </td>
                    </tr>
                </table>
            </form>
        </fieldset>
    <%
        }
     %>
</body>
</html>

src/comm/foreverlogin.java

package comm;

import java.io.IOException;
import java.net.URLEncoder;

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

public class foreverlogin extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    public foreverlogin() {
        super();
    }

    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request,response);
    }

    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        
        String action=request.getParameter("action");
        if(action.equals("login")){
            login(request,response);
        }
        else if(action.equals("logout")){
            logout(request,response);
        }
    }
    
    //login
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
        String account=request.getParameter("account");
        //String password=request.getParameter("password");
        int timeout=Integer.parseInt(request.getParameter("timeout"));
        
        String md5Account=MakeMD5.getMD5(account);  //采用MD5算法加密
        account=URLEncoder.encode(account,"utf-8"); //账号为中文时需要转换Unicode才能保存在Cookie中
        Cookie accountCookie=new Cookie("account",account);
        accountCookie.setMaxAge(timeout);
        Cookie md5AccountCookie=new Cookie("md5Account",md5Account);
        md5AccountCookie.setMaxAge(timeout);
        response.addCookie(accountCookie);
        response.addCookie(md5AccountCookie);
        
        //将线程休眠1秒后在执行
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        //response.sendRedirect("cookie/resultlogin.jsp?"+System.currentTimeMillis());
        response.sendRedirect("cookie/index.jsp?"+System.currentTimeMillis());
    }
    
    //logout
    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
        Cookie accountCookie=new Cookie("account","");
        accountCookie.setMaxAge(0);
        Cookie md5AccountCookie=new Cookie("md5Account","");
        md5AccountCookie.setMaxAge(0);
        response.addCookie(accountCookie);
        response.addCookie(md5AccountCookie);
        
        //将线程休眠一秒后在执行
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        response.sendRedirect("cookie/index.jsp?"+System.currentTimeMillis());
    }

    
    public void init() throws ServletException {
        // Put your code here
    }

}

src/comm/MakeMD5.java

package comm;

import java.security.MessageDigest;

public class MakeMD5 {
    public final static String getMD5(String str){
        // 用来将字节转换成 16 进制表示的字符
        char hexDiagiArr[]={'0','1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f'};
        MessageDigest digest=null;
        try{
            digest=MessageDigest.getInstance("MD5");     //创建MD5算法摘要
            digest.update(str.getBytes());                 //更新摘要
            byte mdBytes[]=digest.digest();                 //加密,并返回字节数组
            //新建字符数组,长度为myBytes字节数组的2倍,用于保存加密后的值
            char newCArr[]=new char[mdBytes.length*2];
            int k=0;
            for(int i=0;i<mdBytes.length;i++){
                byte byte0=mdBytes[i];
                newCArr[k++]=hexDiagiArr[byte0>>>4&0x0f]; //取字节中高 4 位的数字转换,>>>为逻辑右移,将符号位一起右移
                newCArr[k++]=hexDiagiArr[byte0&0x0f];     //取字节中低 4 位的数字转换
                //针对字符0-9的,0-9的ascii码值为0x30,0x31,0x32 0x33 ...0x39,
                //因此与0x0f按位与后只保留个位上的书即0x0,0x1,。。。0x9
                //  0000 1010
                //& 0000 1111
                //  0000 1010
            }
            return String.valueOf(newCArr);   //将转换后的字符转换为字符串
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

免责声明:文章转载自《jsp------实现MD5加密》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇C#在窗体间的数据交互的经验总结Java大文件分片上传/多线程上传组件下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

[转]从minio中读取文件流进行下载文件

本文转自:https://blog.csdn.net/ZHANGLIZENG/article/details/82892678 一、获取Minio连接public static String minioUrl; public static String minioUsername;public static String minioPassword;@Va...

springboot项目中集成ip2region遇到的问题及终极解决办法

1、问题回顾 按照ip2region项目的官方集成到springboot项目后,运行测试一切都ok,没有任何问题。但是当项目打成可执行的jar包后再运行,却显示找不到ip2region.db,无法找到资源文件的错误。异常代码如下: java.io.FileNotFoundException: class path resource [ip2region/i...

Java泛型讲解

1. 概述在引入泛型之前,Java类型分为原始类型、复杂类型,其中复杂类型分为数组和类。引入范型后,一个复杂类型就可以在细分成更多的类型。例如原先的类型List,现在在细分成List<Object>, List<String>等更多的类型。注意,现在List<Object>, List<String>是两种不...

HBase性能优化方法总结

4.1 HBase性能优化方法总结(一):表的设计 4.1.1 Pre-Creating Regions 默认情况下,在创建HBase表的时候会自动创建一个region分区,当导入数据的时候,所有的HBase客户端都向这一个region写数据,直到这个region足够大了才进行切分。一种可以加快批量写入速度的方法是通过预先创建一些空的regions,这样...

JSON反序列化接口的问题

今天在使用JSON序列化类时出现问题,原来类中有一个接口,在反序列化时不知道接口的实体是什么 public class Device : IComparer { private string _deviceid; private string _devicename; private string _deviceaddr = "01"; private s...

Eclipse 开发 jsp

下载 eclipse EE 注意 是eclipse EE 版本 下载 apache-tomcat-8.0.15 只下载上面二个 从Window -> Preferences -> Server -> Runtime Environment,然后 Add -> 选您的Tomcat版本 -> Next -> Browse -...