菜单

JSP+Servlet+JavaBean实现登录网页实例详解

2020年1月29日 - 金沙国际唯一官网
JSP+Servlet+JavaBean实现登录网页实例详解

本文实例讲述了Java Web实现的基本MVC。分享给大家供大家参考。具体如下:

本文实例讲述了JSP+Servlet+JavaBean实现登录网页的方法。分享给大家供大家参考。具体如下:

目录

style=”font-size: 16px;”>1 问题描述

style=”font-size: 18pt;”>2 解决方案

2.1  style=”font-family: 宋体;”>预期效果

2.2  style=”font-family: 宋体;”>系统结构示意图

2.3  style=”font-family: 宋体;”>具体编码

login.jsp——视图部分的输入文件
success.jsp——视图部分的输出文件
failure.jsp——视图部分的输出文件
LoginBean.java——模型部分
LoginServlet.java——控制器部分
web.xml——web应用的配置文件

这里涉及到四个文件:

 

下面分别介绍:

  1. 登录页面:login.html
  2. 登录成功欢迎页面:login_success.jsp
  3. 登录失败页面:login_failure.jsp
  4. Servlet处理文件:LoginServlet.java

 

1、login.jsp

其实还涉及到一个文件:web.xml,这个后面再说:


该功能的输入文件,用户首先访问这个文件。主要用于输入用户名和口令。
代码如下:

下面分别介绍这几个文件:

1 问题描述

利用Java EE相关技术实现一个简单的Web聊天室系统,具体要求如下。

(1)编写一个登录页面,登录信息中有用户名和密码,分别用两个按钮来提交和重置登录信息。

(2)编写一个Servlet程序Main.java通过请求指派来处理用户提交的登录信息,如果用户名为本小组成员的名字且密码为对应的学号时,跳转到LoginSuccess显示聊天界面(类似于QQ群聊天界面,可使用HTML中的frameset标签生成两个窗口,一个用来实现用户信息输入,另一个显示所有用户聊天记录的);否则跳转到LoginFail页面,提示用户重新登录(注:此页面要包含前面的登录界面)。

(3)编写两个Servlet程序,分别用来显示“信息输入”窗口和“聊天记录显示”窗口的内容;用户在“信息输入”窗口中键入聊天内容,点击“发送”按钮后,在“聊天记录显示”窗口中显示发送消息的用户名称和聊天内容。提示:利用HTML中的textarea标签来实现。

(4)在登录界面上实现记住用户名和密码的功能,使得当用户选择了此功能并成功登录后,在其下次登录时可以不用再输入用户名和密码即可登录。提示:此功能可通过两个Cookie来实现。

以下功能选做:

(5)编写一个Listener程序来监听会话的创建和销毁事件,以此统计当前在线(登录)人数,并将其显示在聊天界面上。

(6)添加一个Filter对本系统所有的Servlet程序进行过滤,该Filter实现对请求和响应对象的编码格式的设置(实现此功能后,Servlet可以直接从请求对象中获取参数信息而无需实现对请求进行格式的编码)。在【GlassFish Server】视图中输出程序在Filter和其它资源之间的执行顺序。

 

 


<%@ page contentType="text/html;charset=gb2312"%>
<script language="JavaScript">
 function isValidate(form)
 {
   // 得到用户输入的信息
   username = form.username.value;
   userpass = form.userpass.value;
   // 判断用户名长度
   if(!minLength(username,6))
   {
     alert("用户名长度小于6位!");
     form.username.focus();
     return false;
   }
   if(!maxLength(username,8))
   {
     alert("用户名长度大于8位!");
     form.username.focus();
     return false;
   }
   // 判断口令长度
  if(!minLength(userpass,6))
   {
     alert("口令长度小于6位!");
     form.userpass.focus();
     return false;
   }
   if(!maxLength(userpass,8))
   {
     alert("口令长度大于8位!");
     form.userpass.focus();
     return false;
   }
   return true;
 }
 // 验证是否满足最小长度
 function minLength(str,length)
 {
   if(str.length>=length)
     return true;
   else
     return false;
 }
 // 判断是否满足最大长度
 function maxLength(str,length)
 {
   if(str.length<=length)
     return true;
   else
     return false;
 }
</script>
<html>
 <head>
  <title>用户登陆</title>
 </head>
 <body>
  <h2>用户登录</h2>
  <form name="form1" action="login" method="post"
    onsubmit="return isValidate(form1)">
    用户名:<input type="text" name="username"> <br>
    口令:<input type="password" name="userpass"><br>
    <input type="reset" value="重置">
    <input type="submit" value="提交"><br>
  </form>
 </body>
</html>
  1. 登录页面:login.html

2 解决方案                                               

代码中提供了客户端验证功能(用户名和口令的长度为6-8位)。验证通过之后会把请求提交给控制器Servlet。

  登录

2.1 预期效果                    

 图片 1

图一:网上聊天系统运行示意图

 

2、success.jsp

用户登录

用户名:
密码:
     
<>

  1. 登录成功欢迎页面:login_success.jsp
 My JSP 'login_failure.jsp' starting page












  欢迎您,登录成功!
 <>
  1. 登录失败页面:login_failure.jsp
 My JSP 'login_failure.jsp' starting page












  对不起,登录失败!
 <>
  1. Servlet处理文件:LoginServlet.java

    /**

    • 该JSP程序是用来测试与MySQL数据库的连接,
    • 需要一个数据库:LearnJSP,和其中一个表:userinfo
    • 表中有两个字段分别为:UserName varchar (20) not null,UserPwd varchar (20) not null
      /
      package zieckey.login.servlet;
      import java.sql.Statement;
      import java.io.IOException;
      import java.sql.DriverManager;
      import java.sql.ResultSet;
      import java.sql.SQLException;
      import javax.servlet.Servlet;
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      public class LoginServlet extends HttpServlet implements Servlet
      {
      public LoginServlet ()
      {
      // TODO Auto-generated constructor stub
      }
      /
    • (non-Javadoc)
      *
    • @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
    • javax.servlet.http.HttpServletResponse)
      /
      @Override
      protected void doGet ( HttpServletRequest arg0, HttpServletResponse arg1 )
      throws ServletException, IOException
      {
      }
      /
    • (non-Javadoc)
      *
    • @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
    • javax.servlet.http.HttpServletResponse)
      /
      @Override
      protected void doPost ( HttpServletRequest request, HttpServletResponse response )
      throws ServletException, IOException
      {
      response.setContentType ( “text/html” );
      String result = “”;
      // 获取用户名
      String sUserName = request.getParameter ( “txtUserName” );
      if ( sUserName == “” || sUserName == null || sUserName.length ( ) > 20 )
      {
      try
      {
      result = “请输入用户名(不超过20字符)!”;
      request.setAttribute ( “ErrorUserName”, result );
      response.sendRedirect ( “login.html” );
      } catch ( Exception e )
      {
      }
      }
      // 获取密码
      String sPasswd = request.getParameter ( “txtPassword” );
      if ( sPasswd == “” || sPasswd == null || sPasswd.length ( ) > 20 )
      {
      try
      {
      result = “请输入密码(不超过20字符)!”;
      request.setAttribute ( “ErrorPassword”, result );
      response.sendRedirect ( “login.html” );
      } catch ( Exception e )
      {
      }
      }
      // 登记JDBC驱动程序
      try
      {
      Class.forName ( “org.gjt.mm.mysql.Driver” ).newInstance ( );
      } catch ( InstantiationException e )
      {
      // TODO Auto-generated catch block
      e.printStackTrace ( );
      System.out.println (“InstantiationException”);
      } catch ( IllegalAccessException e )
      {
      // TODO Auto-generated catch block
      e.printStackTrace ( );
      System.out.println (“IllegalAccessException”);
      } catch ( ClassNotFoundException e )
      {
      // TODO Auto-generated catch block
      e.printStackTrace ( );
      System.out.println (“ClassNotFoundException”);
      }
      // 连接参数与Access不同
      String url = “jdbc:mysql://localhost/LearnJSP”;
      // 建立连接
      java.sql.Connection connection = null;
      Statement stmt = null;
      ResultSet rs = null;
      try
      {
      connection = DriverManager.getConnection ( url, “root”, “011124” );
      stmt = connection.createStatement ( );
      // SQL语句
      String sql = “select
      from userinfo where username='” + sUserName

      • “‘ and userpwd = ‘” + sPasswd + “‘”;
        rs = stmt.executeQuery ( sql );// 返回查询结果
        } catch ( SQLException e )
        {
        // TODO Auto-generated catch block
        e.printStackTrace ( );
        }
        try
        {
        if ( rs.next ( ) )// 如果记录集非空,表明有匹配的用户名和密码,登陆成功
        {
        // 登录成功后将sUserName设置为session变量的UserName
        // 这样在后面就可以通过 session.getAttribute(“UserName”) 来获取用户名,
        // 同时这样还可以作为用户登录与否的判断依据
        request.getSession ( ).setAttribute ( “UserName”, sUserName );
        response.sendRedirect ( “login_success.jsp” );
        } else
        {
        // 否则登录失败
        //response.sendRedirect ( “MyJsp.jsp” );
        response.sendRedirect ( “login_failure.jsp” );
        }
        } catch ( SQLException e )
        {
        // TODO Auto-generated catch block
        e.printStackTrace ( );
        }
        try
        {
        if ( null!=rs )
        {
        rs.close ( );
        }
        if ( null!=stmt )
        {
        stmt.close ( );
        }
        if ( null!=connection )
        {
        connection.close ( );
        }
        } catch ( SQLException e )
        {
        // TODO Auto-generated catch block
        e.printStackTrace ( );
        }
        }
        /*
        */
        private static final long serialVersionUID = 1L;
        }

为了让这个网站正常运行还要到web.xml中注册一下,
现该文件内容修改如下:

  LoginServlet
  LoginServlet
  zieckey.login.servlet.LoginServlet


  LoginServlet
  /LoginServlet

好了,这几个文件就可以构成我们的这个登录界面了.

注意事项:

  1. 文件目录形式

login.html,login_success.html,login_failure.html这三个文件放在同一目录,
LoginServlet.java该文件的字节码文件LoginServlet.class放在WEB-INF/classes目录下(注意jar包顺序)
现在整个工程的目录形式是:
M:/Tomcat5.5/webapps/JSP_Servlet_JavaBean_Login 的目录
007-01-18  15:16   

          META-INF
007-01-18  15:16   

          WEB-INF
007-01-18  16:17             1,801 login.html
007-01-18  15:48               858 login_failure.jsp
007-01-18  15:40               234 login_success.html
007-01-18  15:46               781 MyJsp.jsp
007-01-18  16:12               859 login_success.jsp
M:/Tomcat5.5/webapps/JSP_Servlet_JavaBean_Login/WEB-INF 的目录
007-01-18  15:16   

          classes
007-01-18  15:16   

          lib
007-01-18  16:21               606 web.xml
M:/Tomcat5.5/webapps/JSP_Servlet_JavaBean_Login/WEB-INF/classes/zieckey/login/servlet
的目录
2007-01-18  16:18             3,900 LoginServlet.class

  1. 其他注意事项

数据库MySQL服务器程序要先启动起来.

希望本文所述对大家的JSP程序设计有所帮助。

2.2 系统结构示意图                  

 图片 2

图二:系统结构示意图

具体解释:

(1)打开浏览器,进入网上聊天系统首页登录界面login.jsp。输入用户名和密码,点击登陆;

(2)Main.java类获取login.jsp用户输入的用户名和密码,进行逻辑验证,验证成功则跳转到聊天界面welcome.jsp,否则跳转到登陆失败提示界面loginFail.jsp;

(3)Welcome.jsp聊天界面,其中头部界面显示当前登陆用户昵称和当前在线总人数(统计当前在线人数通过调用OnlineListener类来实现);左部为聊天好友列表界面,此处仅作展示页面,未写具体逻辑处理代码;中间主体页面main.jsp页面实现用户在聊天输入框中输入消息,发送并显示在聊天消息显示框中功能。(实现聊天功能通过调用InputInformation.java类来实现)具体页面如下图所示:

图片 3

图三:聊天页面welcome.jsp

图三:welcome.jsp实际运行图

登录成功之后会跳转到这个界面,界面的代码如下:

2.3 具体编码                    

(1)Main.java(Servlet类)通过请求指派来处理login.jsp页面用户提交的登录信息(并使用Cookie实现记住用户登录用户名和密码功能),成功则跳转到welcome.jsp,失败则跳转到loginFail.jsp。具体实现如下:

网上聊天系统登陆首页login.jsp页面代码:

style=”color: #ff0000;”>注意:此处代码有点问题,感谢文末园友指正,具体如下:

login.jsp页面代码:Cookie[] cookies
= request.getCookies();
开启服务第一次登录时是没有cookie的,所以执行 for (int i = 0; i <
cookies.length; i++)
时会出现空指针异常。在for循环前加个if判断:if(cookies!=null)才能成功运行

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

String username = "";
String password = "";
//String[] checkBox = request.getParameterValues("save_password");
//获取当前站点的所有Cookie
 Cookie[] cookies = request.getCookies();

 for (int i = 0; i < cookies.length; i++) {
          //对cookies中的数据进行遍历,找到用户名、密码的数据
         if ("username".equals(cookies[i].getName())) {
          //读取时URLDecoder.decode进行解码(PS:Cookie存取时用URLEncoder.encode进行编码)
             username = java.net.URLDecoder.decode(cookies[i].getValue(),"UTF-8");
         } else if ("password".equals(cookies[i].getName())) {
             password =  java.net.URLDecoder.decode(cookies[i].getValue(),"UTF-8");
         }
  }
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>网上聊天室登陆页面</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <style type="text/css">
        *
        {
            margin: 0;
            padding: 0;
        }
        body
        {

            font-size: 0px;
            padding: 200px;


        }

    </style>
  </head>
 <body>
 <form action="Main" method="post">
 <div style="background:#49AFFF;font-size: 80px;text-align:center;">网上聊天室</div>
<div style="background:#75FFE7;font-size: 35px;text-align:center;">
用户名:<input type="text" name="username" value="<%=username%>" style="border:1px solid #ccc; width:400px; height:40px;" ></div>
<div style="background:#75FFE7;font-size: 35px;text-align:center;">
密    码 :<input type="password" name="password" value="<%=password%>" style="border:1px solid #ccc; width:400px; height:40px;" ></div>
<div style="background:#75FFE7;font-size: 25px;text-align:center;">
<input type="checkbox" value="save" name="save_password">记住密码
<input type="submit" value="登陆" name="login" style="width: 100px; height: 40px;font-size: 30px;">
<input type="reset" value="重置" name="reset" style="width: 100px; height: 40px;font-size: 30px;"></div>
</form>
</body>
</html>

Main.java类代码:

package com.liuzhen.chart;

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;


@SuppressWarnings("serial")
public class Main extends HttpServlet {

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

    /**
     * Destruction of the servlet. <br>
     */
    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 {

        //response.setContentType("text/html;charset=utf-8"); 
        //此出注解是因为使用CodeFilter类过滤所有Servlet,转换编码
        //request.setCharacterEncoding("utf-8");
        String userName = request.getParameter("username");
        String passWord = request.getParameter("password");
        String checkBox = request.getParameter("save_password");

        System.out.println("userName:"+userName+"n"+"passWord:"+passWord);
        request.getSession().setAttribute("nameSession", userName);   //将用户名存入session中
        String[] name_one = {"柳真","刘仁杰","吴超","张浩东","陈初相"};
        String[] pwd_one = {"201421092073","201421092068","201421092077","201421092082","201421092119"};
        String name_two = "";
        String pwd_two = "";
        boolean login_test = false;
        for(int i=0;i<5;i++){
            name_two = name_one[i];
            pwd_two = pwd_one[i];
            if(userName.equals(name_two) && passWord.equals(pwd_two))
                login_test = true;                           
        }

        if(login_test) {
            if ("save".equals(checkBox)) {
                //Cookie存取时用URLEncoder.encode进行编码(PS:读取时URLDecoder.decode进行解码)
                String name = URLEncoder.encode(userName,"UTF-8");
                //创建两个Cookie对象
                Cookie nameCookie = new Cookie("username", name);
                //设置Cookie的有效期为3天
                nameCookie.setMaxAge(60 * 60 * 24 * 3);
                String pwd = URLEncoder.encode(passWord,"UTF-8");
                Cookie pwdCookie = new Cookie("password", pwd);
                pwdCookie.setMaxAge(60 * 60 * 24 * 3);
                response.addCookie(nameCookie);
                response.addCookie(pwdCookie);
             }
             request.getRequestDispatcher("welcome.jsp").forward(request, response);           
        }   
        else{
             response.sendRedirect("loginFail.jsp");      
              // request.getRequestDispatcher("loginFail.jsp").forward(request, response);             
        }


    }

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

}

登陆失败页面loginFail.jsp页面代码:

图片 4图片 5

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'loginFail.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="content-type" content="text/html; charset=gb2312">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
    <br>
      <br>
           <h1>用户名和密码不匹配,请重新登陆!</h1>
           <a href="login.jsp">重新登陆</a>
  </body>
</html>

View Code

登陆成功页面welcome.jsp页面代码(此处使用frameset标签,分为头部、左部和中间主页三部分,分别对象header.jsp、left.jsp和main.jsp页面):

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>网上聊天室</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="content-type" content="text/html; charset=gb2312">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
   <frameset rows="100,*" cols="*" frameborder="no" border="0" framespacing="0">
         <frame src="header.jsp" name="topFrame" scrolling="auto" noresize="noresize" id="topFrame"/>
      <frameset cols="213,*" frameborder="no" border="0" framespacing="0">
        <frame src="left.jsp" name="leftFrame" scrolling="No" noresize="noresize" id="leftFrame"/>
        <frame src="main.jsp" name="mainFrame" scrolling="auto" id="mainFrame"/>
      </frameset>
   </frameset> 
  <body>

  </body>
</html>

聊天头部header.jsp页面代码:

图片 6图片 7

<%@ page language="java" import="java.util.*" contentType="text/html;charset=gb2312" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title></title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <meta http-equiv="Content-Type" content="text/html;charset=gb2312">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body topmargin="0" leftmargin="0" rightmargin="0">
     <form action="">
             <table  width="100%" height="79" border="0" cellpadding="0"
                     cellspacing="0" align=center>
             <tr>
                <td bgcolor="F9A859" valign="top">
                <table width="100%" height="50" border="0" align="center"
                       cellpadding="0" cellspacing="0" bgcolor="FBEAD0">
                 <tr>
                   <td align="center" style="font-size:40px;">
                     网上聊天室
                   </td>
                 </tr> 

                </table>

                </td>
             </tr>
               <tr>
                 <td bgcolor="F9A859" valign="top">
                 <table width="100%" border="0" align="center" cellpadding="0"
                         cellspacing="0">
                  <tr>
                     <td align="center" style="font-size:20px" valign="middle">
                     欢迎<%=(String)request.getSession().getAttribute("nameSession") %>访问!
                     当前在线人数为<%=application.getAttribute("peopleOnline")%>人
                     </td>
                  </tr>       

                 </table>

                 </td>
              </tr>              

             </table>
           </form>
  </body>
</html>

View Code

聊天左部left.jsp页面代码(此处为了显示美观,使用了jquery-1.4.2包):

图片 8图片 9

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'test.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="content-type" content="text/html; charset=gb2312">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
 <style type="text/css">
        *
        {
            margin: 0;
            padding: 0;
        }
        body
        {
            font-size: 15px;
            padding: 00px;
        }
        .menu
        {
            width: 500px;
            border-bottom: solid 1px gray;
        }
        .menu h3
        {
            border: solid 1px gray;
            height: 30px;
            line-height: 30px;
            padding-left: 10px;
            padding:0 5px;
            border-bottom: none;
            cursor: pointer;

        }
        .menu p
        {
            border-left: solid 1px gray;
            border-right: solid 1px gray;
            padding: 20px 0;
            padding-left: 5px;
        }
        .changecolor{background-color:red;}
    </style>
    <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
          $(function () {
            $(".menu p:not(:first)").hide();
            $(".menu h3").css("background", "#ccc");       
            $(".menu h3").hover(function () { $(this).css("background-color", "gray").siblings("h3").css
("background-color", "#ccc");});
            $(".menu h3").mouseleave(function () { 
               $(".menu h3").css("background", "#ccc");}); //离开时将其变为原来颜色
            var index = $(".menu h3").index(this);
            $(".menu h3").click(function () { $(this).next("p").slideToggle().siblings("p").slideUp(); });
        });
    </script>
  </head>

  <body>
    <div class="menu">
        <h3>
            我的好友</h3>
        <p>
   <a href="index.jsp">周杰伦</a><br/><br/>
   <a href="index.jsp">周杰伦</a><br/><br/>
   <a href="index.jsp">周杰伦</a><br/><br/>
   <a href="index.jsp">周杰伦</a><br/><br/>
   <a href="index.jsp">周杰伦</a><br/><br/>
   <a href="index.jsp">周杰伦</a><br/><br/>
   <a href="index.jsp">周杰伦</a><br/><br/>
   <a href="index.jsp">周杰伦</a><br/>
            </p>
        <h3>
            我的朋友</h3>
        <p>
   <a href="index.jsp">李连杰</a><br/><br/>
   <a href="index.jsp">李连杰</a><br/><br/>
   <a href="index.jsp">李连杰</a><br/><br/>
   <a href="index.jsp">李连杰</a><br/><br/>
   <a href="index.jsp">李连杰</a><br/><br/>
   <a href="index.jsp">李连杰</a><br/><br/>
   <a href="index.jsp">李连杰</a><br/><br/>
   <a href="index.jsp">李连杰</a><br/>
         </p>
        <h3>
            陌生人</h3>
        <p>
   <a href="index.jsp">比尔盖茨</a><br/><br/>
   <a href="index.jsp">比尔盖茨</a><br/><br/>
   <a href="index.jsp">比尔盖茨</a><br/><br/>
   <a href="index.jsp">比尔盖茨</a><br/><br/>
   <a href="index.jsp">比尔盖茨</a><br/><br/>
   <a href="index.jsp">比尔盖茨</a><br/><br/>
   <a href="index.jsp">比尔盖茨</a><br/>
          </p>
    </div>
  </body>
</html>

View Code

聊天主页main.jsp页面代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'main.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
  <form action="InputInformation" method=post>
  <textarea  cols="105" rows="25" name="show_textarea"><%=request.getAttribute("input_textarea")%></textarea>
  <br>
  <textarea  cols="105" rows="5"  name="input_textarea"></textarea><br>
  <input type="submit" value="发送" name="button_one" 
   style="width: 100px; height: 40px;font-size: 25px;"><br>
  </form>
  </body>
</html>

 

(2)InputInformation.java(Servlet类)通过请求指派获取main.jsp聊天输入框中输入信息,跳转到main.jsp页面,并在聊天记录显示框中显示聊天信息。具体实现如下:

 InputInformation.java类代码如下:

package com.liuzhen.chart;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

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

@SuppressWarnings("serial")
public class InputInformation extends HttpServlet {
    public String chat_record = "";  //定义聊天记录变量,此处为全局变量

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

    /**
     * Destruction of the servlet. <br>
     */
    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 {

        //response.setContentType("text/html;charset=utf-8"); 
        //此出注解是因为使用CodeFilter类过滤所有Servlet,转换编码
        //request.setCharacterEncoding("utf-8");
        String input_textarea = request.getParameter("input_textarea");
        Date now = new Date();    //创建日期对象,及系统当前时间
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String time = dateFormat.format( now ); //按照给定的日期格式获取系统当前时间
        String t = (String)request.getSession().getAttribute("nameSession");  //获取登陆页面用户名
        chat_record += t+"  "+input_textarea+"  "+time+"n";   //聊天记录存储
        request.setAttribute("input_textarea",chat_record); //将当前聊天输入内容存储
        request.getRequestDispatcher("main.jsp").forward(request,response);  //跳转到当前聊天输入界面,即界面布局不变
    }

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

}

 

(3)CodeFilter.java(过滤器类)截取系统所有Servlet类,实现对请求和响应对象的编码格式的设置,均设置为UTF-8。具体实现如下:

 CodeFilter.java类代码如下:

package com.liuzhen.chart;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//采用注解方式配置URL,此处就不必再在web.xml文件中配置。如果两者均配置的话,系统将以web.xml文件中配置信息为准
@WebFilter(filterName="CodeFilter",urlPatterns={"/*"})      

public class CodeFilter implements Filter{


         @Override
         public void destroy() {
             System.out.println("destroy---CodeFilter");                          
         }

         @Override
         public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
                 throws IOException, ServletException {
             System.out.println("start----doFilter--CodeFilter");

             HttpServletRequest request =(HttpServletRequest) arg0;
             HttpServletResponse response =(HttpServletResponse) arg1;
             //以上是强制内型转换,使用request对象和response对象

             request.setCharacterEncoding("utf-8");          //设置过滤页面提取数据的编码
             response.setContentType("text/html;charset=utf-8");  //设置过滤页面显示数据的编码

             arg2.doFilter(arg0, arg1);//在页面跳转之前执行此语句前面的代码,执行完页面的代码之后,在执行后面的语句
             System.out.println("第一个字符过滤器");
             System.out.println("end------doFilter--CodeFilter");    
             }

         @Override
         public void init(FilterConfig filterConfig) throws ServletException {
             System.out.println("init----CodeFilter");
         }

}

 

(4)OnlineListener.java(监听器类)主动监听系统Web容器,返回当前聊天系统在线人数,具体实现如下:

 OnlineListener.java类代码如下:

package com.liuzhen.chart;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class OnlineListener implements HttpSessionListener{

    public void sessionCreated(HttpSessionEvent arg0) {
           ServletContext context = arg0.getSession().getServletContext();

           Integer count = (Integer) context.getAttribute("peopleOnline");
           if (count == null) {
               count = 1;
           } else {
               count++;
           }
           context.setAttribute("peopleOnline", count);
        }

        public void sessionDestroyed(HttpSessionEvent arg0) {
           ServletContext context = arg0.getSession().getServletContext();
           Integer count = (Integer) context.getAttribute("peopleOnline");

           count--;
           context.setAttribute("peopleOnline", count);
        }

}

此处还要给OnlineListener监听器类在web.xml文件中配置路径,web.xml配置代码具体如下(红色标记代码):

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>

  <listener>
    <listener-class>com.liuzhen.chart.OnlineListener</listener-class>
  </listener>

  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>Main</servlet-name>
    <servlet-class>com.liuzhen.chart.Main</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>InputInformation</servlet-name>
    <servlet-class>com.liuzhen.chart.InputInformation</servlet-class>
  </servlet>



  <servlet-mapping>
    <servlet-name>Main</servlet-name>
    <url-pattern>/Main</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>InputInformation</servlet-name>
    <url-pattern>/InputInformation</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
</web-app>

在调用监听器类实现监听系统当前在线人数时,本机上同一个浏览器同时登陆多个用户,只能算作一次,本机上不同浏览器登陆则分别算作一次。以下分别是在IE、谷歌和360浏览器登陆在线人数显示:

图片 10

图四:IE浏览器登陆,显示在线人数1人

 图片 11

图五:谷歌浏览器登陆,显示在线人数2人

 图片 12

图六:360浏览器登陆,显示在线人数3人

 附:本文系统代码Coding链接:

 参考资料:

1、cookie实现记住密码

2、监听器(实现在线统计人数,踢人)

3、Java
Filter过滤机制详解

4、jsp与servlet之间页面跳转及参数传递实例

 

<%@ page contentType="text/html;charset=gb2312"%>
<html>
 <head>
  <title>登录成功</title>
 </head>
 <body>
  <h2>${sessionScope.username}您好,欢迎登录网上书店!</h2>
 </body>
</html>

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图