1. 程式人生 > >SpringMVC學習指南 模型2和MVC模式

SpringMVC學習指南 模型2和MVC模式

package cn.app02a.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.app02a.domain.Product;
import cn.app02a.form.ProductForm;

public class ControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -6714354047703169167L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	private void process(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String uri = request.getRequestURI();
		int lastIndex = uri.lastIndexOf("/");
		String action = uri.substring(lastIndex + 1);
		// execute an action
		if (action.equals("product_input.action")) {
			// no action class,there is nothing to be done.
		} else if (action.equals("product_save.action")) {
			// create form
			ProductForm productForm = new ProductForm();
			productForm.setName(request.getParameter("name"));
			productForm.setDescription(request.getParameter("description"));
			productForm.setPrice(request.getParameter("price"));
			// create model
			Product product = new Product();
			product.setName(productForm.getName());
			product.setDescription(productForm.getDescription());
			try {
				product.setPrice(Float.parseFloat(productForm.getPrice()));
			} catch (NumberFormatException e) {
			}
			// code to save product
			// store model in a scope variable for the view
			request.setAttribute("product", product);
		}
		// forward to a view
		String dispatchUri = null;
		if (action.equals("product_input.action")) {
			dispatchUri = "/WEB-INF/jsp/ProductForm.jsp";
		} else if (action.equals("product_save..action")) {
			dispatchUri = "/WEB-INF/jsp/ProductDetail.jsp";
		}
		if (dispatchUri != null) {
			RequestDispatcher rd = request.getRequestDispatcher(dispatchUri);
			rd.forward(request, response);
		}
	}
}
若基於servlet3.0規範,則可以採用註解的方式,而無需在部署描述中進行對映