【ssm框架】增刪改查的最佳實踐
在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這個註解的作用是什麼呢?他有兩個值,required和value,其中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;
}