servlet 不同登录用权限跳转不同页面简易实现

  很多朋友第一接触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;
	}

至此,功能基本实现。

你可能感兴趣的:(oracle,servlet,javaweb,登录分配权限)