彤筹网ssm(二)Day05之增删(删一个)改(普通请求)

  1. jsp
    a标签
 <a href="admin/remove/${admin.id}/${requestScope.pageInfo.pageNum}" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i></a>
  1. Handler
/**
     * 普通请求 实现单条删除
     * @param adminId
     * @param pageNum
     * @return
     */
    @RequestMapping("/admin/remove/{adminId}/{pageNum}")
    public String remove(
            @PathVariable("adminId") Integer adminId,
            @PathVariable("pageNum") Integer pageNum
            ){
    
    
        adminService.remove(adminId);
            return "redirect:/admin/get/page?pageNum="+pageNum; // 保持原本所在页面和查询关键字参数
    }
  1. Service
/**
     * 普通请求单一删除
     * @param adminId
     * @return
     */
    @Override
    public int remove(Integer adminId) {
    
    
        return adminMapper.deleteByPrimaryKey(adminId);
    }

  1. 数据库修改字段唯一约束

ALTER TABLE ssm2_tongchou.t_admin ADD UNIQUE INDEX (login_acct);

  1. admin-page.jsp新增按钮
<a href="admin/to/add/page" class="btn btn-primary" style="float:right;"><i class="glyphicon glyphicon-plus"></i> 新增</a>
  1. 跳转访问内部资源<`view-controller
<!--    前往新增管理员页面-->
    <mvc:view-controller path="/admin/to/add/page" view-name="admin-add"/>
  1. 准备admin-add.jsp页面
<div class="container-fluid">
    <div class="row">
        <%--        sidebar--%>
        <%@include file="/WEB-INF/include-sidebar.jsp" %>
            <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
                <ol class="breadcrumb">
                    <li><a href="/admin/to/main/page">首页</a></li>
                    <li><a href="/admin/get/page">数据分页列表</a></li>
                    <li class="active">新增</li>opppp
                </ol>
                <div class="panel panel-default">
                    <div class="panel-heading">表单数据<div style="float:right;cursor:pointer;" data-toggle="modal" data-target="#myModal"><i class="glyphicon glyphicon-question-sign"></i></div></div>
                    <div class="panel-body">
                        <form action="admin/save" method="post" role="form">
                            <p style="color: red">${requestScope.exception.message}</p>
                            <div class="form-group">
                                <label for="exampleInputPassword1">登录账号</label>
                                <input name="loginAcct" type="text" class="form-control" id="exampleInputPassword1" placeholder="请输入登录账号">
                            </div>
                            <div class="form-group">
                                <label for="exampleInputPassword1">登录密码</label>
                                <input name="userPswd" type="text" class="form-control" id="exampleInputPassword2" placeholder="请输入登录密码">
                            </div>
                            <div class="form-group">
                                <label for="exampleInputPassword1">用户昵称</label>
                                <input name="userName" type="text" class="form-control" id="exampleInputPassword3" placeholder="请输入用户昵称">
                            </div>
                            <div class="form-group">
                                <label for="exampleInputEmail">电子邮箱</label>
                                <input name="email" type="email" class="form-control" id="exampleInputEmail" placeholder="请输入邮箱地址">
                                <p class="help-block label label-warning">请输入合法的邮箱地址, 格式为: [email protected]</p>
                            </div>
                            <button type="submit" class="btn btn-success"><i class="glyphicon glyphicon-plus"></i> 新增</button>
                            <button type="reset" class="btn btn-danger"><i class="glyphicon glyphicon-refresh"></i> 重置</button>
                        </form>
                    </div>
                </div>
            </div>
    </div>
</div>

</body>
  1. Handler层
@RequestMapping("/admin/save")
    public String save(Admin admin){
    
    
        adminService.saveAdmin(admin);

        return "redirect:/admin/get/page?pageNum="+Integer.MAX_VALUE;
    }
  1. Service层
    如果新增了重复的登录名,spring则会抛出DuplicateKeyException异常。为了防止之后其他属性也添加重复,我们使用自定义异常针对当前此时的登录账号重复创建自定义异常LoginAcctAlreadyInUseException,继承RuntimeException。判断当前异常是否是DuplicateKeyException
@Override
    public int saveAdmin(Admin admin) {
    
    
//int i=1;
//i=i/0;
        String userPswd = admin.getUserPswd();
        userPswd = TongchouUtil.md5(userPswd);
        admin.setUserPswd(userPswd);

        Date date = new Date();// 生成创建时间
        String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        admin.setCreateTime(nowTime);

        int i = 0;
        try {
    
    
            i = adminMapper.insert(admin);// 保存
        } catch (Exception exception) {
    
    
            exception.printStackTrace();
            logger.info("异常全类名:"+exception.getClass().getName());
            if (exception instanceof DuplicateKeyException) {
    
     // 注意:这里判断当前异常类型是DuplicateKeyException类型才向外抛出自定义异常
                throw new LoginAcctAlreadyInUseException(TongchouConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }
        logger.debug("管理员增加成功"+i+"条");
        return i;
    }

自定义异常类LoginAcctAlreadyInUseException

/**
 * 保护或更新admin时如果检测到登录账号出现重复 则抛出异常
 * @Author Li Weitong
 * @Date 2021/1/17 16:32
 */
public class LoginAcctAlreadyInUseException extends RuntimeException{
    
    
    private static final long serialVersionUID = 1L;

    public LoginAcctAlreadyInUseException() {
    
    
        super();
    }

    public LoginAcctAlreadyInUseException(String message) {
    
    
        super(message);
    }

    public LoginAcctAlreadyInUseException(String message, Throwable cause) {
    
    
        super(message, cause);
    }

    public LoginAcctAlreadyInUseException(Throwable cause) {
    
    
        super(cause);
    }

    protected LoginAcctAlreadyInUseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
    
    
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

基于注解方式配置异常映射地TongchouExceptionResolver

/**
     * 抛出用户名已经被使用异常,通过注解配置当登录账号已经存在被使用的异常,并仍跳转到新增页面去显示警告信息
     * @param req
     * @param resp
     * @param loginAcctAlreadyInUseException
     * @return
     * @throws IOException
     */
    @ExceptionHandler(value = LoginAcctAlreadyInUseException.class)
    public ModelAndView resolveLoginAcctAlreadyInUserException(HttpServletRequest req, HttpServletResponse resp, LoginAcctAlreadyInUseException loginAcctAlreadyInUseException) throws IOException {
    
    
        String viewName = "admin-add";
        return commonResolver(viewName, req, resp,loginAcctAlreadyInUseException);
    }

基于xml配置

<!--    配置基于XML的异常映射-->
    <bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <!--        配置异常类型和具体视页面的对应关系-->
        <property name="exceptionMappings">
            <props>
                <!--                key属性执行异常全类名 标签体写对应的页面名-->
                <prop key="java.lang.Exception">system-error</prop>
<!--                访问拒绝异常拦截器映射到登录页面-->
                <prop key="com.lwt.exception.AccessForbiddenException">admin-login</prop>
                <prop key="com.lwt.exception.LoginAcctAlreadyInUseException">admin-add</prop>
            </props>
        </property>
    </bean>

  1. admin-page.jsp
<a href="admin/to/edit/page?adminId=${admin.id}&pageNum=${requestScope.pageInfo.pageNum}" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i></a>
  1. handler层去回显
@RequestMapping("/admin/to/edit/page")
    public String toEditPage(
            @RequestParam("adminId") Integer adminId,
            @RequestParam("pageNum") Integer pageNum,
            ModelMap modelMap
            ){
    
    
        Admin admin = adminService.getAdminById(adminId);
        modelMap.addAttribute("admin",admin);
        return "admin-edit";
    }
  1. service层去回显
@Override
    public Admin getAdminById(Integer adminId) {
    
    
        return adminMapper.selectByPrimaryKey(adminId);
    }
  1. admin-edit.jsp
<div class="panel panel-default">
                    <div class="panel-heading">表单数据<div style="float:right;cursor:pointer;" data-toggle="modal" data-target="#myModal"><i class="glyphicon glyphicon-question-sign"></i></div></div>
                    <div class="panel-body">
                        <form action="admin/update" method="post" role="form">
                            <input type="hidden" name="id" value="${requestScope.admin.id}">
                            <input type="hidden" name="pageNum" value="${param.pageNum}">
                            <p style="color: red">${requestScope.exception.message}</p>
                            <div class="form-group">
                                <label for="exampleInputPassword1">登录账号</label>
                                <input name="loginAcct" type="text" class="form-control" id="exampleInputPassword1" value="${requestScope.admin.loginAcct}">
                            </div>
                            <div class="form-group">
                                <label for="exampleInputPassword1">用户名称</label>
                                <input name="userName" type="text" class="form-control" id="exampleInputPassword2" value="${requestScope.admin.userName}">
                            </div>
                            <div class="form-group">
                                <label for="exampleInputEmail1">邮箱地址</label>
                                <input name="email" type="email" class="form-control" id="exampleInputEmail1" value="${requestScope.admin.email}">
                                <p class="help-block label label-warning">请输入合法的邮箱地址, 格式为: [email protected]</p>
                            </div>
                            <button type="submit" class="btn btn-success"><i class="glyphicon glyphicon-edit"></i> 修改</button>
                            <button type="reset" class="btn btn-danger"><i class="glyphicon glyphicon-refresh"></i> 重置</button>
                        </form>
                    </div>
                </div>
  1. handler层去更新
@RequestMapping("/admin/update")
    public String update(
            Admin admin,
            @RequestParam("pageNum") Integer pageNum
            ){
    
    
        adminService.update(admin);
        return "redirect:/admin/get/page?pageNum="+pageNum;
    }
  1. service层去更新
@Override
    public int update(Admin admin) {
    
    
        int i = 0;
        
        try {
    
    
            i = adminMapper.updateByPrimaryKeySelective(admin);// 有选择的更新,对应null值的字段不更新
        } catch (Exception exception) {
    
    
            exception.printStackTrace();
            if (exception instanceof DuplicateKeyException) {
    
    
                throw new LoginAcctAlreadyInUseForUpdateException(TongchouConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }
        System.out.println("您更新了"+i+"条");
        return i;
    }

猜你喜欢

转载自blog.csdn.net/m0_47119598/article/details/112747144