很多朋友第一接觸javaweb和servlet想實(shí)現(xiàn)管理系統(tǒng)中不同用戶角色進(jìn)入相應(yīng)權(quán)限的頁(yè)面進(jìn)行相應(yīng)權(quán)限的操作功能,總的來(lái)說(shuō)有很多方法,最簡(jiǎn)單想到就是直接在用戶數(shù)據(jù)庫(kù)中插入一列帶有權(quán)限的字段(permission number),然后查詢的時(shí)候,將值返回到對(duì)應(yīng)的serlvet頁(yè)面(LoginServlet.java),用簡(jiǎn)單的if判斷即可。 下面是具體代碼:
成都創(chuàng)新互聯(lián)公司主要從事做網(wǎng)站、成都網(wǎng)站制作、網(wǎng)頁(yè)設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)福清,十年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專業(yè),歡迎來(lái)電咨詢建站服務(wù):028-86922220
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 回調(diào)的方法,用于判斷
/*************************************************************** * * 驗(yàn)證登陸用戶 * * *************************************************************/ 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; }
至此,功能基本實(shí)現(xiàn)。