1. 程式人生 > >java jsp+servlet實現登入網頁設計

java jsp+servlet實現登入網頁設計

這次涉及到四個檔案:
登入頁面:login.jsp 登入成功歡迎頁面:success.jsp
登入失敗頁面:fail.jsp
Servlet處理檔案:LoginServlet.java 其實還涉及到一個檔案:web.xml,這個後面再說: 下面分別介紹這幾個檔案:
//--------------------------------------------------------------------------------------------------------------------
LoginServlet.java   內容: package org.cai.servlet ; import java.sql.* ;
import java.io.* ;
import javax.servlet.http.* ;
import javax.servlet.* ; public class LoginServlet extends HttpServlet implements Servlet{
 public LoginServlet(){
 }
 
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
 
 }
// protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//  System.out.println("-------------------------") ;
//  doPost(request, response) ;
// }
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
  response.setContentType("text/html;charset=gb2312") ;
  request.setCharacterEncoding("gb2312") ;
  String result = "" ;
  //獲取使用者名稱
  String username = request.getParameter("username") ;
  String psw = request.getParameter("password") ;
  if ((username == "") || (username==null) || (username.length() > 20 )){
   try{
    result = "請輸入使用者名稱(不能超過20個字元)!" ;
    request.setAttribute("message" ,result) ;
    response.sendRedirect("login.jsp") ;
   }catch(Exception e){
    e.printStackTrace() ;
   }
  }   if ((psw == "") || (psw==null) || (psw.length() > 20 )){
   try{
    result = "請輸入密碼(不能超過20個字元)!" ;
    request.setAttribute("message" ,result) ;
    response.sendRedirect("login.jsp") ;
   }catch(Exception e){
    e.printStackTrace() ;
   }
  }
  
  //登記JDBC驅動程式
  try{
   Class.forName("org.gjt.mm.mysql.Driver") ;
  }catch(ClassNotFoundException e){
   e.printStackTrace() ;
   System.out.println("Class Not Found Exception . ") ;
  }
  //連線URL
  String url ="jdbc:mysql://localhost:3306/learnJSP" ;
  Connection conn = null ;
  Statement stmt = null ;
  ResultSet rs = null ;
  
  try{
   conn = DriverManager.getConnection(url, "root", "root") ;
   stmt = conn.createStatement() ;
   //SQL語句
   String sql ="select * from userInfo where username='"+username+"' and userpsw= '"+psw+"'" ;
   rs = stmt.executeQuery(sql) ;//返回查詢結果
  }catch(SQLException e){
   e.printStackTrace() ;
  }
   HttpSession session =  request.getSession() ;
   session.setAttribute("username", username) ;
   //System.out.println("+++++++++++++++++++++++"+ username) ;
  try{
   if (rs.next()){ //如果記錄集非空,表明有匹配的使用者名稱和密碼,登陸成功
       // 登入成功後將username設定為session變數的username
          // 這樣在後面就可以通過 session.getAttribute("username") 來獲取使用者名稱,
          // 同時這樣還可以作為使用者登入與否的判斷依據
    session.setAttribute("age",rs.getString("age")) ;
    session.setAttribute("sex",rs.getString("sex")) ;
    session.setAttribute("weight",rs.getString("weight")) ;
    response.sendRedirect("success.jsp") ;
   }else{
    session.setAttribute("message", "使用者名稱或密碼不匹配。");
    response.sendRedirect("fail.jsp") ;
   }
  }catch(SQLException e){
   e.printStackTrace() ;
  }
 }
 
 private static final long serialVersionUID = 1L; } //--------------------------------------------------------------------------------------------------------------------
login.jsp內容:
<%@ page language="java" contentType="text/html;charset=gb2312"%> <html>
 <head>
  <title>登陸</title>
 </head>
 <body>
  <form method="POST" name="frmLogin" action="LoginServlet">
   <h1 align="center">使用者登入</h1><br />
   <center>
    <table border=1>
     <tr>
      <td>使用者名稱:</td>
      <td>
       <input type="text" name="username" value="Your name" size="20" maxlength="20" onfocus="if (this.value=='Your name')  this.value='';" />
      </td>
     </tr>
     <tr>
      <td>密&nbsp;&nbsp;碼:</td>
      <td>
       <input type="password" name="password" value="Your password" size="20" maxlength="20" onfocus="if (this.value=='Your password')  this.value='';" />
      </td>
     </tr>
     <tr>
      <td>
       <input type="submit" name="Submit" value="提交" onClick="return validateLogin()" />
      </td>
      <td>
       <input type="reset" name="Reset" value="重置" />
      </td>
     </tr>
    </table>
   </center>
  </form>
  <script language="javascript">
   function validateLogin(){
    var sUserName = document.frmLogin.username.value ;
    var sPassword = document.frmLogin.password.value ;
    if ((sUserName =="") || (sUserName=="Your name")){
     alert("請輸入使用者名稱!");
     return false ;
    }
    
    if ((sPassword =="") || (sPassword=="Your password")){
     alert("請輸入密碼!");
     return false ;
    }
   }
  </script>
 </body>
</html>
//--------------------------------------------------------------------------------------------------------------------
success.jsp 內容;
<%@ page language="java" contentType="text/html;charset=gb2312" pageEncoding ="gb2312"%>
<html>
 <head>
  <title>歡迎</title>
 </head>
 <body>
  <%
   String userName = (String)session.getAttribute("username") ;
   String age = (String)session.getAttribute("age") ;
   String weight = (String)session.getAttribute("weight") ;
   String sex = (String)session.getAttribute("sex") ;    System.out.println("性別:A" + sex +"A")  ;
   if (sex.trim().equals("M")) {
    sex ="男" ;
   }else{
    sex = "女" ;
   }
  %>
  <div align="center">
   <%=userName %>
   歡迎您,登陸成功!<br />
   <font color="blue">登陸使用者資訊:</font>
   <table border =1 >
    <tr>
     <td>&nbsp;姓名:&nbsp;</td>
     <td>&nbsp;&nbsp;<%=userName %>&nbsp;&nbsp;</td>
    </tr>
    <tr>
     <td>&nbsp;年齡:&nbsp;</td>
     <td>&nbsp;&nbsp;<%=age %>&nbsp;&nbsp;</td>
    </tr>
    <tr>
     <td>&nbsp;體重:&nbsp;</td>
     <td>&nbsp;&nbsp;<%=weight %>&nbsp;kg&nbsp;</>
    </tr>
    <tr>
     <td>&nbsp;性別:&nbsp;</td>
     <td>&nbsp;&nbsp;<%=sex %>&nbsp;&nbsp;</>
    </tr>
   </table>
   <a href="login.jsp">返回</a>
  </div>
 </body>
</html>
//--------------------------------------------------------------------------------------------------------------------
fail.jsp 內容: <%@ page language="java" contentType="text/html;charset=gb2312" pageEncoding ="gb2312"%>
<html>
 <head>
  <title>登陸失敗</title>
 </head>
 <body>
  <%
   String userName = (String)session.getAttribute("username") ;
   String msg  = (String)session.getAttribute("message") ;
  %>
  <div align="center">
   <%=userName %>
   對不起,登陸失敗!<br />
   <font color="red">原因: </font>
   <%=msg %>
   <br/>
   <br/>
   5秒後將返回登陸介面。
  </div>
   
   <%
     response.setHeader("Refresh","5;URL=/learnJSP/login.jsp");  
    %>
 </body>
</html>
//--------------------------------------------------------------------------------------------------------------------
  mysql資料庫中需要建立資料庫learnJSP,其中建立表userInfo 建立表語句為:
  create database learnJSP ;
  use learnJSP
  create table userInfo(id int not null primary key,username char(20) not null,userpsw char(20) ,age int ,weight int ,sex enum('M','F')) ;
 
  需要把連線mysql的jar包放到專案的lib目錄中 //-------------------------------------------------------------------------------------------------------------------- web.xml 內容: <?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "
http://java.sun.com/dtd/web-app_2_3.dtd
">
<web-app>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 
 <servlet>
        <servlet-name>
            LoginServlet
        </servlet-name>
        <servlet-class>
            org.cai.servlet.LoginServlet
        </servlet-class>
    </servlet>     <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
    </servlet-mapping>
 
</web-app>
//--------------------------------------------------------------------------------------------------------------------