Hiển thị các bài đăng có nhãn xử lý form. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn xử lý form. Hiển thị tất cả bài đăng

Thứ Năm, 26 tháng 12, 2013

Xử lý form trong Spring MVC

Trong phần này ta sẽ làm ví dụ xử lý dữ liệu lấy từ form ở trang JSP.
File->new->Spring project->Spring MVC Project
cấu trúc thư mục sẽ như sau:

Nội dung:
Sử dụng domain sau để lưu trữ thông tin của Product
package vn.ds.store.domains;

import java.io.Serializable;

public class Product implements Serializable {
 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 private String name;
 private String price;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getPrice() {
  return price;
 }

 public void setPrice(String price) {
  this.price = price;
 }
}


Chương trình sẽ lấy dữ liệu khi người dùng nhập vào

 và in ra danh sách


dữ liệu nhập vào sẽ được validate như hình sau

Đầu tiên ta xây dựng file properties để lưu trữ thông báo cho chương trình.
file product-messages.properties sẽ được tạo ra ở thư mục src/main/resources

các parameter được tryền vào theo các vị trí {0} {1}...
Để spring đọc được file resources này ta định nghĩa thêm 1 bean  là thể hiện của lớp org.springframework.context.support.ReloadableResourceBundleMessageSource để đọc messages.
vào file WEB-INF/spring/appServlet/servlet-context.xml thêm đoạn sau:

  
 

Toàn bộ file servlet-context.xml sẽ như thế này:


 
 
 
 

 
 

 
 
  
  
 
 
 
 
 
  
 
 



Xong phần cấu hình, giờ sẽ xây dựng một lớp ProductValidator để valid dữ liệu từ người dùng. Vì spring đã hỗ trợ validate trong interface Validator nên class của ta chỉ việc implements giao diện đó và triển khai phương thức validate() của Validator interface.
package vn.ds.store.validators;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import vn.ds.store.domains.Product;

public class ProductValidator implements Validator {

 @Override
 public boolean supports(Class clazz) {

  return Product.class.isAssignableFrom(clazz);
 }

 @Override
 public void validate(Object target, Errors errors) {
  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name",
    "msg.required", new Object[] { "name" });
  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "price",
    "msg.required", new Object[] { "price" });
  Product product = (Product) target;
  String name = product.getName();
  int max = 6;
  if (!name.isEmpty() && name.length() > max)
   errors.rejectValue("name", "msg.maxlength", new Object[] { "name",
     max }, "");
  if (!isNumber(product.getPrice().trim()))
   errors.rejectValue("price", "msg.number", new Object[] { "price",
     max }, "");
 }

 public boolean isNumber(String s) {
  for (int i = 0; i < s.length(); i++) {
   if (!Character.isDigit(s.charAt(i)))
    return false;
  }
  return true;
 }

}


Phương thức
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name",
    "msg.required", new Object[] { "name" });
sẽ kiểm tra xem trường "name" có emty hay có space không, nếu có sẽ add thêm một message vào đối tượng errors, nội dung msg sẽ được lấy theo id của msg trong resources là "msg.required" và truyền vào một parameter cho msg đó là một mảng Object có 1 phần tử là "name". Tương tự phương thức
errors.rejectValue("price", "msg.number", new Object[] { "price",
     max }, "");
cũng sẽ add thêm một msg của trường "price" vào errors theo msg là "msg.number" và set vào 2 parameter là một biến String "price" và một biến Integer max
Controller
package vn.ds.store.controllers;

import java.util.ArrayList;

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 vn.ds.store.domains.Product;
import vn.ds.store.validators.ProductValidator;

@Controller
@RequestMapping("product")
public class ProductController {

 private ProductValidator validator = new ProductValidator();

 @RequestMapping(value = "create", method = RequestMethod.GET)
 public String doGet(Model model) {
  model.addAttribute("product", new Product());
  return "createProduct";
 }

 @RequestMapping(value = "save", method = RequestMethod.POST)
 public String doPost(@ModelAttribute Product product,
   Model model, BindingResult errors) {
  validator.validate(product, errors);
  if (errors.hasErrors()) {
   return "createProduct";
  }
  ArrayList lst = new ArrayList();
  Product p = new Product();
  p.setName("product 1");
  p.setPrice("100");
  lst.add(p);
  lst.add(product);
  model.addAttribute("products", lst);
  return "listProduct";
 }
}


Ở đây Phương thức GET của url "/product/create" sẽ được xử lý bởi hàm doGet(). hàm này sẽ tạo mới một đối tượng Product và add vào model. sau đó trả về một view có tên là "createProduct". view này là view jsp được định nghĩa trong file servlet-context.xml. vì ta không định nghĩa cụ thể nên spring sẽ xem id của view theo tên file jsp. Phương thức POST của url "/product/save" sẽ xử lý khi người dụng submit form trong method doPost()
Đầu tiên sẽ validate dữ liệu theo đối tượng ProductValidator. nếu có lỗi sẽ trả về view "createProduct" là trang nhập dữ liệu
Nếu không có lỗi sẽ thực hiện add dữ liệu vào model và gửi xuống view "listProduct".
JSP
file createProduct.jsp trong thư mục WEB-INF/views sẽ như sau:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>




Insert title here



 
  
create
Name
Price
 

và view hiển thị danh sách listProduct.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>   




Insert title here



 
List of products
Name Price
${p.name} ${p.price}

Source code theo link http://www.mediafire.com/download/vki3lvwpsqtpam8/Store_handling_form.rar Thanks & Rgds!!!