使用session验证的用户登录界面(简写)

其实在我刚刚学习javaWeb的时候我也是觉得这些东西很难很繁琐,但是学习了一阵子之后就觉得其实都是这点东西鼓捣来鼓捣去的下面开始代码部分:

1:具体的登陆页面:(要注意的是我的这里面使用了css 如果看不懂的就用一个简单的form就行 将其中的action修改成自己的继承自HttpServlet的类名(其实就是servlet名字只是为了防止混乱))

<%@ 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%>">
    
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     <title>Book Store</title>
     <link rel="stylesheet" type="text/css" href="style.css" />


  </head>
  
  <body>
  <jsp:include  page="head.jsp"/> 
    
    <div id="wrap">
    <div class="center_content">
    <div class="left_content">
      <div class="title"><span class="title_icon"><img src="images/bullet1.gif" alt="" title="" /></span>登陆 </div>
      <div class="feat_prod_box_details">
        <p class="details"> 我们是专门做书籍的网站,您想要的书籍我们这里都有只有你想不到,没有我们做不到这就是我们想要的网上书店。我们同时也是一家做特卖的网站。只不过我们做的特卖都是书籍。因为我们相信书籍可以改变世界改变你的人生! </p>
        <div class="contact_form">
          <div class="form_subtitle">登陆 以查看清单</div>
          <form name="register" method="post" action="UserDAO">
            <div class="form_row">
              <label class="contact"><strong>用户名:</strong></label>
              <input type="text" class="contact_input" name="userName" />
            </div>
            <div class="form_row">
              <label class="contact"><strong>密  码:</strong></label>
              <input type="password" class="contact_input" name="password" />
            </div>
            <div class="form_row">
              <div class="terms"><input type="checkbox" name="terms" />记住密码 </div>
            </div>
            <div class="form_row">
              <input type="submit" class="register" value="登陆" />
            </div>
          </form>
        </div>
         </div>
      <div class="clear"></div>
    </div>
    <jsp:include  page="broadside.jsp"/> 
    </div>
    </div>
  </body>
</html>
2:登录时需要用的servlet类(由于时间段我只做了简单的设计其实应该将对数据库中的增删改查设计成另一个类这样的话可以提高代码的重用性):
package userUtil;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bookConnUtil.*;


public class UserDAO extends HttpServlet{
       //在这之前你应该已经建立了自己的user类并且为其设置了setter和getter访问器
	private User user=null;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public UserDAO() {
		// TODO Auto-generated constructor stub
	}

	
protected void doPost(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{
		response.setContentType("text/html");//
		response.setCharacterEncoding("utf-8");//
		//PrintWriter out=response.getWriter();
		String userName=request.getParameter("userName");
		String password=request.getParameter("password");
		//System.out.println(userName);
		//System.out.println(password);
		 HttpSession session=request.getSession();//返回与当前request相关联的session,如果没有则在服务器端创建一个;
		 session.setAttribute("username",userName);
		Connection conn=null;
		PreparedStatement stmt=null;
		ResultSet rs=null;
		try
		{
			conn=DBUtil.getConnection(DBUtil.CONNECTION_SQL);
			stmt=conn.prepareStatement("select * from users where uname=? and password=?");
			stmt.setString(1, userName);
			stmt.setString(2,password);
			//System.out.println("设置参数没问题");
			rs=stmt.executeQuery();
			//System.out.println("获取结果集没问题");
			if(rs.next())
			{
				
				
				
//				System.out.println("-------------------");
//				System.out.println("成功!");
//				System.out.println("-----------------------");
			   if(userName.equals("zhangfan")){
				   
				   request.getRequestDispatcher("adminManagePage.jsp").forward(request, response);
				   
			   }else{	
				   
				   		request.getRequestDispatcher("index.jsp").forward(request, response);
			   }
				
			} else{
				request.getRequestDispatcher("error.html").forward(request, response);
				
			}
		
			
		} catch(Exception e){
			System.out.println("出岔子了");
		}
		finally
		{
			try {

				stmt.close();
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	} 
}
	
	
	
DButil类(实现建立数据库连接类):

package bookConnUtil;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public class DBUtil {
	public static final int CONNECTION_MYSQL=2;
	public static final int CONNECTION_SQL=1;
	public static final int CONNECTION_ODBC=0;
	public DBUtil() {	}
	public static Connection getConnection(int connection_type)throws Exception
	{
		switch (connection_type)
		{
			case CONNECTION_ODBC:
				return getConnectionODBC();
			case CONNECTION_SQL:
				return getConnectionSQL();
			case CONNECTION_MYSQL:
				return getConnectionMYSQL();
		}
		return null;
	}
	
	/**
	 * 使用ODBC连接数据库
	 */
	private static Connection getConnectionODBC()throws Exception
	{
		Connection conn=null;
		try
		{
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			System.out.println("abc");
			conn=DriverManager.getConnection("jdbc:odbc:mybook","sa","123");
			System.out.println("连接成功");
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		return conn;
	}
	private static Connection getConnectionSQL() throws Exception
	{
		Connection conn=null;
		String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=user;";
		try
		{
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		
			conn=DriverManager.getConnection(connectionUrl,"sa","123");
			System.out.println("连接成功");
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		return conn;
	}
	private static Connection getConnectionMYSQL() throws Exception
	{
		String connectionUrl = "jdbc:mysql://localhost:3306/user"; 
		String username = "root"; 
		String password = "mysql"; 
		Connection conn=null;
		
		try
		{
			Class.forName("com.mysql.jdbc.Driver"); 
			
			conn=DriverManager.getConnection(connectionUrl, username,password);
			System.out.println("连接成功");
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		return conn;
		
	}
	public static void close(Connection conn) throws Exception
	{
		if(conn!=null)
		{
			try
			{
				conn.close();
			}
			catch(SQLException e)
			{
				e.printStackTrace();
				throw e;
			}
		}
	}
	
	
	

}





你可能感兴趣的:(java,类,session,servlet,javaweb)