基于SSM框架和easyUI框架的简易人事管理系统(五)

基于SSM框架和easyUI框架的简易人事管理系统(五)

Controller的编写

Admin

package controller;

import domain.Admin;
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 service.AdminService;
import util.ResponseUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类中的所有响应方法都被映射到 /admin 路径下
 */
@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", "请检查用户名和密码!");
            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";
    }
}

Dept

package controller;

import domain.Department;
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 service.DepartmentService;
import util.ResponseUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**类中的所有响应方法都被映射到 /dept 路径下
 */
@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;
    }
}


Employee

package controller;

import domain.Employee;
import domain.Post;
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 service.EmployeeService;
import util.IntegrateObject;
import util.JsonDateValueProcessor;
import util.ResponseUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**类中的所有响应方法都被映射到 /empl 路径下
 *
 */
@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 HH:mm:ss");
        CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
        binder.registerCustomEditor(Date.class, editor);
    }

}


Position

package controller;

import domain.Position;
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 service.PositionService;
import util.ResponseUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**类中的所有响应方法都被映射到 /position 路径下
 *
 */
@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;
    }
}

Post

package controller;

import domain.Admin;
import domain.Post;
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 service.PostService;
import util.DateUtil;
import util.JsonDateValueProcessor;
import util.ResponseUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**类中的所有响应方法都被映射到 /post 路径下
 *
 */
@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";
    }
}


springmvc配置文件

代码层都写好了想要调用还是要配置好配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 自动扫描该包,Spring MVC 会将包下用 @Controller 注解的类注册为 Spring 的 controller -->
    <context:component-scan base-package="controller" />
    <!-- 设置默认配置方案 -->
    <mvc:annotation-driven />
    <!-- 静态资源访问 -->
    <mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/css/**" location="/css/"/>
    <mvc:resources mapping="/images/**" location="/images/"/>
    <mvc:resources location="/jquery-easyui-1.3.3/demo/" mapping="/demo/**"/>
    <mvc:resources location="/jquery-easyui-1.3.3/themes/" mapping="/themes/**"/>
    <mvc:resources location="/jquery-easyui-1.3.3/locale/" mapping="/locale/**"/>


        <!-- 视图解析器 -->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="3500000" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
    <!-- 配置拦截器 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/*" />
            <bean class="interceptor.LoginInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

现在基本ssm框架的都算是写好了,至于日志文件和jdbc的配置大家应该还是都知道的,不知道的百度下好了,其中有什么问题和新的见解的可以提出来,大家一起讨论

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值