【问题标题】:How to make spring repositories respond with html forms instead of json?如何让 Spring 存储库使用 html 表单而不是 json 响应?
【发布时间】:2016-09-14 16:01:10
【问题描述】:

我有多个 spring 存储库,一个用于我数据库中的每个表。在 application.properties 中使用 @EnableJpaRepositories(basePackage = "com.company.repositories")spring.data.rest.base-path=/api 我现在有了一个基于 json 的完整 REST api。

我可以在 JSON 对象的帮助下发布到 /api/customers、PATCH 等。

当我在资源上使用 GET 并在表单使用 PUT、POST 等提交数据时处理 application/x-www-form-urlencoded 时,有没有办法告诉 Spring 呈现 html 表单而不是 json 对象?

【问题讨论】:

    标签: java rest spring-data-rest


    【解决方案1】:

    你可以在 spring mvc 中借助 ViewResolvers 使用 jsps 来渲染 html。如果验证失败,将在下面呈现 new.jsp。

    //Controller example from spring doc
    @RequestMapping(method = RequestMethod.POST)
    public String add(@Valid AppointmentForm appointment, BindingResult result) {
        if (result.hasErrors()) {
            return "appointments/new";
        }
        appointmentBook.addAppointment(appointment);
        return "redirect:/appointments";
    }
    
    //Spring context    
    <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>  
    

    【讨论】:

    • 我需要在 new.jsp 中写表单吗?我不想为模型中的 50 多个实体编写代码。难道没有其他方法可以做到这一点吗?
    猜你喜欢
    • 2016-06-11
    • 2018-12-19
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多