登録・更新処理
登録・更新はhidden項目に_idがあるかどうかで判断しています。
(セキュリティ的にはセッションに_idに入れておくとか、DESで暗号化したものをhiddenに入れろとかツッコミは甘んじてお受けします)
MongoDBではsaveメソッドを使うと、_idがMongoDB内にあるときにはupdate、_idがないときにはinsertを発行してくれます。
そのsaveメソッドに渡すものはBasicDBObjectを渡すのですが、この時に引数にMapを渡しています。
Mapの中身は列名をkeyにしたmapを作ります。
DBへの書き込みが完了したあとは、http://localhost:8080/sample/ へリダイレクトさせています。
リダイレクト時には、redirect: とします。
…あ、MongoDBの例外が発生した時のハンドリングを忘れたので、実装しなきゃ。
Controllerクラスの中身
@RequestMapping(value = "/edit", method = RequestMethod.POST) public String regist(@Valid EditPage page, BindingResult bindingResult, Model model ){ // エラーチェック if(!isValid(page, bindingResult)){ logger.debug(bindingResult.getObjectName()); return "edit"; } // DBに登録 ServerBean bean = new ServerBean(); if(StringUtils.hasText(page.getId())){ bean.setId(new ObjectId(page.getId())); } bean.setIps(page.getIps()); bean.setOs(page.getOs()); bean.setServerName(page.getServerName()); Map<String, String> softMap = new HashMap<String, String>(); List<String> softList = page.getSoftName(); List<String> verList = page.getSoftVersion(); int size = softList.size(); for(int i = 0 ; i < size ; i++){ softMap.put(softList.get(i), verList.get(i)); } bean.setSoft(softMap); bean.setCreated(page.getCreated()); bean.setUpdated(new Date()); new ServersDao().save(bean, getDb()); return "redirect:/"; }
ServersDaoクラスの中身
public void save(ServerBean bean, DB db){ DBCollection collection = db.getCollection(COLLECTION_NAME); // saveメソッドはinsert,updateを判断してくれるので便利 collection.save(new BasicDBObject(bean.toMap())); }