Kimi's NutShell

我荒废的今日,正是昨日殒身之人祈求的明日

BlogJava 新随笔 管理
  141 Posts :: 0 Stories :: 75 Comments :: 0 Trackbacks
这次涉及到四个文件:
登录页面:login.html
登录成功欢迎页面:login_success.jsp
登录失败页面:login_failure.jsp
Servlet处理文件:LoginServlet.java
其实还涉及到一个文件:web.xml,这个后面再说:
下面分别介绍这几个文件:
登录页面:login.html

<!-- 该Login页面是一个简单的登录界面 -->
<!--
该JSP程序是用来测试与MySQL数据库的连接,
需要一个数据库:LearnJSP,和其中一个表:userinfo
表中有两个字段分别为:UserName varchar (20) not null,UserPwd varchar (20) not null
-->

< html >
  <head>
    <title>登录</title>
    <meta http-equiv="content-type"content="text/html; charset=UTF-8">
    <meta http-equiv="Content-Language"content="ch-cn">
  </head>
  <body>
<!-- Form 用来提取用户填入并提交的信息-->
<formmethod="post"name="frmLogin"action="LoginServlet">
   <h1align="center">用户登录</h1><br>
   <divalign="center">用户名:
      <inputtype="text"name="txtUserName"value="Your name"
       size="20"maxlength="20"
       onfocus="if(this.value=='Your name')this.value='';"><br>密码:
      <inputtype="password"name="txtPassword"value="Your password"
       size="20"maxlength="20"
       onfocus="if(this.value=='Your password')this.value='';"><br>
      <inputtype="submit"name="Submit" value="提交"onClick="validateLogin();">
       &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <inputtype="reset"name="Reset"value="重置"><br>
   </div>
</form>
<!-- javaScript 函数 validateLogin(),用来验证用户名和密码是否为空 -->
    <scriptlanguage="javaScript">
      function validateLogin()
     {
      var sUserName = document.frmLogin.txtUserName.value;
      var sPassword = document.frmLogin.txtPassword.value;
       if( sUserName=="")
      {
        alert("请输入用户名!");
        return false;
      }
       if( sPassword=="")
      {
        alert("请输入密码!");
        return false;
      }
     }
    </script>
  </body>
</html>

登录成功欢迎页面:login_success.jsp

< % @ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <title>My JSP 'login_failure.jsp' starting page</title>
  <meta http-equiv="content-type"content="text/html; charset=UTF-8">
  <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">
  <!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>
<body>
  <%
   String userName =(String)session.getAttribute ("UserName");
  %>
  <divalign=center>
   <%=userName%>
    欢迎您,登录成功!
  </div>
</body>
</html>

登录失败页面:login_failure.jsp

< % @ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <title>My JSP 'login_failure.jsp' starting page</title>
  <meta http-equiv="content-type"content="text/html; charset=UTF-8">
  <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">
  <!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>
<body>
  <%
  String userName =(String)session.getAttribute ("UserName");
  %>
  <divalign=center>
   <%=userName%>
    对不起,登录失败!
  </div>
</body>
</html>

Servlet处理文件:LoginServlet.java

/**
* 该JSP程序是用来测试与MySQL数据库的连接,
* 需要一个数据库:LearnJSP,和其中一个表:userinfo
* 表中有两个字段分别为:UserName varchar (20) not null,UserPwd varchar (20) not null
*/

package zieckey.login.servlet;
importjava.sql.Statement;
importjava.io.IOException;
importjava.sql.DriverManager;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjavax.servlet.Servlet;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
publicclass 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
protectedvoid 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
protectedvoid doPost ( HttpServletRequest request, HttpServletResponse response )
   throws ServletException,IOException
{
   response.setContentType("text/html");
  Stringresult="";
  
// 获取用户名

  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不同

  Stringurl="jdbc:mysql://localhost/LearnJSP";
  
// 建立连接

  java.sql.Connectionconnection=null;
  Statement stmt =null;
  ResultSet rs =null;
  try
  {
   connection=DriverManager.getConnection(url,"root","011124");
    stmt =connection.createStatement();
   
// SQL语句

   Stringsql="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中注册一下,
现该文件内容修改如下:

< ?xml version="1.0"encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>zieckey.login.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
</web-app>

好了,这几个文件就可以构成我们的这个登录界面了.
注意事项:
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    <DIR>          META-INF
007-01-18 15:16    <DIR>          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    <DIR>          classes
007-01-18 15:16    <DIR>          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
2. 其他注意事项
数据库MySQL服务器程序要先启动起来.
posted on 2008-02-28 14:39 Kimi 阅读(1967) 评论(3)  编辑  收藏 所属分类: Java

评论

# re: MVC简单模式: 登录 (转) 2011-02-22 11:24 vghv
m mkllmkmk;  回复  更多评论
  

# re: MVC简单模式: 登录 (转) 2011-02-22 11:25 vghv
怎么运行不成功?  回复  更多评论
  

# re: MVC简单模式: 登录 (转)[未登录] 2011-02-22 11:43 nick
不会啊,是不是你哪里没有配置好?@vghv
  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: