N. Patial
N. Patial

Reputation: 33

Failed to convert value of type 'java.lang.String' to required type 'int'; For input string: "save"

**Resolving exception from handler [com.controller.EmpController@77cb027f]: org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "save" **

this is the controller part

 @Controller
  public class EmpController {

  private static final Logger logger = Logger
            .getLogger(EmpController.class);

    public EmpController() {
        System.out.println("EmpController()");
    } 

    @Autowired
    private EmpService service;

    @Autowired
    private UserService userservice;

    public UserService getUserservice() {
        return userservice;
    }


    public void setUserservice(UserService userservice) {
        this.userservice = userservice;
    }


    public EmpService getService() {
        return service;
    }


    public void setService(EmpService service) {
        this.service = service;
    }



    @RequestMapping(value="login", method= RequestMethod.GET)
    public ModelAndView showlogin(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav= new ModelAndView("login");
        mav.addObject("login", new User() );
        return mav;
    }


    @RequestMapping(value="loginProcess", method= RequestMethod.POST)
    public ModelAndView loginProcess(HttpServletRequest request, HttpServletResponse response,
            Model model,@ModelAttribute("login") User user) {
        ModelAndView mav = null;
        boolean user1 = userservice.validateUser(user);
        if(false != user1) {

            List<Emp> list = service.getAllEmployees();
            model.addAttribute("list", list);
            mav= new ModelAndView("empform","command",new Emp());
            mav.addObject("userId", user.getUserId());
        } else {
            mav= new ModelAndView("login");
            mav.addObject("message","UserId and Password is wrong");
        }
        return mav;
    }



    @RequestMapping(value="/empform", method= RequestMethod.GET)
    public ModelAndView showform(Model model,@ModelAttribute("emp") Emp emp) throws IOException {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");

        List<Emp> list = service.getAllEmployees();
        model.addAttribute("list", list);
        return new ModelAndView("empform","command",new Emp());

    }

   /* @RequestMapping(value="/newEmp", method= RequestMethod.GET)
    public ModelAndView newContact(ModelAndView model) { 
        Emp emp = new Emp();
        model.addObject("emp", emp);
        model.setViewName("empform");
        return model;
    }  */

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ModelAndView saveEmployee(@ModelAttribute Emp emp,Model model) {
        System.out.println(">>>>welcome to save>>>>>");
        if (emp.getEmpId() == 0) {
            service.save(emp);
        }  else { 
            service.update(emp);

        }
        List<Emp> list = service.getAllEmployees();
        model.addAttribute("list", list);
        return new ModelAndView("redirect:/empform");
    }


    @RequestMapping(value="/delete/{empId}", method= RequestMethod.GET)
    public ModelAndView delete(Model model,@PathVariable int empId) {
        service.delete(empId);
        List<Emp> list = service.getAllEmployees();
        model.addAttribute("list", list);
        return new ModelAndView("redirect:/empform");
    }


    @RequestMapping(value="/edit/{empId}")
    public ModelAndView edit(Model model,@PathVariable int empId) {
        System.out.println(">>>>>>>>>>>edit");
        Emp emp= service.getEmpById(empId);
        System.out.println(">>>>>>>>> continue edit>>>>");
        return new ModelAndView("empform","command", emp);
    }

}

this is the spring-srvlet.xml

    <context:component-scan base-package="com.controller">
     </context:component-scan>  

       <bean 
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">  

   <property name="prefix" value="/WEB-INF/"></property>  
   <property name="suffix" value=".jsp"></property>  
    </bean>  

     <bean id="dataSource" 
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
    <property name="driverClassName" value="com.mysql.jdbc.Driver">
    </property>  
    <property name="url" value="jdbc:mysql://10.125.129.252:3306/nehaempdb">
     </property>  
   <property name="username" value="root"></property>  
   <property name="password" value="admin"></property>  
   </bean>  

    <bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="hibernateProperties">
        <props>
            <prop 
        key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.format_sql">true</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
    <property name="packagesToScan" value="com.model"></property>
</bean>

<bean id="service" class="com.service.EmpService">  

</bean>

<bean id="userservice" class="com.service.UserService">   
</bean>

<bean id="dao" class="com.dao.EmpDao"> 
</bean> 
<bean id="userdao" class="com.dao.UserDao"> 
</bean> 

<!-- Transaction -->
<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

this is .jsp

<div align="center">
        <h1>New/Edit Employee</h1>
        <form:form action="save" method="post" >
        <table>
            <form:hidden path="empId"/>
            <tr>
                <td>Name:</td>
                <td><form:input path="empName" /></td>
            </tr>
            <tr>
                <td>Salary:</td>
                <td><form:input path="salary" /></td>
            </tr>
            <tr>
                <td>DeptId:</td>
                <td><form:input path="deptId" /></td>
            </tr>

            <tr>
                <td colspan="2" align="center"><input type="submit" value="Save"></td>
            </tr>
        </table>
        </form:form>
    </div>

    value="Save"></td>
        </tr>
    </table>
    </form:form>
</div>

Upvotes: 1

Views: 23377

Answers (4)

AbdullahAltamimi
AbdullahAltamimi

Reputation: 11

you need to check method type .. may you try to @GET some service from Postman but in real app it's a @POST service .. The error is not clear at first time.

Upvotes: 1

Rodolfo Bortoluzzi
Rodolfo Bortoluzzi

Reputation: 1

I had the same problem, but the solution for me was simple: In the following code I forgot the first / in / admin / products when I was updating the history with history.push ('/ admin / products');

My code:

useEffect(() => {
    if (isEditing) {
        makeRequest({ url: `/products/${productId}` })
            .then(response => {
                setValue('name', response.data.name);
                setValue('price', response.data.price);
                setValue('description', response.data.description);
                setValue('imgUrl', response.data.imgUrl);
            })
    }
}, [productId, isEditing, setValue]);

const onSubmit = (data: FormState) => {
    makePrivateRequest({
        url: isEditing ? `/products/${productId}` : '/products', 
        method: isEditing ? 'PUT' : 'POST', 
        data
    })
    .then(() => {
        toast.info('Produto salvo com sucesso!');
        history.push('/admin/products');
    })
    .catch(() => {
        toast.error('Erro ao salvar produto!');
    })
}

Upvotes: 0

Holzberg
Holzberg

Reputation: 171

I had this same problem and Plog is correct about having a numeric route map.

However, instead of changing "/{id}" to "/something/{id}", you can change it "/{id:\\d+}" and then it won't match "/save".

I use the numeric regex for all "/id" cases so that I don't have this problem. For example "/users/25" and "/users/forgotpassword".

Upvotes: 1

Plog
Plog

Reputation: 9612

It sounds to me like you probably have a @RequestMapping to a resource something like "/{id}" and when you are trying to hit your "/save" resource instead of mapping it to your controller method you showed in your question it is trying to parse the word "save" as an integer id for the resource "/{id}".

To fix this you should rename this previous resource mapping from "/{id}" to something with a suitable prefix "/something/{id}.

Upvotes: 3

Related Questions