【ssm框架】增删改查的最佳实践

来源:互联网 发布:贵州广电网络节目表 编辑:程序博客网 时间:2024/06/08 19:19

在javaweb网站项目开发的过程当中,增删改查一直是最主要的内容,下面是经过最近的项目实战总结出来的一套SSM框架进行增删改查的架构。

 

我们知道,利用controller可以跳转页面,同时带上我们处理后得到的数据。

在controller中我们可以设置这样一段代码

@ModelAttribute("user")    public User get(@RequestParam(required= false, value = "id") Long id) throws Exception {        if (id != null && id >0) {            returnuserService.queryById(id);        } else {            return new User();        }    }

@RequestParam这个注解的作用是什么呢?他有两个值,requiredvalue,其中value将和我们前台传入的参数进行对应,比如前台传入id=1,就会被这里获取到。required可以设置为true或者false,为true时,表示必须传入这个参数,如果前台没有传入id这个参数,则会报错。如果如果设置为false则传或者不传都可以。

 

注意到方法的上面还有一个注解@ModelAttribute注解。@ModelAttribute的使用方法有多种。其中一种是标记在方法上面的@ModelAttribute,还有一种是标记在方法参数前面的@ModelAttribute。

标记@ModelAttribute的方法,会在各种请求之前执行。也就是说,即使请求对应的是其他方法,标记@ModelAttribute的方法也会在这之前执行。它可以有返回值,也就是说他可以返回各种各样的东西

标记@ModelAttribute的参数,会优先去获得标记了@ModelAttribute的方法的返回值来填充。上面的get方法中标记了@ModelAttribute("user"),那么如果我有另外一个方法的参数是@ModelAttribute User user,这个方法在被调用的时候就会先执行get方法来填充user。

 

那怎么把参数传到前台页面进行展示呢?比如我们要把user对象传到前台,可以在方法参数中添加一个Model model,ssm框架会自动帮我们获取,然后我们只需要调用model.addAttribute(“user”,user),这样下一个页面就会获取到我们传过去的user对象了。

前台获取到对象之后进行数据的展示的方法也很简单。直接${user.id},${user.name}这样,框架会帮我们解析并显示。


前端代码:

<tr>    <td><label>用户名称</label></td>    <td><inputclass="easyui-textbox" type="text"name="username" value="${user.username}"data-options="required:true" style="width: 200px;" /></td></tr><tr>    <td><label>用户账号</label></td>    <td><inputclass="easyui-textbox" type="text" name="account"value="${user.account}" data-options="required:true"style="width: 200px;" /></td></tr><tr>    <td><label>用户密码</label></td>    <td><inputtype="password" class="easyui-validatebox"id="pwd" name="pwd" style="width: 200px;"/></td></tr><tr>    <td><label>确认密码</label></td>    <td><inputtype="password" class="easyui-validatebox"name="rpassword" validType="equals['#pwd']"style="width: 200px;" /></td></tr>

后端代码:

public class EUDataGridResult {   private long total;   private List<?> rows;   public long getTotal() {      return total;   }   public void setTotal(long total) {      this.total = total;   }   public List<?> getRows() {      return rows;   }   public void setRows(List<?>rows) {      this.rows = rows;   }} @Controller@RequestMapping("/console/user")public class UserController extends BaseController{    @Autowired    private UserService userService;    @ModelAttribute("user")    public Userget(@RequestParam(required = false, value = "id") Long id) throwsException {        if (id != null && id >0) {            returnuserService.queryById(id);        } else {            return new User();        }    }    @RequestMapping(value ="/list", produces = "text/html;charset=utf-8", method =RequestMethod.GET)    public String listView(Model model) {        return"console/user/list";    }    @RequestMapping(value ="/list.json", produces = "application/json;charset=utf-8")    @ResponseBody    public EUDataGridResult list(Integerpage, Integer rows, String keywords, UserType type){        EUDataGridResult result = newEUDataGridResult();        try {            PageInfo<User> pageInfo= userService.listByPage(page, rows, keywords, type);            result.setTotal(pageInfo.getTotal());           result.setRows(pageInfo.getList());        } catch (Exception e) {            e.printStackTrace();        }        return result;    }    @RequestMapping(value ={"/add", "/edit"}, produces ="text/html;charset=utf-8", method = RequestMethod.GET)    public String edit(@ModelAttributeUser user, Model model) throws Exception {       model.addAttribute("types", UserType.values());       model.addAttribute("user", user);        return"console/user/edit";    }    @RequestMapping(value ="/edit", produces = "application/json;charset=utf-8",method = RequestMethod.POST)    @ResponseBody    public EUResult form(@ModelAttributeUser user, String pwd) {        EUResult result = new EUResult();        try {            if (userService.checkAccount(user)){                result =EUResult.build(EUResult.FAIL, "用户账号已存在,请重新输入!");            } else {                if (user.getId() != null&& user.getId() > 0) {                   //编辑逻辑                } else {                    //新增逻辑                }               result.setStatus(EUResult.OK);                result.setMsg("用户信息保存成功!");            }        } catch (Exception ex) {           result.setStatus(EUResult.FAIL);            result.setMsg(ex.getMessage());        }        return result;    }    @RequestMapping(value ="/delete", method = RequestMethod.POST, produces ="application/json;charset=utf-8")    @ResponseBody    public EUResult delete(String ids) {        EUResult result = new EUResult();        if (StringUtils.isNotEmpty(ids)){            List<Long> idsArry =Arrays.asList(CommonUtils.getIdsArray(ids));            try {               result.setStatus(EUResult.OK);                String msg ="";                for (Long id : idsArry) {                    msg = msg +userService.deleteOnCheck(id) + "<br>";                }                result.setMsg(msg);             } catch (Exception e) {               result.setStatus(EUResult.FAIL);                result.setMsg("删除用户时发生异常!" + e.getMessage());            }        } else {           result.setStatus(EUResult.FAIL);            result.setMsg("请选择要删除的用户!");        }        return result;    } 

原创粉丝点击