Problem passing Polled Bean to controller and insert into DB using Java with Spring mvc

2

I would like you to help me with this problem that is occurring in my application.

The following is the code below:

 package br.com.estoque.Controller;


 import java.util.Map;

 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
 import org.springframework.ui.ModelMap;
 import org.springframework.validation.BindingResult;
 import org.springframework.web.bind.annotation.ModelAttribute;
 import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import br.com.estoque.Dao.CategoriaProdutoDao;
import br.com.estoque.Dao.ProdutoDao;
import br.com.estoque.Modelo.Produto;

@Controller
public class ProdutoController {

@RequestMapping("produtoForm")
public ModelAndView entradaForm(){
    ModelAndView mav = new ModelAndView();
    CategoriaProdutoDao dao = new CategoriaProdutoDao();
    mav.setViewName("produtos/frmCadastroProduto");
    mav.addObject("lista",dao.listar());
    mav.addObject("produto",new Produto());
    return mav;

}

@RequestMapping(value = "/inserirProduto", method = RequestMethod.POST)
public String save(@ModelAttribute("produto") Produto produto){
    ProdutoDao dao = new ProdutoDao();      
    dao.adiciona(produto);
    return "produtos/frmCadastroProduto";
}


}

My productMarketProduct

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration</title>
</head>
<body>
    <div align="center">
        <form:form action="inserirProduto" method="post" modelAttribute="produto">

            <table border="0">   

            <tr>
        <td><form:label path="descricao">Nome Produto</form:label></td>
        <td><form:input path="descricao" /></td>
    </tr>
    <tr>
        <td><form:label path="categoriaProduto">Selecione a categoria de produto</form:label></td>
        <td><form:select path="categoriaProduto">
            <form:option value=" - " label="--Please Select"></form:option>
            <form:options items="${lista}" itemValue="cdCategoriaProduto" itemLabel="descricao"/>
        </form:select>
        </td>
    </tr>


                <tr>
                    <td colspan="2" align="center"><input type="submit" value="Register" /></td>
                </tr>
            </table>


        </form:form>
    </div>
</body>
</html>

Error that is coming back to me ...

    
asked by anonymous 17.09.2014 / 04:16

2 answers

3

The problem appears to be caused because you have a kind of "complex" CategoriaProduto as% attribute Produto being mapped to a single value field, ie, the "combo" whose value of the options is based cdCategoriaProduto .

I assumed this by the produto.getCategoriaProduto().getCdCategoriaProduto() stretch.

Unless you have done the configuration of a binder elsewhere, Spring will see that the information submitted in the request is not compatible with your model received by parameter, then explaining error 400 that the request is syntactically incorrect .

What is the solution?

1. Use a "Simple" attribute

Create a codigoCategoria attribute of type String or numeric to receive the value of the form instead of using a class of yours.

If you need to retrieve other information from the category, use the code to retrieve the session or database value.

2. Create an Editor

The Spring allows you to set a special class for automatic conversion for the binding request your model .

Here is an example ( that caught the SOEN ):

public class GroupEditor extends PropertyEditorSupport{

    private final GroupService groupService;

    public GroupEditor(GroupService groupService){
        this.groupService= groupService;
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
      Group group = groupService.getById(Integer.parseInt(text));
      setValue(group);
    }
}

The setAsText method is used during request . It will get the value of the field (the code, in your case) and then you must retrieve the corresponding CategoriaProduto object.

Note that this groupService of the example would be a bean responsible for fetching the value in the database, for example.

Finally, you set Spring to use the above class in its Controller as follows:

@InitBinder
protected void initBinder(WebDataBinder binder)     {
      binder.registerCustomEditor(Group.class, new GroupEditor(groupService));
}

Adapt this code to your classes.

    
18.09.2014 / 13:14
0

This is your method

@RequestMapping(value = "/inserirProduto", method = RequestMethod.POST)
public String save(@ModelAttribute("produto") Produto produto){
//sua logica aqui
}

Note that you are sent via post, so it should look like this:

@RequestMapping(value = {"/inserirProduto,""}, method = RequestMethod.POST)
public String save(@RequestBody Produto produto){
// sua logica aqu
}

When the pop spring comes to you, since you are using post then you have to use @RequestBody , note also the use of {} in @RequestMapping .

This will work correctly.

    
22.09.2016 / 19:43