Ни BindingResult, ни простой целевой объект для имени компонента 'userProfile' не доступны в качестве атрибута запроса - PullRequest
2 голосов
/ 26 сентября 2011

Я встретил следующее исключение, когда пытался реализовать свое первое веб-приложение spring + hibernate:

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'userProfile' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
    at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
    at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
    at org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
    ...

UserController.java:

@Controller
public class UserController {

    @Autowired
    private UserProfileService userProfileService;

    public UserController(){

    }

    @RequestMapping(value="/add", method=RequestMethod.POST)
    public String registerUser(@ModelAttribute("userProfile") UserProfile userProfile, BindingResult result, Map model){

        userProfileService.addUserProfile(userProfile);

        return "redirect:/login";
    }
    ...
}

UserProfile.java

@Entity
@Table(name="USER_PROFILE")
public class UserProfile {
    @Id
    @GeneratedValue
    @Column(name = "ID")
    private Long id;

    @Column(name = "USERNAME")
    private String userName;

    @Column(name = "PASSWORD")
    private String password;

    //sets and gets
}

index.jsp

<form:form method="post" action="add" commandName="userProfile">
    <table>
        <tr>
            <td><form:label path="userName"><spring:message code="label.username" /></form:label></td>
            <td><form:input path="userName" /></td>
        </tr>
        <tr>
            <td><form:label path="password"><spring:message code="label.password" /></form:label></td>
            <td><form:password path="password" /></td>
        </tr>
        <tr>
            <td><input type="submit" value="<spring:message code="label.adduser" />"></td>
        </tr>
    </table>
</form:form>

Ответы [ 5 ]

2 голосов
/ 26 сентября 2011

Я не заметил, что мне нужно реализовать метод для создания формы, который будет предоставлять экземпляр UserProfile.Я добавил 2 метода, и теперь все работает отлично.

@RequestMapping("/")
public String home() {
    return "redirect:/index";
}

@RequestMapping(value = "/index", method = RequestMethod.GET)
public String createRegisterForm(Map<String, Object> model){
    model.put("userprofile", new UserProfile());
    return "index";
}
1 голос
/ 31 мая 2012

Добавьте modelAttribute="userProfile" к тегу <form:form>.

<form:form method="post" action="add" commandName="userProfile" modelAttribute="userProfile">
0 голосов
/ 08 апреля 2014
@ModelAttribute("userProfile")
public UserProfile getProfile(){
    return new UserProfile();
}
<form:form method="post" action="add" modelAttribute="userProfile">
0 голосов
/ 05 сентября 2012

Добавление этого в ваш контроллер должно исправить это

model.addAttribute(new UserProfile());
0 голосов
/ 26 сентября 2011

Попробуйте добавить BindingResult в качестве параметра метода рядом с @ModelAttribute("userProfile") UserProfile userProfile

Spring ищет параметр BindingResult после каждого @ ModelAttribute

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...