简体   繁体   中英

error HTTP Status 400 -The request sent by the client was syntactically incorrect. updated

First of all I have two tables job, category which are in diagram as

工作对猫

and my entities are :

@Entity
@Table( name = TableName.JOB_TABLE)
public class Job {


    @Id
    @GeneratedValue
    private Integer id;

    private String title;

    private String description;     

    @OneToMany(mappedBy = "job")
    private List<Category> categories;

    // omitting setters an getters for brevity  

}

and

@Entity
@Table( name = TableName.CATEGORY_TABLE)
public class Category {

    @Id
    @GeneratedValue
    private Integer id;

    private String name;

    @ManyToOne
    @JoinColumn(name = "job_id")
    private Job job;

    // omitting setters an getters for brevity  

}

JobService is

@Service
public class JobService implements IDatabaseCrud<Job>{

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private CategoryRepository categoryRepository;

    public void saveCategory(Job job) {
        List<Category> categories = job.getCategories();
        for (Category category : categories) {
            category.setJob(job);
            categoryRepository.save(category);
        }
    }

    @Override
    public void save(Job obj) {
        // TODO Auto-generated method stub      
        jobRepository.save(obj);
        saveCategory(obj);
    }
}

now I don't have any idea to save new job where I've to save one Job with many categories selected from list.

<form:form commandName="job">
   <form:input path="title"/><br>
    <form:input path="company"/><br>
    <form:input path="location"/><br>
    <form:input path="url"/><br>
    <form:input path="email"/><br>
    <form:input path="description"/><br>
    <form:select path="categories">
    <form:options items="${categories}" itemValue="id" itemLabel="name"/>
    </form:select><br>
    <form:input path="createdAt"/><br>
    <form:input path="toApply"/><br>
    <input type="submit" value="Add Job">
</form:form>

the above form is not submitting data to controller and gives error HTTP Status 400 -The request sent by the client was syntactically incorrect. following controller I want to save these details to DB

@Controller
public class JobController {

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

    @Autowired
    private JobService jobService;

    @Autowired
    private CategoryService categoryService;

    @ModelAttribute("job")
    public Job constructJob() {
        return new Job();
    }

    @RequestMapping(value = "/jobs", method = RequestMethod.GET)
    public String showJobs(Model model) {
        model.addAttribute("jobs", jobService.findAll());
        return "jobs";
    } 

    @RequestMapping(value = "/jobs/{id}", method = RequestMethod.GET)
    public String showJobDetail(Model model, @PathVariable Integer id) {
        model.addAttribute("job", jobService.findJobWithCategories(id));
        return "job-detail";
    } 

    @RequestMapping(value = "/show-add-job", method = RequestMethod.GET)
    public String showJobForm(Model model) {
        model.addAttribute("categories", categoryService.findAll());
        return "add-job";
    } 

    @RequestMapping(value = "/show-add-job", method = RequestMethod.POST)
    public String addJobDetail(@ModelAttribute("job") Job job) {
        ///jobService.save(job);
        List<Category> categories = job.getCategories();
        for (Category category : categories) {
            logger.info("DEBUG job object", category);
        }
        return "redirect:/jobs";
    } 

}

with the above stuff I'm unable to save job with categories when I submit the form I get HTTP Status 400 . is some thing wrong in form. This is URL to that project.

The problem you are getting is related to how you bind the categories, in fact you need to help the framework resolve them, eg with a help of WebDataBinder . You should add something like

   @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Category.class,
                new PropertyEditorSupport() {

                    @Override
                    public void setAsText(String text) {
                        // replace the dao with your appropriate repository call
                        Category category = dao.find(Category.class,
                                Integer.parseInt(text));
                        setValue(category);
                    }
                });
    }

about the createdAt

the trouble you're facing there is that you need to tell the framework in which format are you entering the date. For example, if you are passing the date in the format of yyyy\\MM\\dd , than it will simply work. If you are using some other format it will suffice to annotate the property with @DateTimeFormat . A concrete example, you can annotate your property inside the Job class with

@DateTimeFormat(iso= DateTimeFormat.ISO.DATE)
@Column(name = "created_at")
private Date createdAt;

DateTimeFormat.ISO.DATE expects a date in yyyy-MM-dd format, or use a pattern attribute, and the format you prefer

Hello i checked out your code and found that you have three issues: one is related to submission of the date field - createdAt , the other one is with the applyTo field and the other one is with categories field.

About the problem with dates you should check documentation for spring @InitBinder. Here is a good SO thread for it. Basic problem is that spring don't know how to bind date to String .

Other problem with categories field is that you should implement a Converter that will convert categoryId which is a number to Category class. see here good thread.

if you remove all three fields - applyTo,createdAt and categories, your form submission will work. but if you want to work as expected please implement @initBinder for date and Converter for categories

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM