您好,登錄后才能下訂單哦!
很多朋友第一接觸javaweb和servlet想實現管理系統中不同用戶角色進入相應權限的頁面進行相應權限的操作功能,總的來說有很多方法,最簡單想到就是直接在用戶數據庫中插入一列帶有權限的字段(permission number),然后查詢的時候,將值返回到對應的serlvet頁面(LoginServlet.java),用簡單的if判斷即可。 下面是具體代碼:
LoginServlet.java:
package com.cola.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.cola.entity.Userjia;
import com.cola.manager.impl.UserManagerOracleImpl;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
Userjia user = new Userjia();
user.setUsername(request.getParameter("userName"));
user.setUserpasswd(request.getParameter("passwd"));
//獲取類型
System.out.println(user.getUsername());
request.setAttribute("haha", user);
UserManagerOracleImpl userManager = new UserManagerOracleImpl();
int permission = userManager.isValid(user);
// permssion = 1 為管理員 =0 為普通用戶
//判斷類型
if(permission==1){
request.getRequestDispatcher("/index.html").forward(request, response);
System.out.println("userName------------>"+user.getUsername());
}else if(permission==0){
request.getRequestDispatcher("/index2.html").forward(request,response);
System.out.println("userName------------>"+user.getUsername());
}else if(permission==-1){
request.getRequestDispatcher("/failed.html").forward(request,response);
}
}
}
userManager 中isValid(User ueser)的方法://用于將permission 回調的方法,用于判斷
/*************************************************************** * * 驗證登陸用戶 * * *************************************************************/ public int isValid(Userjia user){ int permission = -1; Connection conn = null; ResultSet rs = null; Statement stmt = null; conn=ConnectionFactory.getConnection(); try { stmt = conn.createStatement(); rs = stmt.executeQuery ("select * from login_user where name ='" +user.getUsername()+"' and passwd= '"+user.getUserpasswd()+"' "); if(rs.next()){ permission = rs.getInt("permission"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ CloseResource.release(rs, stmt, conn); } return permission; }
至此,功能基本實現。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。