相关疑难解决方法(0)

@ModelAttribute注释,什么时候使用它?

假设我们有一个实体Person,一个控制器PersonController和一个edit.jsp页面(创建一个新的或编辑一个现有的人)

调节器

@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String editPerson(@RequestParam("fname") String fname, Model model) {
    if(fname == null || fname.length() == 0){
        model.addAttribute("personToEditOrCreate", new Person());
    }
    else{
        Person p = personService.getPersonByFirstName(fname);
        model.addAttribute("personToEditOrCreate", p);
    }

    return "persons/edit";
}

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String savePerson(Person person, BindingResult result) {

    personService.savePerson(person);
    return "redirect:/home";
}
Run Code Online (Sandbox Code Playgroud)

文件edit.jsp

<form:form method="post" modelAttribute="personToEditOrCreate" action="save">
    <form:hidden path="id"/> 
    <table>
        <tr>
            <td><form:label path="firstName">First Name</form:label></td>
            <td><form:input path="firstName" /></td>
        </tr>
        <tr>
            <td><form:label path="lastName">Last Name</form:label></td>
            <td><form:input path="lastName" /></td>
        </tr>
        <tr> …
Run Code Online (Sandbox Code Playgroud)

annotations spring-mvc

35
推荐指数
1
解决办法
8万
查看次数

从 Spring 的 Rest 控制器同时支持 application/json 和 application/x-www-form-urlencoded

我正在编写一个 REST 端点,它需要同时支持 application/x-www-form-urlencoded 和 application/json 作为请求正文。我做了以下配置,

@RequestMapping(method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE }, consumes = {          
        MediaType.APPLICATION_FORM_URLENCODED_VALUE, MediaType.APPLICATION_JSON_VALUE }, path = Constants.ACCESS_TOKEN_V1_ENDPOINT)
public OAuth2Authorization createAccessTokenPost(
        @RequestBody(required = false) MultiValueMap<String, String> paramMap) { ..
Run Code Online (Sandbox Code Playgroud)

虽然它单独支持 application/x-www-form-urlencoded 或 application/json (当我从 Consumers = {} 注释掉一种内容类型时),但它不能同时支持两者。有任何想法吗 ?

spring spring-restcontroller

6
推荐指数
2
解决办法
5699
查看次数