3

stackoverflowに関する最初の投稿...私はSpringMVCをいじり始めており、エンティティを可能な限りステートレスなWebビューにリンクするための最良のアプローチを見つけようとしていました。

私が見つけた1つの方法は、パラメーターで(リクエストから)エンティティIDを受け取るメソッドで@ModelAttributeを使用することです。これは、サービス/永続層からエンティティIDを見つけ、それを返し、モデルのモデルに挿入されます。現在のリクエスト。

さらに、Spring MVCは、エンティティのフィールドに一致するすべての着信パラメーターをバインドし、その値を(WebDataBinderを介して)自動的に更新します。

私の質問は、この最後の行動に関するものです。クライアントによってデータが投稿されたときにエンティティが更新されると便利です。しかし、私は単純なGETリクエスト(私は読み取り専用と見なします)ではそれを避けたいと思います。現在の動作では、このようなリクエストのクエリにパラメータを追加することでエンティティを更新できますが、これはセキュリティの問題である可能性があります。

dataBinder.setAllowedFields()などについては知っていますが、任意のGETリクエストをマッピングする任意の種類のフィールドを無効にする方法を希望します。それを行う方法はありますか?

ありがとう!

編集:私が探しているものをより明確にするためにサンプルプロトタイプを追加しました...

@ModelAttribute Entity retrieveEntity(@RequestParam(required=true) Long id) {
    // This is called before the request handler and before parameters are mapped to the entity
    return entityRepository.get(id);
}

@RequestMapping(value="/modify", method=RequestMethod.POST) 
public ModelAndView handleModifyRequest(@ModelAttribute Entity entity) {
    // Here, I want my entity to reflect the parameters passed in the posted form (this works)
    ....
}

@RequestMapping(value="/read", method=RequestMethod.GET) 
public ModelAndView handleReadRequest(@ModelAttribute Entity entity) {
    // Here, I DON'T want my entity to reflect the parameters passed in the URL (which is what happens...)
    ....
}
4

1 に答える 1

2

最後に、リクエストハンドラーメソッドがModelAttributeパラメーターを受け取る場合にのみパラメーターのマッピングが行われるように見えるため、このようなものを使用することにしました。

@ModelAttribute Entity retrieveEntity(@RequestParam(required=true) Long id) {
    return entityRepository.get(id);
}

@RequestMapping(value="/modify", method=RequestMethod.POST) 
public ModelAndView handleModifyRequest(@ModelAttribute Entity entity) {
    // Here, the request parameters have been mapped to the entity
    ....
}

@RequestMapping(value="/read", method=RequestMethod.GET) 
public ModelAndView handleReadRequest(ModelMap model) {
    // This will avoid any parameter mapping to the entity
    Entity entity = (Entity)model.get("entity");
    ....
}

より良い解決策は大歓迎です!ありがとう

于 2012-10-23T00:38:12.637 に答える