十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
很多朋友第一接触javaweb和servlet想实现管理系统中不同用户角色进入相应权限的页面进行相应权限的操作功能,总的来说有很多方法,最简单想到就是直接在用户数据库中插入一列带有权限的字段(permission number),然后查询的时候,将值返回到对应的serlvet页面(LoginServlet.java),用简单的if判断即可。 下面是具体代码:
成都创新互联公司主要从事做网站、成都网站制作、网页设计、企业做网站、公司建网站等业务。立足成都服务福清,十年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务: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 回调的方法,用于判断
/*************************************************************** * * 验证登陆用户 * * *************************************************************/ 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; }
至此,功能基本实现。