问题描述
我在与@SessionAttributes
的会话中存储了一个User
对象.还有一个用@ModelAttribute
装饰的简单方法,以便在会话的值为null时对其进行初始化.
I have an User
object stored in the session with @SessionAttributes
. And a straight-forward method decorated with @ModelAttribute
in order to initialize it whenever the session's value is null.
用户类别:
@Entity
@Table( name="USER")
public class User implements java.io.Serializable {
private Long id;
private String username;
private String password;
....
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name ="ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
...
控制器:
@RequestMapping("/item")
@Controller
@SessionAttributes({"user"})
public class MyController {
@ModelAttribute方法:
@ModelAttribute method:
@ModelAttribute("user")
public User createUser(Principal principal) {
return userService.findByUsername(principal.getName());
}
除此特定方法外,一切似乎都能按预期工作:
It all seems to work as expected except in this particular method:
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String showItem(@PathVariable("id") Long id, @ModelAttribute("user") User user,
Model uiModel) {
...
}
问题是使用@PathVariable("id")
设置了User.id
.我相信我也遇到了@RequestParam
这个问题.我假设这是因为两者具有相同的名称和类型.阅读 Spring的文档(见下文),我假设这是预期的行为:
The problem is that User.id
is being set with @PathVariable("id")
. I believe I ran into this with @RequestParam
too. I'm assuming that's because both have the same name and type. After reading Spring's documentation (see below) I'm assuming this is expected behavior:
但是,我认为这种情况相当普遍,其他人如何处理呢?如果我的发现是正确的,并且这是预期的行为(或错误),则似乎很容易出错.
However, I would think this scenario is fairly common, how are other people handling this? If my findings are correct and this is expected behavior (or bug), this seems to be very error prone.
可能的解决方案:
- 将
@PathVariable("id")
更改为@PathVariable("somethingElse")
.可以,但是@RequestParam并不是那么简单(例如,我不知道如何将jqgrid的请求参数ID更改为其他名称,但这是另一个问题). - 将
@PathVariable("id")
类型从Long更改为Int.这将使User.id
和id
类型不同,但是对Long的强制转换看起来很丑陋:) - 在此处不要使用
@ModelAttribute
,并再次在数据库中查询User
.与其他方法不一致,并且涉及冗余的数据库调用.
- Change
@PathVariable("id")
to@PathVariable("somethingElse")
. Works but it's not as straightforward with @RequestParam (e.g. I don't know how to change jqgrid's request parameter id to something else but this is another issue). - Change
@PathVariable("id")
type from Long to Int. This will makeUser.id
andid
types differ but the cast to Long looks ugly :) - Don't use
@ModelAttribute
here and query the DB forUser
again. Not consistent with other methods and involves redundant DB calls.
有什么建议吗?
推荐答案
这种方法怎么样-
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String showItem(@PathVariable("id") Long id,
Model uiModel) {
User user = (User)uiModel.asMap().get("user");
...
}
这篇关于@PathVariable和@ModelAttribute的值重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!