2017-09-04 61 views
0

有人建議,不應將對象ID發送到隱藏的Id標記中的視圖,因爲惡意用戶可以編輯源html並將數據提交(發佈)回錯誤記錄,並且更好的方法是將對象存儲在會話變量中,直到它返回。春季會議存儲對象

我已閱讀此SO answer但它並沒有幫助我在這個問題上。

我有一個DTO OccurencePerson存儲發生的細節和人的集合。形式控制器的設置是這樣的:

CLASS

@Component 
@Controller 
@SessionAttributes(value = { "user", "occModelView" }) 
public class FormController { 

GET HANDLER

@GetMapping("/occurence/{occeno}") 
public String findOcc(@PathVariable String occno, @ModelAttribute("occViewModel") OccViewModel occViewModel, Model model, HttpSession session, SessionStatus sessionStatus) { 

    Occurence occ = occurenceRepository.findByoccno(occno); 
    occViewModel.setOccurence(occ); 
    occViewModel.setPersons(occPersonRepository.findOccPersonByEpisode(occurence.getId())); 

    model.addAttribute("occViewModel", occViewModel); 
    session.setAttribute("occViewModel", occViewModel); 
    sessionStatus.equals(occViewModel); 
    return "occurence"; 

POST HANDLER

@PostMapping("newOccurence") 
public String episodeSubmit(@Valid @ModelAttribute OccViewModel occViewModel, BindingResult result) { 
    if (result.hasErrors()) { 
     List<ObjectError> errors = result.getAllErrors(); 
     for(ObjectError error : errors) { 
     } 
     return "occurence"; 
    } else { 
     occService.saveNewOccurence(occViewModel.getOccurence(), occViewModel.getPersons()); 
     return "redirect:/dash"; 

如何使用session vars從Hibernate返回一個對象,然後將該對象返回給Hibernate,使其不創建新對象?

現在,如果我刪除存儲發生id的html中的隱藏標籤,並將個人id和數據提交回來,它會創建一個新的發生/人員。

+1

有幾點注意事項:1.您可以使用「merge()」而不是save/persist更新現有對象的值。 2.恕我直言,可以在視圖中使用對象標識符,系統必須授權訪問權限3.只是一個想法 - JSF使用加密和簽名的視圖狀態在請求之間傳遞視圖模型。 – gusto2

+0

您的關係是否在JPA中正確註釋?你可以發佈內部occService.saveNewOccurence(),因爲我認爲你將這些對象附加到休眠會話中。 – aksappy

回答

0

你將存儲的標識在視圖模型 - 而不是將其暴露在頁面上 -

OccViewModel occViewModel - 這是你的DTO從findOcc稀少,所以纔會有屬性 -

  • 編號
  • 其他值

然後你有你的DTO的映射到JPA對象

OccViewModel存儲在會話中幷包含ID的事實意味着您可以重新引用JPA模型以確保它未在其他位置更新