It is easy to jump to different pages with different login permissions in servlet.
Many friends first contact javaweb and servlet want to manage different user roles in the system to enter the corresponding permissions of the page for the operation function, generally speaking, there are many ways, the easiest to think of is to directly insert a column of fields with permissions in the user database (permission number), and then query, the value will be returned to the corresponding serlvet page (LoginServlet.java), with a simple if judgment. Here is the specific code:
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"))
/ / get type
System.out.println (user.getUsername ())
Request.setAttribute ("", user)
UserManagerOracleImpl userManager = new UserManagerOracleImpl ()
Int permission = userManager.isValid (user)
/ / permssion = 1 is an administrator = 0 is an ordinary user
/ / determine the type
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)
}
}
}
Method of isValid (User ueser) in userManager: / / method for callback of permission, used to determine
/ * verify login users * * * / 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;}
At this point, the function is basically realized.