Product

package com.mstf.bean;

import java.io.Serializable;
/**
* Product类,封装了一些信息,包含三个属性
* @author wangzheng
*
*/
public class Product implements Serializable { private static final long serialVersionUID = 1L; private String name;
private String description;
private float price; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
} }

  ProductForm

package com.mstf.bean.form;
/**
* ProductForm是表单类
* 作用:当数据校验失败时,用于保存和展示用户在原始表单的输入
* @author wangzheng
*
*/
public class ProductForm {
private String name;
private String description;
private String price; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
} }

  Controller

package com.mstf.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public interface Controller { String handleRequest(HttpServletRequest req,HttpServletResponse resp);
}

  InputProductController

package com.mstf.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class InputProductController implements Controller { @Override
public String handleRequest(HttpServletRequest req,HttpServletResponse resp) {
return "/WEB-INF/jsp/ProductForm.jsp";
}
}

  SaveProductController

package com.mstf.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.mstf.bean.Product;
import com.mstf.bean.form.ProductForm;
import com.mstf.validator.ProductValidator; public class SaveProductController implements Controller { @Override
public String handleRequest(HttpServletRequest req,HttpServletResponse resp) {
// 构建一个ProductForm表单对象
ProductForm productForm = new ProductForm();
// 写入表单对象
productForm.setName(req.getParameter("name"));
productForm.setDescription(req.getParameter("description"));
productForm.setPrice(req.getParameter("price")); //引入校验器
ProductValidator productValidator=new ProductValidator();
List<String> errors=productValidator.validate(productForm);
if(errors.isEmpty()) {
// 创建模型
Product product = new Product();
product.setName(productForm.getName());
product.setDescription(productForm.getDescription());
product.setPrice(Float.parseFloat(productForm.getPrice()));
req.setAttribute("product", product);
return "/WEB-INF/jsp/ProductDetails.jsp";
} else {
req.setAttribute("errors", errors);
req.setAttribute("form", productForm);
return "/WEB-INF/jsp/ProductForm.jsp";
}
}
}

  DispatcherServlet

package com.mstf.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 com.mstf.controller.InputProductController;
import com.mstf.controller.SaveProductController; public class DispatcherServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
process(req, resp);
} @Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
process(req, resp);
}
/**
* 这个方法用来处理所有输入请求
* @param req
* @param resp
* @throws IOException
* @throws ServletException
*/
private void process(HttpServletRequest req,HttpServletResponse resp) throws IOException,ServletException {
req.setCharacterEncoding("UTF-8"); //转码
resp.setCharacterEncoding("UTF-8");
String uri=req.getRequestURI(); // 获取请求URI
int lastIndex=uri.lastIndexOf("/");
String action=uri.substring(lastIndex+1); // 获取action名称
String dispatchUrl=null;
// 执行方法
if(action.equals("product_input.action")) {
InputProductController controller=new InputProductController();
dispatchUrl=controller.handleRequest(req, resp);
} else if (action.equals("product_save.action")) {
SaveProductController controller=new SaveProductController();
dispatchUrl=controller.handleRequest(req, resp);
}
if(dispatchUrl!=null) {
RequestDispatcher rd=req.getRequestDispatcher(dispatchUrl);
rd.forward(req, resp);
}
}
}

 ProductValidator

package com.mstf.validator;

import java.util.ArrayList;
import java.util.List; import com.mstf.bean.form.ProductForm;
/**
* 校验器
* @author wangzheng
*
*/
public class ProductValidator { public List<String> validate(ProductForm productForm) {
List<String> errors = new ArrayList<String>();
String name = productForm.getName();
if (name == null || name.trim().isEmpty()) {
errors.add("必须输入名称!");
}
String price = productForm.getPrice();
if (price == null || price.trim().isEmpty()) {
errors.add("必须输入价格!");
} else {
try {
Float.parseFloat(price);
} catch (NumberFormatException e) {
errors.add("输入的价格无效!");
}
}
return errors;
}
}

  ProductDetails.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>详情</title>
<style type="text/css">@IMPORT url("css/main.css");</style>
</head>
<body>
<div id="global">
<h4>产品已保存</h4>
<p>
<h5>详细列表:</h5>
名称: ${product.name}<br>
简介: ${product.description}<br>
价格: ¥${product.price}
</p>
</div>
</body>
</html>

  ProductForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加</title>
<style type="text/css">@IMPORT url("css/main.css");</style>
</head>
<body>
<div id="global">
<c:if test="${requestScope.errors != null }">
<p id="errors">
操作出错!
<ul>
<c:forEach var="error" items="${requestScope.errors }">
<li>
${error }
</li>
</c:forEach>
</ul>
</p>
</c:if>
<form action="product_save.action" method="post">
<fieldset>
<legend>添加:</legend>
<p>
<label for="name">名称: </label>
<input type="text" id="name" name="name" tabindex="1">
</p>
<p>
<label for="description">简介: </label>
<input type="text" id="description" name="description" tabindex="2">
</p>
<p>
<label for="price">价格: </label>
<input type="text" id="price" name="price" tabindex="3">
</p>
<p id="buttons">
<input id="reset" type="reset" tabindex="4">
<input id="submit" type="submit" tabindex="5" value="添加">
</p>
</fieldset>
</form>
</div>
</body>
</html>

  

 

Spring MVC模式示例(采用解耦控制器+校验器)的更多相关文章

  1. Spring MVC模式示例(采用解耦控制器)

    Product package com.mstf.bean; import java.io.Serializable; /** * Product类,封装了一些信息,包含三个属性 * @author ...

  2. Spring MVC模式示例(未采用解耦控制器)

    Product package com.mstf.bean; import java.io.Serializable; /** * Product类,封装了一些信息,包含三个属性 * @author ...

  3. Spring MVC 入门示例讲解

    在本例中,我们将使用Spring MVC框架构建一个入门级web应用程序.Spring MVC 是Spring框架最重要的的模块之一.它以强大的Spring IoC容器为基础,并充分利用容器的特性来简 ...

  4. Spring MVC 完整示例

    在本例中,我们将使用Spring MVC框架构建一个入门级web应用程序.Spring MVC 是Spring框架最重要的的模块之一.它以强大的Spring IoC容器为基础,并充分利用容器的特性来简 ...

  5. Spring MVC 入门示例讲解 - howtodoinjava

    在本例中,我们将使用Spring MVC框架构建一个入门级web应用程序.Spring MVC 是Spring框架最重要的的模块之一.它以强大的Spring IoC容器为基础,并充分利用容器的特性来简 ...

  6. Spring mvc 模式小结

    http://www.taobaotesting.com/blogs/2375 1.spring mvc简介 Spring MVC框架是一个MVC框架,通过实现Model-View-Controlle ...

  7. Spring MVC体系结构和处理请求控制器

    Spring MVC体系结构和处理请求控制器 一:MVC设计模式: (1.)数据访问接口:DAO层 (2.)处理业务逻辑层:Service层 (3.)数据实体:POJO (4.)负责前段请求接受并处理 ...

  8. Spring MVC 项目示例

    Spring MVC是Spring Framework的一部分,是基于Java实现MVC的轻量级Web框架.Spring的web框架围绕DispatcherServlet设计, 作用是将请求分发到不同 ...

  9. spring mvc: 可参数化的视图控制器(在配置中指定jsp文件)MultiActionController/SimpleUrlHandlerMapping/ParameterizableViewController

    spring mvc: 可参数化的视图控制器(在配置中指定jsp文件)MultiActionController/SimpleUrlHandlerMapping/ParameterizableView ...

随机推荐

  1. django models.py增加后MySQL数据库中并没有生成相应的表

    根据教程到添加并保存quest的时候报错了 1.models.py里面的命名没有错 2.查看mysite->settiongs下的INSTALLED_APPS设置正确 3.使用python ma ...

  2. Unity学习笔记 之 发射小球碰撞物体的代码记录

    绑定在摄像机上的脚本 using UnityEngine; using System.Collections; public class abc : MonoBehaviour { //设置移动速度 ...

  3. Cocos2d-x-lua学习点滴

    Lua下的方法.自己项目经验,个人见解,不能确保正确. Sprite: local Light = CCSprite:create("light.png")             ...

  4. 51nod-1346: 递归

    [传送门:51nod-1346] 简要题意: 给出一个式子a[i][j]=a[i-1][j]^a[i][j-1] 给出a[1][i],a[i][1](2<=i<=131172) 有n个询问 ...

  5. angular4(2-1)angular脚手架引入第三方类库(jquery)

    欢迎加入前端交流群交流知识&&获取视频资料:749539640 如何在angular4脚手架中引入第三方类库呢比如jquery.swiper.bootstrap...... 例如引入j ...

  6. [jzoj 6087] [GDOI2019模拟2019.3.26] 获取名额 解题报告 (泰勒展开+RMQ+精度)

    题目链接: https://jzoj.net/senior/#main/show/6087 题目: 题解: 只需要统计$\prod_{i=l}^r (1-\frac{a_i}{x})$ =$exp(\ ...

  7. luogu 1941 飞扬的小鸟

    这道题对于第13个数据点,不知为什么f数组第二位开到2000以下就不能过,求指教 飞扬的小鸟 传送门 题目大意 一个小鸟在\(n*m\)的方阵里,然后有许多管道你们玩过就不多介绍了,然后每一个位置,点 ...

  8. Charles抓取微信小程序数据 以及 其它应用网站数据

    为了抓取小程序数据所以使用Charles来抓取,下面介绍下使用方法(mac环境下使用).使用Charles可以非常方便的抓取Http/Https请求.官方dmg下载地址:点击此处下载 Charles抓 ...

  9. Javascript四种调用模式中的this指向

    第一种:函数直接调用执行的模式 function add(a,b){ console.log(this); return a+b; } add(,) //this===window 这里的this指向 ...

  10. 亿财道APP赚钱攻略,亿财道,一个看广告年入36万的APP

            亿财道(http://etway.net/),一款看广告(传单)赚钱的软件,这是一项革新的广告产品,代替了以往的纸质传单.在商家节约成本的同时,还给阅读者佣金,推广也有相应提成比例. ...