在jsp+servlet中实习管理员与用户的判定
时间: 2024-05-16 18:13:23 浏览: 13
在JSP + Servlet中实现管理员和用户的判断,可以采用以下方法:
1. 在数据库中创建一个用户表和一个管理员表,分别保存用户和管理员的信息。
2. 在登录页面中,用户输入用户名和密码,然后在Servlet中查询用户表和管理员表,判断输入的用户名和密码是否正确。
3. 如果用户名和密码正确,则根据用户类型跳转到不同的页面。如果是管理员,则跳转到管理员页面;如果是普通用户,则跳转到用户页面。
下面是一个示例代码:
在登录页面中,用户输入用户名和密码,然后提交表单到Servlet中:
```html
<form action="loginServlet" method="post">
<label>用户名:</label>
<input type="text" name="username"><br>
<label>密码:</label>
<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
```
在Servlet中,查询用户表和管理员表,判断用户类型:
```java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
// 查询用户表
User user = userDao.getUserByUsernameAndPassword(username, password);
if(user != null) {
// 普通用户登录成功,跳转到用户页面
request.getSession().setAttribute("user", user);
response.sendRedirect("user.jsp");
return;
}
// 查询管理员表
Admin admin = adminDao.getAdminByUsernameAndPassword(username, password);
if(admin != null) {
// 管理员登录成功,跳转到管理员页面
request.getSession().setAttribute("admin", admin);
response.sendRedirect("admin.jsp");
return;
}
// 用户名或密码错误,返回登录页面,并显示错误提示
request.setAttribute("error", "用户名或密码错误");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
```
在用户页面和管理员页面中,可以根据session中保存的用户或管理员信息来判断用户类型:
```jsp
<%
User user = (User) session.getAttribute("user");
Admin admin = (Admin) session.getAttribute("admin");
if(user != null) {
// 普通用户页面
} else if(admin != null) {
// 管理员页面
} else {
// 未登录,跳转到登录页面
response.sendRedirect("login.jsp");
}
%>
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)