Spring MVCテキストボックスの例
Spring MVCでは、<form:input />タグを使用してHTMLテキストボックスフィールドをレンダリングできます。 例えば、
次のHTMLコードをレンダリングします
このチュートリアルでは、Springのフォームタグ「input」からrender a HTML textboxを使用して「userName」を格納する方法を示します。 さらに、空のチェックバリデータを追加して、テキストボックスの値が空でないことを確認します。
1. コントローラ
フォーム値を処理し、フォーム値をCustomerオブジェクトにリンクするためのSimpleFormController。
ファイル:TextBoxController.java
package com.example.customer.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.example.customer.model.Customer;
public class TextBoxController extends SimpleFormController{
public TextBoxController(){
setCommandClass(Customer.class);
setCommandName("customerForm");
}
@Override
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
Customer customer = (Customer)command;
return new ModelAndView("CustomerSuccess","customer",customer);
}
}
2. モデル
テキストボックスの値を格納するCustomerオブジェクト。
ファイル:Customer.java
package com.example.customer.model;
public class Customer{
String userName;
//getter and setter methods
}
3. フォームバリデーター
フォームバリデータークラスを作成し、ValidationUtilsクラスを使用して、「userName」が空でないことを確認します。空でない場合は、対応するリソースバンドル(プロパティファイル)から「required.userName」メッセージを取得します。
ファイル:CustomerValidator.java
package com.example.customer.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.example.customer.model.Customer;
public class CustomerValidator implements Validator{
@Override
public boolean supports(Class clazz) {
//just validate the Customer instances
return Customer.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName",
"required.userName", "Field name is required.");
}
}
ファイル:message.properties
required.userName = username is required!
4. View
Springのフォームタグ「input」を使用してHTMLテキストボックスをレンダリングし、いくつかのCSSスタイルを配置してエラーメッセージを強調表示するJSPページ。
ファイル:CustomerForm.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
Spring's form textbox example
Username :
フォームが送信された場合、成功したページをレンダリングし、送信されたテキストボックスの値を表示します。
ファイル:CustomerSuccess.jsp
Spring's form textbox example
userName : ${customer.userName}
5. Spring Beanの構成
それをすべてリンクしてください〜
/WEB-INF/pages/ .jsp
6. Demo
ページへのアクセス - http://localhost:8080/SpringMVCForm/textbox.htm

フォームの送信中にテキストボックスの値が空の場合、エラーメッセージを表示して強調表示します。

フォームが正常に送信された場合、送信されたテキストボックスの値を表示するだけです。

ソースコードをダウンロード
ダウンロード–SpringMVCForm-TextBox-Example.zip(9KB)