获取大型表单到Spring控制器

时间:2014-07-30 16:35:39

标签: java javascript spring jsp spring-mvc

我有一个表单,其目的是允许用户在数据库表中创建新条目。形式非常大,总共约50个领域。我需要一种方法将所有这些值传递给我的控制器,尽管我没有看到一个简单的方法。我见过的每个解决方案都是@RequestParam('field'),但有大约50个字段有点疯狂。也许如果可以使用@RequestParam Map<T, T>

我最初尝试的是创建一个对

的AJAX POST调用

baseapplication.com/add?field1=value1&field2=value2&...&field50=value50

然后servlet抱怨找不到add.jsp文件。这是合理的,因为该文件不存在,但我创建了一个映射@RequestMapping(value="/add")的控制器,所以我实际上不需要该文件。我有另一个方法,它创建一个带有一些url参数的/search的AJAX GET调用,并且工作正常。还没有search.jsp文件。

这个问题很难解释,我希望我做了一个中等体面的工作。我们现在看一些代码,遗漏因为处理~50个表单字段非常冗长。

从启动整个过程的JavaScript开始:

ctx = "baseapplication.com"
$('#addNewRecordBtn').on('click', function(){
    var m_insId = document.getElementById('m_insId');
    //This repeats for every field
    var url = ctx + '/add?insuredId=' + m_insId /** + all other fields **/;
    addCase(url);
});

function addCase(url) {
    $.ajax({
        url: url,
        type: 'POST'
    }).success(function(data){
        alert("Successfully added row");
    }).fail(function(jzXHR, textStatus, errorThrown){
        alert(jzXHR);
        alert(textStatus);
        alert(errorThrown);
    });
}

所以这个流程如下:用户点击addNewRecordBtn按钮,它会触发第一个功能。此函数获取表单中每个字段的值,然后使用每个值的参数构建一个URL。然后调用addCase()函数,它会创建一个AJAX POST(不知道该怎么称呼它?)到刚构建的URL。此功能不成功,错误警报提供零信息,但服务器控制台声明Failed to find resource /WEB-INF/views/add.jsp

现在我们进入控制器。

@Controller
public class ApplicationController {

    @Autowired
    SpecialClaimsCaseManager caseManager;

    @RequestMapping(value="/add")
    public void addRow(@RequestParam Map<String, String> requestParams) {
        SpecialClaimsCase newCase = new SpecialClaimsCase();

        newCase.setInsuredId(requestParams.get("insuredId"));
        //Repeat this for all parameters

        caseManager.addNewSpecialClaimsCase(newCase);
}

caseManager.addNewSpecialClaimsCase(newCase)调用只是从这个模型对象中创建一个DTO对象,然后通过一些Hibernate魔法将该新对象添加到数据库中。除了工作之外,我对这方面知之甚少。

所以,我不确定我是否会采用正确的方法。我听说有一种方法可以使用Spring的标签库将模型对象映射到JSP表单,但这需要大量的重写,因为表单很大。我也使用Bootstrap构建接口,我不确定Bootstrap和Spring的标签库是否混合良好。我无法想象为什么不。

我不确定我是否需要在这里使用AJAX。我去了,因为我不希望页面必须重新加载或任何东西。我通常不是网络开发人员,所以我确信我缺乏一些基础知识。

我的主要问题是:鉴于我的情况,将这种大量信息传递给我的控制器的最佳方法是什么?

提前感谢您阅读这面文字和代码,以及您可以提供的任何帮助!

1 个答案:

答案 0 :(得分:3)

创建一个包含所有这些必需字段的域类,并生成getter和setter以及构造函数。一旦你得到所有这些字段/其中一些字段POST作为json到你的控制器。然后,适当的控制器将调用所需的服务,然后DAO将处理持久性部分。 简而言之,将您需要的数据作为JSON对象发送。将json设为java对象,并对其执行相同的操作。

这是控制器

@Controller
@RequestMapping(value = "/students/association")
public class StudentDepartmentController {

@Autowired
private StudentService studentService;

@Autowired
private StudentDepartmentService studentDepartmentService;

@RequestMapping(value = "/add-department", method = RequestMethod.POST)
public ResponseEntity<StudentDepartment> createStudentDepartmentAssociation(
        @RequestBody final StudentDepartment studentDepartment) {

    StudentDepartment newStudentDepartment;

    // check if the student exists

    Student student = studentService.getStudentByUuid(studentDepartment
            .getStudentUuid().getUuid());

    if (null == student) {

        throw new IllegalArgumentException("No students found!");

    }

    // check the status of student
    if (student.getStatus() == Liveliness.INACTIVE) {
        throw new IllegalArgumentException(
                "cannot create an association with an inactive student! activate student first");
    }

    // check for valid department

    if (null == studentDepartment.getDepartment().getName()) {
        throw new IllegalArgumentException("No such Department");
    }

    // check if the association already exists

    if (null != findOneAssociationAgainstStudent(student)) {
        throw new IllegalArgumentException(
                "cannot create student department association, as "
                        + student.getUsn()
                        + " already present in another association ( "
                        + studentDepartment.getDepartment().getName()
                        + " )");
    }

    try {

        newStudentDepartment = studentDepartmentService
                .createNewAssociation(studentDepartment);

    } catch (DataIntegrityViolationException ex) {

        throw new AutomationTransactionException(
                "cannot create student department association, as "
                        + student.getUsn()
                        + " already present in another association ( "
                        + studentDepartment.getDepartment().getName()
                        + " )", ex);

    }

    return new ResponseEntity<StudentDepartment>(newStudentDepartment,
            HttpStatus.CREATED);
}

private StudentDepartment findOneAssociationAgainstStudent(Student student) {

    return studentDepartmentService.findOneAssociation(student);
}

private StudentDepartment findOne(Uuid uuid) {

    String studentDepartmentUuid = uuid.getUuid();

    return findOne(studentDepartmentUuid);

}

private StudentDepartment findOne(String uuid) {

    return studentDepartmentService.findOne(uuid);

}

@RequestMapping(value = "/delete-association", method = RequestMethod.DELETE)
public ResponseEntity<String> deleteStudentDepartmentAssociationByUuid(
        @RequestBody final StudentDepartment studentDepartment) {

    // check if association exists
    StudentDepartment association = findOne(studentDepartment.getUuid());
    if (null == association) {
        throw new IllegalArgumentException("No such association found!");
    }

    studentDepartmentService.deleteAssociation(association);

    return new ResponseEntity<String>("success", HttpStatus.OK);

}

}`

@RequestBody注释可帮助您将json对象转换为java对象。

这样,您可以将有效负载作为json,并获取java对象并使用ResponseEntity<Class>注释将json发送回UI

相关问题