spring mvc 提交表单的例子

1. 构建MAVEN项目,然后转换成web格式,结构图如下:

spring mvc 提交表单的例子

2. 通过@RequestMapping来进行配置,当输入URL时,会以此找到对应方法执行,首先调用setupForm方法,该方法主要是生成一个EmployeeVO对象,然后返回给view.同时需要对form表单中的数据进行验证,其验证方法在submitForm方法中实现。

package com.howtodoinjava.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus; import com.howtodoinjava.demo.model.EmployeeVO;
import com.howtodoinjava.demo.service.EmployeeManager; @Controller
@RequestMapping("/employee-module/addNew")
@SessionAttributes("employee")
public class EmployeeController {
@Autowired
EmployeeManager manager; @RequestMapping(method = RequestMethod.GET)
public String setupForm(Model model) {
EmployeeVO employeeVO = new EmployeeVO();
model.addAttribute("employee", employeeVO);
return "addEmployee";
} @RequestMapping(method = RequestMethod.POST)
public String submitForm(@ModelAttribute("employee") EmployeeVO employeeVO,
BindingResult result, SessionStatus status) { //Validation code start
boolean error = false; System.out.println(employeeVO); //Verifying if information is same as input by user if(employeeVO.getFirstName().isEmpty()){
result.rejectValue("firstName", "error.firstName");
error = true;
} if(employeeVO.getLastName().isEmpty()){
result.rejectValue("lastName", "error.lastName");
error = true;
} if(employeeVO.getEmail().isEmpty()){
result.rejectValue("email", "error.email");
error = true;
} if(error) {
return "addEmployee";
}
// Store the employee information in database
// manager.createNewRecord(employeeVO); // Mark Session Complete
status.setComplete();//清除会话数据
return "redirect:addNew/success";
} @RequestMapping(value = "/success", method = RequestMethod.GET)
public String success(Model model) {
return "addSuccess";
}
}

  3. 修改jsp文件。

<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

<html>
<head>
<title>Add Employee Form</title>
<style>
.error
{
color: #ff0000;
font-weight: bold;
}
</style>
</head>

<body>
<h2><spring:message code="lbl.page" text="Add New Employee" /></h2>
<br/>
<form:form method="post" modelAttribute="employee">
<%-- <form:errors path="*" cssClass="error" /> --%>
<table>
<tr>
<td><spring:message code="lbl.firstName" text="First Name" /></td>
<td><form:input path="firstName" /></td>
<td><form:errors path="firstName" cssClass="error"/></td>
</tr>
<tr>
<td><spring:message code="lbl.lastName" text="Last Name" /></td>
<td><form:input path="lastName" /></td>
<td><form:errors path="lastName" cssClass="error"/></td>
</tr>
<tr>
<td><spring:message code="lbl.email" text="Email Id" /></td>
<td><form:input path="email" /></td>
<td><form:errors path="email" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Add Employee"/></td>
</tr>
</table>
</form:form>
</body>
</html>

  3. 在messages.properties文件添加error信息。

lbl.page=Add New Employee
lbl.firstName=First Name
lbl.lastName=Last Name
lbl.email=Email Id //Error messages
error.firstName=First Name can not be blank
error.lastName=Last Name can not be blank
error.email=Email Id can not be blank

 其他地方无需做修改。

通过URL访问,可以得到

spring mvc 提交表单的例子

但是该例子存在一个问题尚未解决,即验证表单数据是否为空时,返回到addEmployee.jsp文件时,会报错。未找到原因。

三月 02, 2016 4:11:35 下午 org.springframework.web.servlet.tags.form.ErrorsTag doStartTag
SEVERE: No message found under code 'error.firstName' for locale 'zh_CN'.
org.springframework.context.NoSuchMessageException: No message found under code 'error.firstName' for locale 'zh_CN'.
at org.springframework.context.support.AbstractMessageSource.getMessage(AbstractMessageSource.java:186)
at org.springframework.context.support.AbstractApplicationContext.getMessage(AbstractApplicationContext.java:1127)
at org.springframework.web.servlet.support.RequestContext.getMessage(RequestContext.java:732)
at org.springframework.web.servlet.support.BindStatus.initErrorMessages(BindStatus.java:181)
at org.springframework.web.servlet.support.BindStatus.getErrorMessages(BindStatus.java:277)
at org.springframework.web.servlet.tags.form.ErrorsTag.exposeAttributes(ErrorsTag.java:174)
at org.springframework.web.servlet.tags.form.AbstractHtmlElementBodyTag.writeTagContent(AbstractHtmlElementBodyTag.java:48)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
at org.apache.jsp.WEB_002dINF.views.addEmployee_jsp._jspService(addEmployee_jsp.java:135)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:486)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:411)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:338)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:168)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1228)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1011)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:955)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

  

上一篇:js动态添加事件


下一篇:.net c# MVC提交表单的4种方法