package com.lanou.servlet.role; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.lanou.bean.Admin; import com.lanou.bean.Result; import com.lanou.bean.Role; import com.lanou.service.AdminService; import com.lanou.service.RoleMenuService; import com.lanou.service.impl.AdminServiceImpl; import com.lanou.service.impl.RoleMenuServiceImpl; import com.lanou.util.FastJSONUtil; @WebServlet("/admin/delRole") public class DeleteRole extends HttpServlet{ private static final long serialVersionUID = 1L; RoleMenuService roleMenuService = new RoleMenuServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Role role = (Role) req.getSession().getAttribute("role"); long roleId = Long.parseLong(req.getParameter("roleId")); boolean isDelete = false; // 只有超级管理员 有权限删除 if (role.getRoleId() == 1) { isDelete = roleMenuService.delRMByRoleId(roleId); } Result result = null; if (isDelete) { result = new Result(0, "删除成功", null, null); }else { result = new Result(1, "删除失败", null, null); } System.out.println(result.getCode()); resp.setContentType("type/json;charset=utf-8"); resp.getWriter().write(FastJSONUtil.entityToJson(result)); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
时间: 2024-04-08 19:33:09 浏览: 150
这是一个名为`DeleteRole`的`Servlet`类,用于处理删除角色的请求。下面是代码的解析:
1. `doGet()`方法用于处理`GET`请求。
2. 从会话中获取当前登录用户的角色对象:
```java
Role role = (Role) req.getSession().getAttribute("role");
```
3. 从请求参数中获取要删除的角色的ID,并将其转换为`long`类型:
```java
long roleId = Long.parseLong(req.getParameter("roleId"));
```
4. `isDelete`变量用于表示是否成功删除角色,默认为`false`。
5. 只有超级管理员(角色ID为1)有权限删除角色,因此在此条件下进行删除操作:
```java
if (role.getRoleId() == 1) {
isDelete = roleMenuService.delRMByRoleId(roleId);
}
```
`roleMenuService.delRMByRoleId(roleId)`是一个删除与角色相关联的菜单权限的方法,根据`roleId`参数执行删除操作并返回结果。
6. 创建一个`Result`对象来表示操作结果,根据`isDelete`的值设置不同的状态和消息:
```java
Result result = null;
if (isDelete) {
result = new Result(0, "删除成功", null, null);
} else {
result = new Result(1, "删除失败", null, null);
}
```
7. 打印结果代码:
```java
System.out.println(result.getCode());
```
8. 设置响应的内容类型为JSON,并将结果对象转换为JSON字符串并写入响应:
```java
resp.setContentType("type/json;charset=utf-8");
resp.getWriter().write(FastJSONUtil.entityToJson(result));
```
9. `doPost()`方法直接调用`doGet()`方法,以便处理`POST`请求。
阅读全文