Controller 層實現


一、實驗介紹

1.1 實驗內容

本節課程主要利用 Spring MVC 框架實現 Controller 層以及一些輔助類的實現。

1.2 實驗知識點

  • Spring MVC 框架

1.3 實驗環境

  • JDK1.8
  • Eclipse JavaEE

二、實驗步驟

在項目 hrms 的目錄 src/main/java 下新建包 com.shiyanlou.controller,作為 Controller 層的包,新建包 com.shiyanlou.util,作為輔助類的包,這些輔助類是為了使 Controller 層的代碼更好維護,以及實現一些其他功能。

2.1 輔助類的實現

2.1.1 DateUtil 類

在包 com.shiyanlou.util 下建一個輔助類 DateUtil,其中的 getDate() 方法的作用是返回格式化的當前日期,代碼如下:

package com.shiyanlou.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateUtil { public static Date getDate() throws ParseException{ Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.parse(sdf.format(date)); } } 

2.1.2 JsonDateValueProcessor 類

在包 com.shiyanlou.util 下建一個輔助類 JsonDateValueProcessor,其作用是將日期轉化使之能在 easyUI 的 datagrid 中正常顯示,代碼如下:

package com.shiyanlou.util; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import net.sf.json.JsonConfig; import net.sf.json.processors.JsonValueProcessor; public class JsonDateValueProcessor implements JsonValueProcessor { private String format ="yyyy-MM-dd"; public JsonDateValueProcessor() { super(); } public JsonDateValueProcessor(String format) { super(); this.format = format; } @Override public Object processArrayValue(Object paramObject, JsonConfig paramJsonConfig) { return process(paramObject); } @Override public Object processObjectValue(String paramString, Object paramObject, JsonConfig paramJsonConfig) { return process(paramObject); } private Object process(Object value){ if(value instanceof Date){ SimpleDateFormat sdf = new SimpleDateFormat(format,Locale.CHINA); return sdf.format(value); } return value == null ? "" : value.toString(); } } 

2.1.3 ResponseUtil 類

在包 com.shiyanlou.util 下建一個輔助類 ResponseUtil,其 write() 方法的作用是將用 HttpServletResponse 返回前台 JSON 格式數據,同時減少 Controller 層代碼的冗余,代碼如下:

package com.shiyanlou.util;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

public class ResponseUtil { public static void write(HttpServletResponse response, Object o) throws Exception { response.setContentType("text/html;charset=utf-8"); response.addHeader("Access-Control-Allow-Origin", "*"); PrintWriter out = response.getWriter(); out.println(o.toString()); out.flush(); out.close(); } } 

2.1.4 IntegrateObject 類

在包 com.shiyanlou.util 下建一個輔助類 IntegrateObject,其 genericAssociation() 方法的作用是完成 Employee 與 Department, Position 對象的關聯映射,代碼如下:

package com.shiyanlou.util; import com.shiyanlou.domain.Department; import com.shiyanlou.domain.Employee; import com.shiyanlou.domain.Position; public class IntegrateObject { /** * 由於部門和職位在 Employee 中是對象關聯映射, * 所以不能直接接收參數,需要創建 Department 對象和 Position 對象 * */ public static void genericAssociation(Integer dept_id,Integer pos_id,Employee employee){ Department department = new Department(); department.setId(dept_id); Position position = new Position(); position.setId(pos_id); employee.setDepartment(department); employee.setPosition(position); } } 

2.2 Controller 層代碼實現

2.2.1 AdminController

在包 com.shiyanlou.controller 下新建一個類 AdminController,代碼如下:

package com.shiyanlou.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.shiyanlou.domain.Admin; import com.shiyanlou.service.AdminService; import com.shiyanlou.util.ResponseUtil; /**類中的所有響應方法都被映射到 /admin 路徑下 * * @author shiyanlou * */ @Controller @RequestMapping("/admin") public class AdminController { // 自動注入 adminService @Resource private AdminService adminService; /** 處理登錄請求 * * @param admin * @param request * @param session * @return */ @RequestMapping("/login") public String login(Admin admin, HttpServletRequest request, HttpSession session) { Admin resultAdmin = adminService.login(admin); // 如果該登錄的管理員用戶名或密碼錯誤返回錯誤信息 if (resultAdmin == null) { request.setAttribute("admin", admin); request.setAttribute("errorMsg", "Please check your username and password!"); return "login"; } else { // 登錄成功, Session 保存該管理員的信息 session.setAttribute("currentAdmin", resultAdmin); session.setAttribute("username", resultAdmin.getUsername()); return "redirect:main"; } } /**處理跳轉至主頁請求 * * @param model * @return * @throws Exception */ @RequestMapping(value="/main") public String test(Model model) throws Exception{ return "home_page"; } /**處理查詢管理員請求 * * @param admin * @param response * @return * @throws Exception */ @RequestMapping("/list") public String list(Admin admin, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); // 判斷查詢條件是否為空,如果是,對條件做數據庫模糊查詢的處理 if (admin.getUsername() != null && !"".equals(admin.getUsername().trim())) { map.put("username", "%" + admin.getUsername() + "%"); } List<Admin> adminList = adminService.findAdmins(map); Integer total = adminService.getCount(map); // 將數據以 JSON 格式返回前端 JSONObject result = new JSONObject(); JSONArray jsonArray = JSONArray.fromObject(adminList); result.put("rows", jsonArray); result.put("total", total); ResponseUtil.write(response, result); return null; } /**處理保存管理員請求 * * @param admin * @param request * @param response * @return * @throws Exception */ @RequestMapping("/save") public String save(Admin admin, HttpServletRequest request, HttpServletResponse response) throws Exception { int resultTotal = 0; // 如果 id 不為空,則添加管理員,否則修改管理員 if (admin.getId() == null) resultTotal = adminService.addAdmin(admin); else resultTotal = adminService.updateAdmin(admin); JSONObject result = new JSONObject(); if (resultTotal > 0) { result.put("success", true); } else { result.put("success", false); } ResponseUtil.write(response, result); return null; } /** 處理刪除管理員請求 * * @param ids * @param response * @param session * @return * @throws Exception */ @RequestMapping("/delete") public String delete(@RequestParam(value = "ids") String ids, HttpServletResponse response, HttpSession session) throws Exception { JSONObject result = new JSONObject(); // 將要刪除的管理員的 id 進行處理 String[] idsStr = ids.split(","); for (int i = 0; i < idsStr.length; i++) { // 不能刪除超級管理員(superadmin) 和當前登錄的管理員 if (idsStr[i].equals("1")||idsStr[i].equals(((Admin)session.getAttribute("currentAdmin")).getId().toString())){ result.put("success", false); continue; }else{ adminService.deleteAdmin(Integer.parseInt(idsStr[i])); result.put("success", true); } } ResponseUtil.write(response, result); return null; } /**處理退出請求 * * @param session * @return * @throws Exception */ @RequestMapping("/logout") public String logout(HttpSession session) throws Exception { session.invalidate(); return "redirect:/login.jsp"; } } 

2.2.2 PostController

在包 com.shiyanlou.controller 下新建一個類 PostController,代碼如下:

package com.shiyanlou.controller; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.shiyanlou.domain.Admin; import com.shiyanlou.domain.Post; import com.shiyanlou.service.PostService; import com.shiyanlou.util.DateUtil; import com.shiyanlou.util.JsonDateValueProcessor; import com.shiyanlou.util.ResponseUtil; /**類中的所有響應方法都被映射到 /post 路徑下 * * @author shiyanlou * */ @Controller @RequestMapping("/post") public class PostController { // 自動注入 postService @Resource private PostService postService; /**處理查詢公告請求 * * @param post * @param response * @return * @throws Exception */ @RequestMapping("/list") public String list(Post post, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); // 判斷查詢條件是否為空,如果是,對條件做數據庫模糊查詢的處理 if (post.getTitle() != null && !"".equals(post.getTitle().trim())) { map.put("title", "%" + post.getTitle() + "%"); } List<Post> postList = postService.findPosts(map); Integer total = postService.getCount(map); // 處理日期使之能在 easyUI 的 datagrid 中正常顯示 JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor()); // 將數據以 JSON 格式返回前端 JSONObject result = new JSONObject(); JSONArray jsonArray = JSONArray.fromObject(postList, jsonConfig); result.put("rows", jsonArray); result.put("total", total); ResponseUtil.write(response, result); return null; } /**處理保存公告請求 * * @param post * @param request * @param response * @param session * @return * @throws Exception */ @RequestMapping("/save") public String save(Post post, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception { Admin admin = (Admin)session.getAttribute("currentAdmin"); post.setAdmin(admin); post.setDate(DateUtil.getDate()); int resultTotal = 0; // 如果 id 不為空,則添加公告,否則修改公告 if (post.getId() == null) resultTotal = postService.addPost(post); else resultTotal = postService.updatePost(post); JSONObject result = new JSONObject(); if (resultTotal > 0) { result.put("success", true); } else { result.put("success", false); } ResponseUtil.write(response, result); return null; } /**處理刪除公告請求 * * @param ids * @param response * @param session * @return * @throws Exception */ @RequestMapping("/delete") public String delete(@RequestParam(value = "ids") String ids, HttpServletResponse response, HttpSession session) throws Exception { JSONObject result = new JSONObject(); // 將要刪除的公告的 id 進行處理 String[] idsStr = ids.split(","); for (int i = 0; i < idsStr.length; i++) { postService.deletePost(Integer.parseInt(idsStr[i])); } result.put("success", true); ResponseUtil.write(response, result); return null; } /**處理根據 id 查詢公告請求 * * @param id * @param request * @param response * @return * @throws Exception */ @RequestMapping("/getById") public String getById(@RequestParam(value = "id") Integer id, HttpServletRequest request, HttpServletResponse response) throws Exception { Post post = postService.getPostById(id); request.setAttribute("postContent", post.getContent()); return "postContent"; } } 

2.2.3 DeptController

在包 com.shiyanlou.controller 下新建一個類 DeptController,代碼如下:

package com.shiyanlou.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.shiyanlou.domain.Department; import com.shiyanlou.service.DepartmentService; import com.shiyanlou.util.ResponseUtil; /**類中的所有響應方法都被映射到 /dept 路徑下 * * @author shiyanlou * */ @Controller @RequestMapping("/dept") public class DeptController { // 自動注入 departmentService @Resource private DepartmentService departmentService; /**處理查詢部門請求 * * @param department * @param response * @return * @throws Exception */ @RequestMapping("/list") public String list(Department department, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); // 判斷查詢條件是否為空,如果是,對條件做數據庫模糊查詢的處理 if (department.getName() != null && !"".equals(department.getName().trim())) { map.put("name", "%" + department.getName() + "%"); } List<Department> deptList = departmentService.findDepartments(map); Integer total = departmentService.getCount(map); JSONObject result = new JSONObject(); JSONArray jsonArray = JSONArray.fromObject(deptList); result.put("rows", jsonArray); result.put("total", total); ResponseUtil.write(response, result); return null; } /**處理保存部門請求 * * @param department * @param request * @param response * @return * @throws Exception */ @RequestMapping("/save") public String save(Department department, HttpServletRequest request, HttpServletResponse response) throws Exception { int resultTotal = 0; // 如果 id 不為空,則添加部門,否則修改部門 if (department.getId() == null) resultTotal = departmentService.addDepartment(department); else resultTotal = departmentService.updateDepartment(department); JSONObject result = new JSONObject(); if (resultTotal > 0) { result.put("success", true); } else { result.put("success", false); } ResponseUtil.write(response, result); return null; } /**處理刪除部門請求 * * @param ids * @param response * @return * @throws Exception */ @RequestMapping("/delete") public String delete(@RequestParam(value = "ids") String ids, HttpServletResponse response) throws Exception { JSONObject result = new JSONObject(); // 將要刪除的部門的 id 進行處理 String[] idsStr = ids.split(","); for (int i = 0; i < idsStr.length; i++) { // 捕獲 service 層拋出的異常,如果捕獲到則置 success 值為 false,返回給前端 try { departmentService.deleteDepartment(Integer.parseInt(idsStr[i])); result.put("success", true); } catch (Exception e) { result.put("success", false); } } ResponseUtil.write(response, result); return null; } /**處理獲得部門 id 與 name 請求,用於前端 easyUI combobox 的顯示 * * @param request * @return */ @RequestMapping("/getcombobox") @ResponseBody public JSONArray getDept(HttpServletRequest request) { Map<String, Object> map = new HashMap<String, Object>(); List<Department> deptList = departmentService.findDepartments(map); List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (Department dept : deptList) { Map<String, Object> result = new HashMap<String, Object>(); result.put("id", dept.getId()); result.put("name", dept.getName()); list.add(result); } // 返回 JSON JSONArray jsonArray = JSONArray.fromObject(list); return jsonArray; } } 

2.2.4 PositionController

在包 com.shiyanlou.controller 下新建一個類 PositionController,代碼如下:

package com.shiyanlou.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.shiyanlou.domain.Position; import com.shiyanlou.service.PositionService; import com.shiyanlou.util.ResponseUtil; /**類中的所有響應方法都被映射到 /position 路徑下 * * @author shiyanlou * */ @Controller @RequestMapping("/position") public class PositionController { // 自動注入 positionService @Resource private PositionService positionService; /**處理查詢職位請求 * * @param position * @param response * @return * @throws Exception */ @RequestMapping("/list") public String list(Position position, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); // 判斷查詢條件是否為空,如果是,對條件做數據庫模糊查詢的處理 if (position.getName() != null && !"".equals(position.getName().trim())) { map.put("name", "%" + position.getName() + "%"); } List<Position> dpositionList = positionService.findPositions(map); Integer total = positionService.getCount(map); JSONObject result = new JSONObject(); JSONArray jsonArray = JSONArray.fromObject(dpositionList); result.put("rows", jsonArray); result.put("total", total); ResponseUtil.write(response, result); return null; } /**處理保存職位請求 * * @param position * @param request * @param response * @return * @throws Exception */ @RequestMapping("/save") public String save(Position position, HttpServletRequest request, HttpServletResponse response) throws Exception { int resultTotal = 0; // 如果 id 不為空,則添加職位,否則修改職位 if (position.getId() == null) resultTotal = positionService.addPosition(position); else resultTotal = positionService.updatePosition(position); JSONObject result = new JSONObject(); if (resultTotal > 0) { result.put("success", true); } else { result.put("success", false); } ResponseUtil.write(response, result); return null; } /**處理刪除職位請求 * * @param ids * @param response * @return * @throws Exception */ @RequestMapping("/delete") public String delete(@RequestParam(value = "ids") String ids, HttpServletResponse response) throws Exception { JSONObject result = new JSONObject(); // 將要刪除的部門的 id 進行處理 String[] idsStr = ids.split(","); for (int i = 0; i < idsStr.length; i++) { // 捕獲 service 層拋出的異常,如果捕獲到則置 success 值為 false,返回給前端 try { positionService.deletePosition(Integer.parseInt(idsStr[i])); result.put("success", true); } catch (Exception e) { result.put("success", false); } } ResponseUtil.write(response, result); return null; } /**處理獲得職位 id 與 name 請求,用於前端 easyUI combobox 的顯示 * * @param request * @return */ @RequestMapping("/getcombobox") @ResponseBody public JSONArray getPos(HttpServletRequest request) { Map<String, Object> map = new HashMap<String, Object>(); List<Position> posList = positionService.findPositions(map); List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (Position pos : posList) { Map<String, Object> result = new HashMap<String, Object>(); result.put("id", pos.getId()); result.put("name", pos.getName()); list.add(result); } // 返回 JSON JSONArray jsonArray = JSONArray.fromObject(list); return jsonArray; } } 

2.2.5 EmployeeController

在包 com.shiyanlou.controller 下新建一個類 EmployeeController,代碼如下:

package com.shiyanlou.controller; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.shiyanlou.domain.Employee; import com.shiyanlou.domain.Post; import com.shiyanlou.service.EmployeeService; import com.shiyanlou.util.IntegrateObject; import com.shiyanlou.util.JsonDateValueProcessor; import com.shiyanlou.util.ResponseUtil; /**類中的所有響應方法都被映射到 /empl 路徑下 * * @author shiyanlou * */ @Controller @RequestMapping("/empl") public class EmployeeController { // 自動注入 employeeService @Resource private EmployeeService employeeService; /**處理查詢員工請求 * * @param employee * @param request * @param response * @return * @throws Exception */ @RequestMapping("/list") public String list(Employee employee, HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); // 判斷查詢條件是否為空,如果是,對條件做數據庫模糊查詢的處理 if (employee.getId() != null && !"".equals(employee.getId().trim())) { map.put("id", "%" + employee.getId() + "%"); } if (employee.getName() != null && !"".equals(employee.getName().trim())) { map.put("name", "%" + employee.getName() + "%"); } if (employee.getSex() != null && !"".equals(employee.getSex().trim())) { map.put("sex", "%" + employee.getSex() + "%"); } if (employee.getDepartment() != null) { if (employee.getDepartment().getName() != null && !"".equals(employee.getDepartment().getName().trim())) { map.put("department_name", "%" + employee.getDepartment().getName() + "%"); } } if (employee.getPosition() != null) { if (employee.getPosition().getName() != null && !"".equals(employee.getPosition().getName().trim())) { map.put("position_name", "%" + employee.getPosition().getName() + "%"); } } List<Post> postList = employeeService.findEmployees(map); Integer total = employeeService.getCount(map); // 處理日期使之能在 easyUI 的 datagrid 中正常顯示 JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor()); JSONObject result = new JSONObject(); JSONArray jsonArray = JSONArray.fromObject(postList, jsonConfig); result.put("rows", jsonArray); result.put("total", total); ResponseUtil.write(response, result); return null; } /**處理保存員工請求 * * @param dept_id * @param pos_id * @param updateFlag * @param employee * @param request * @param response * @param session * @return * @throws Exception */ @RequestMapping("/save") public String save(@RequestParam("dept_id") Integer dept_id, @RequestParam("pos_id") Integer pos_id, @RequestParam("updateFlag") String updateFlag, Employee employee, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception { int resultTotal = 0; // 完成 Department 和 Position 在 Employee 中的關聯映射 IntegrateObject.genericAssociation(dept_id, pos_id, employee); JSONObject result = new JSONObject(); // 根據 updateFlag 的值,判斷保存方式,如果值為 no,則添加員工,如果值為 yes,則修改員工 if (updateFlag.equals("no")){ // 捕獲 service 層插入時主鍵重復拋出的異常,如果捕獲到則置 success 值為 false,返回給前端 try { resultTotal = employeeService.addEmployee(employee); if (resultTotal > 0) { result.put("success", true); } else { result.put("success", false); } } catch (Exception e) { result.put("success", false); } }else if(updateFlag.equals("yes")){ resultTotal = employeeService.updateEmployee(employee); if (resultTotal > 0) { result.put("success", true); } else { result.put("success", false); } } ResponseUtil.write(response, result); return null; } /**處理刪除員工請求 * * @param ids * @param response * @param session * @return * @throws Exception */ @RequestMapping("/delete") public String delete(@RequestParam(value = "ids") String ids, HttpServletResponse response, HttpSession session) throws Exception { JSONObject result = new JSONObject(); // 將要刪除的部門的 id 進行處理 String[] idsStr = ids.split(","); for (int i = 0; i < idsStr.length; i++) { employeeService.deleteEmployee(idsStr[i]); } result.put("success", true); ResponseUtil.write(response, result); return null; } /**springmvc 日期綁定 * * @param binder */ @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); CustomDateEditor editor = new CustomDateEditor(dateFormat, true); binder.registerCustomEditor(Date.class, editor); } } 

三、實驗總結

到這里我們就完成了 Controller 層的代碼實現,下一節我們將完成表現層 JSP 頁面的實現。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM