同时实现不同权限用户登入

LoginServlet.java 

package com.mvc.controlle;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mvc.bean.*;

import com.mvc.dao.*;
/**
 * Servlet implementation class Servlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		 	String userNameInput = request.getParameter("user");
	        String passwordInput = request.getParameter("pwd");
	        	
	        String type=request.getParameter("type");
	        System.out.println(type);
	        //判断类型
	        if("2".equals(type)){
	        
	        StaffBean loginBeanInput = new StaffBean(); // Bean classes are efficiently used to access user information wherever required in the application.
	        loginBeanInput.setName(userNameInput);
	        loginBeanInput.setPwd(passwordInput);

	        StaffDao loginDao = new StaffDao();
	        
	        String userValidate = loginDao.authenticateUser(loginBeanInput);

	        if(userValidate.equals("SUCCESS")){
	            System.out.print("SUCCESSyes");
	            request.setAttribute("userNameInput", userNameInput); //with setAttribute() you can define a "key" and value pair so that you can get it in future using getAttribute("key")
	            request.getRequestDispatcher("/KMGP.jsp").forward(request, response);//RequestDispatcher is used to send the control to the invoked page.
	        }

	        else{
	            System.out.print("SUCCESSno");
	            request.setAttribute("errMessage", userValidate); // Here the error message returned from function has been stored in a errMessage key.
	            request.getRequestDispatcher("/login.jsp").forward(request, response);//forwarding the request
	        }
	        }
	        
	        else
	        {
		        UserBean loginBeanInput = new UserBean(); // Bean classes are efficiently used to access user information wherever required in the application.
		        loginBeanInput.setName(userNameInput);
		        loginBeanInput.setPwd(passwordInput);

		        UserDao loginDao = new UserDao();
		        
		        String userValidate = loginDao.authenticateUser(loginBeanInput);

		        if(userValidate.equals("SUCCESS")){
		            System.out.print("SUCCESSyes");
		            request.setAttribute("userNameInput", userNameInput); //with setAttribute() you can define a "key" and value pair so that you can get it in future using getAttribute("key")
		            request.getRequestDispatcher("/h_main.jsp").forward(request, response);//RequestDispatcher is used to send the control to the invoked page.
		        }

		        else{
		            System.out.print("SUCCESSno");
		            request.setAttribute("errMessage", userValidate); // Here the error message returned from function has been stored in a errMessage key.
		            request.getRequestDispatcher("/login.jsp").forward(request, response);//forwarding the request
		        }
	        }
	}

}

UserDao.java 

package com.mvc.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mvc.bean.*;
import com.mvc.util.DBConnection;
import com.mysql.jdbc.Connection;


public class UserDao {


    public String authenticateUser(UserBean loginBeanInput) {

        String userNameInput = loginBeanInput.getName(); //Keeping user entered values in temporary variables.
        String passwordInput = loginBeanInput.getPwd();

        Connection con = null;
        Statement statement = null;
        ResultSet resultSet = null;

        String userNameDB = "";
        String passwordDB = "";

        try {
            con = DBConnection.createConnection(); //establishing connection
            statement = con.createStatement(); //Statement is used to write queries.
            resultSet = statement.executeQuery("SELECT name,pwd from db_restaurant.user");


            // Until next row is present otherwise it return false
            while (resultSet.next()){

                userNameDB = resultSet.getString("name"); //fais attention c'est les valeurs du DB
                passwordDB = resultSet.getString("pwd");

                if (userNameInput.equals(userNameDB) && passwordInput.equals(passwordDB)) {
                    return "SUCCESS";
                }
            }



        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.print("Invalid user credentials");
        return "Invalid user credentials";

    }
}

StaffDao.java 

package com.mvc.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mvc.bean.*;
import com.mvc.util.DBConnection;
import com.mysql.jdbc.Connection;


public class StaffDao {


    public String authenticateUser(StaffBean loginBeanInput) {

        String userNameInput = loginBeanInput.getName(); //Keeping user entered values in temporary variables.
        String passwordInput = loginBeanInput.getPwd();

        Connection con = null;
        Statement statement = null;
        ResultSet resultSet = null;

        String userNameDB = "";
        String passwordDB = "";

        try {
            con = DBConnection.createConnection(); 
            statement = con.createStatement(); 
            resultSet = statement.executeQuery("SELECT name,pwd from db_restaurant.staff");


            // Until next row is present otherwise it return false
            while (resultSet.next()){

                userNameDB = resultSet.getString("name"); //fais attention c'est les valeurs du DB
                passwordDB = resultSet.getString("pwd");

                if (userNameInput.equals(userNameDB) && passwordInput.equals(passwordDB)) {
                    return "SUCCESS";
                }
            }



        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.print("Invalid user credentials");
        return "Invalid user credentials";

    }
}

StaffBean.java 

package com.mvc.bean;

public class StaffBean {
	private Integer sid;
	private String name;
	private String pwd;
	private String sex;
	private String phone;
	
	public Integer getSid() {
		return sid;
	}
	public void setSid(Integer sid) {
		this.sid = sid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
    
}

UserBean.java 

package com.mvc.bean;

public class UserBean {
	private Integer uid;
	private String name;
	private String pwd;
	private String sex;
	private String email;
	private String phone;
	private String adress;

	public Integer getUid() {
		return uid;
	}
	public void setUid(Integer uid) {
		this.uid = uid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getAdress() {
		return adress;
	}
	public void setAdress(String adress) {
		this.adress = adress;
	}
}

DBConnection.java 

package com.mvc.util;


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

import com.mysql.jdbc.Connection;


public class DBConnection {
    public static Connection createConnection(){
        Connection con = null;
        String url = "jdbc:mysql://localhost:3306/db_restaurant?useUnicode=true&characterEncoding=utf8"; 
        String username = "root";
        String password = "root";
        try {

            Class.forName("com.mysql.jdbc.Driver"); //loading mysql driver
            con = (Connection) DriverManager.getConnection(url, username, password); //attempting to connect to MySQL database
            System.out.println("Printing connection object "+con);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }
    
	/**
	 * 以下是获取oracle数据库的连接方法,注意使用oracle要导入oracle驱动相应的jar包.
	 * @return
	 */
//    private static String USERNAMR = "root";
//    private static String PASSWORD = "123";
//    private static String DRVIER = "oracle.jdbc.OracleDriver";
//    private static String URL = "jdbc:oracle:thin:@localhost:1521:orcl";
//	public Connection getConnection() {
//		Connection con = null;
//			 try {
//		            Class.forName(DRVIER);
//		            con = DriverManager.getConnection(URL, USERNAMR, PASSWORD);
//		            System.out.println("成功连接数据库");
//		        } catch (ClassNotFoundException e) {
//		            throw new RuntimeException("class not find !", e);
//		        } catch (SQLException e) {
//		            throw new RuntimeException("get connection error!", e);
//		        }
//		
//
//		return con;
//	}
}

h_main.jsp 

s <%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <style type="text/css">
        	*{
     		padding: 0;
     		margin: 0;
     		}
        	.top{
				width: 1600px;
				height: 200px;
				margin: auto;
				background:#FFFFFF;
				}
.left{
	border: 2px solid #FFFFFF;
	width: 250px;
	height: 520px;
	float: left;
}
.right{
	width: 1240px;
	height: 660px;
	border: 2px solid  #FFFFFF;
	float: right;
}
        </style>
    </head>
    <body>
<script type="text/javascript">
    $(function () {
        layoutrezise();
        AutoHeight();
    })
    function layoutrezise() {
        var headerH = $("div#Headbox").height(); //获取头部的高度
        var bodyerH = $(window).height() - headerH;  //计算内容的高度(不包括头部)
        $("div#Bodybox,div#bleftBox,div#brightBox,iframe#leftiframe,iframe#mainframe").height(bodyerH); //设置主框架的高度--%>
        $("div#brightBox").width($(window).width() - $("div#bleftBox").width()); //设置主框架的宽度
    }
    function AutoHeight() {
        $(window).resize(function () {
            layoutrezise();
        })
    }        
</script>
		<div id="Headbox" class="clearfix">
    	<iframe class="top"frameborder="0" name="top" src="h_topImage.jsp" style="width:100%; border:0;" id="top"></iframe>
    	</div>
    	<div id="Bodybox" class="clearfix">
        <iframe class="left"frameborder="0" name="left" src="h_leftcontent.jsp" id="left"></iframe>
         </div>
         <div id="brightBox" class="fl">
        <iframe class="right" frameborder="0" src="img/D.png" name="right"  style="width:70%; border:0;"  id="right"></iframe>
        </div>
    </body>
</html>
    
    
    

login.jsp 

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html >
<meta charset="UTF-8">
<title>Login</title>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
    <meta http-equiv="Content-Language" content="zh-CN" />
    <style type="text/css">
    	html{
    width: 100%;
    height: 100%;
    overflow: hidden;
    font-style: sans-serif;
}
body{
    width: 100%;
    height: 100%;
    font-family: 'Open Sans',sans-serif;
    margin: 0;
    background-color: #4A374A;
}
#login{
    position: absolute;
    top: 50%;
    left:50%;
    margin: -150px 0 0 -150px;
    width: 300px;
    height: 300px;
    
}
#login h1{
    color: #fff;
    text-shadow:0 0 10px;
    letter-spacing: 1px;
    text-align: center;
}
h1{
    font-size: 3.5em;
    margin: 0.4em 0;
    transition: 3s;
    font-family:Times New Roman;
}
input{
    width: 278px;
    height: 18px;
    margin-bottom: 10px;
    outline: none;
    padding: 10px;
    font-size: 13px;
    color: #fff;
    text-shadow:1px 1px 1px;
    border-top: 1px solid #312E3D;
    border-left: 1px solid #312E3D;
    border-right: 1px solid #312E3D;
    border-bottom: 1px solid #56536A;
    border-radius: 4px;
    background-color: #2D2D3F;
}
#o{
	 text-decoration:none ;
	 out-line: nonecolor: #*****;
	 color: azure;
}

.but{
    width: 300px;
    min-height: 20px;
    display: block;
    background-color: #4a77d4;
    border: 1px solid #3762bc;
    color: #fff;
    padding: 9px 14px;
    font-size: 15px;
    line-height: normal;
    border-radius: 5px;
    margin: 0;
    transition: 1.5s;

}
.bu{
    width: 300px;
    min-height: 20px;
    display: block;
    background-color: #424242;
    border: 1px solid #3762bc;
    color: #fff;
    padding: 9px 14px;
    font-size: 15px;
    line-height: normal;
    border-radius: 5px;
    margin: 0;
    transition: 1s;
     background-color:#008080;
     }
    .bu :hover{
    border-radius: 42%;
    color: white;
    background-color:#AABBCC;
    transition: 1s;
}
    .but :hover{
    border-radius: 12%;
    color: white;
    background-color:#F5DEB3;
    transition: 1.5s;
}
     
.link {
	
  outline: none;
  text-decoration: none;
  position: relative;
  font-size: 8em;
  line-height: 1;
  color: #9e9ba4;
  display: inline-block;
}   
.but:link { color: #06F; text-decoration: none; }/* 未访问的链接 */
    .but:visited { color: #999; text-decoration: line-through; } /* 已访问的链接 */
    .but:hover { color: #F00; text-decoration: underline; }/* 鼠标移动到链接上 */
    .but:active { color: #F0F; } /* 选定的链接 */
.b{
    width: 300px;
    min-height: 20px;
    display: block;
    background-color: #424242;
    border: 1px solid #3762bc;
    color: #fff;
    padding: 9px 14px;
    font-size: 15px;
    line-height: normal;
    border-radius: 5px;
    margin: 0;
    transition: 1s;
     background-color:#008080;

     }
    .b :hover{
    border-radius: 42%;
    color: white;
    background-color:#F5DEB3;
    transition: 1s;
}

.p{
	background-color: #4a77d4;
	font-family: "bookman old style";
	color: white;
}
.p{

    border-radius: 18%;
    color: white;
    background-color:#4A374A;
    transition: 1s;
    margin: 0;
    padding: 0;

}

    </style>
</head>
<body>
    <div id="login">
    	<h1>Login</h1>
          <form action="/Restaurant/LoginServlet" method="post">
            <input type="text" required="required" placeholder="用户名" name="user"></input>
            <input type="password" required="required" placeholder="密码" name="pwd"></input>
             <button class="bu" type="button"><a id="o" href="register.jsp">注册</a></button>

                   <select name="type" class="p">
                <option value="1">普通用户</option>
                <option value="2">管理员</option>
            </select> 
            <button class="but" type="submit">登录</button>
        </form>
    </div>
</body>
</html>>
</html>

 

  • 10
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值