如何将值传递给模型类

时间:2015-08-07 09:21:08

标签: java spring-mvc

在jsp页面中,我正在使用输入字段

<input type="text"  name="basic" id="basic"  >

在控制器中

@RequestMapping(value="/palySlip/add",method=RequestMethod.POST)
public String addData(@ModelAttribute("empPaySlip") EmployeePlaySlip e){

    return "redirect:/employeepayin";
}

将值设置为模型类

 public class EmployeePlaySlip {
    private double basic;
    public double getBasic() {
        return basic;
    }
    public void setBasic(double basic) {
        this.basic = basic;
    }
}

但在发送数据时我收到了错误

  

HTTP状态400 - 类型状态报告消息描述请求   客户发送的语法不正确。

2 个答案:

答案 0 :(得分:0)

首先,您需要将对象设置为模型属性。

@RequestMapping(value="/employeepaying",method=RequestMethod.POST)
public ModelAndView showData(){
    ModelAndView mav = new ModelAndView("employeepayingPage");
    mav.addObject(empPaySlip, new EmployeePlaySlip ());
    return mav;
}

将Spring taglib添加到JSP

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

为submition创建表单:

<form:form method="post"  modelAttribute="empPaySlip" action="/palySlip/add">
    <form:input path="basic" />
    <input type="submit" value="Submit" />
</form:form>

然后获取您的模型属性。

@RequestMapping(value="/palySlip/add", method=RequestMethod.POST)
public String addData(@ModelAttribute("empPaySlip") EmployeePlaySlip e){
    // Do whatever you want with your object
    return "redirect:/employeepaying";
}

答案 1 :(得分:0)

在你的@Controller首先将你的jsp页面表单与Get方法的Model Attribute链接

@RequestMapping(value= "/studenteducation", method= RequestMethod.GET)
public String setupUpdateEducationForm(Model model,@ModelAttribute("education") Student student){

    student = studentService.getStudent(getStudentName());
    model.addAttribute("education", student);  //adding saved student data into model
    return "studenteducation";
}

一个Post方法将提交你的jsp表单

@RequestMapping(value= "/studenteducation", method= RequestMethod.POST)
public String studentEducationForm(Model model, @ModelAttribute("education") Student student, BindingResult result){

    if(result.hasErrors()){
        return "studenteducation";          
    }

    student.setStudentId(getStudentName()); // inserting primary key
    studentService.updateStudent(student);  // updating student table

    return "redirect:/";        
}

注意@ModelAttribute名称,它应该与jsp modelAttribute名称相同。

现在在jsp页面中,modelAttribute =“education”action =“/ studenteducation”和表格输入与您的列名称将起作用。

<form:form method="post"  modelAttribute="education" action="/studenteducation">
    <form:input path="your column name" />
    ....
<input type="submit" value="Submit" />