持久层,服务层,表现层都涉及到了。

这个分得确实比DJANGO细致,

多体会,多注解。。:)

The domain layer

package com.packt.webstore.domain;

import java.math.BigDecimal;

public class Product {

    private String productId;
    private String name;
    private BigDecimal unitPrice;
    private String description;
    private String manufacturer;
    private String category;
    private long unitsInStock;
    private long unitsInOrder;
    private boolean discontinued;
    private String condition;

    public Product() {
        super();
    }

    public Product(String productId, String name,
            BigDecimal unitPrice) {
        this.productId = productId;
        this.name = name;
        this.unitPrice = unitPrice;
    }

    public String getProductId() {
        return productId;
    }

    public void setProductId(String productId) {
        this.productId = productId;
    }

    public String getName() {
        return name;
    }

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

    public BigDecimal getUnitPrice() {
        return unitPrice;
    }

    public void setUnitPrice(BigDecimal unitPrice) {
        this.unitPrice = unitPrice;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public long getUnitsInStock() {
        return unitsInStock;
    }

    public void setUnitsInStock(long unitsInStock) {
        this.unitsInStock = unitsInStock;
    }

    public long getUnitsInOrder() {
        return unitsInOrder;
    }

    public void setUnitsInOrder(long unitsInOrder) {
        this.unitsInOrder = unitsInOrder;
    }

    public boolean isDiscontinued() {
        return discontinued;
    }

    public void setDiscontinued(boolean discontinued) {
        this.discontinued = discontinued;
    }

    public String getCondition() {
        return condition;
    }

    public void setCondition(String condition) {
        this.condition = condition;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((productId == null) ? 0 : productId.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Product other = (Product) obj;
        if (productId == null) {
            if (other.productId != null)
                return false;
        } else if (!productId.equals(other.productId))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Product [productId=" + productId + ", name=" + name + "]";
    }

}

The persistence layer

A persistence layer usually contains repository objects to
access domain objects. A repository object makes queries to the data source for the data,
thereafter maps the data from the data source to a domain object, and finally, persists the
changes in the domain object to the data source. So, a repository object is typically
responsible for CRUD operations ( Create , Read , Update , and Delete ) on domain objects.
The @Repository annotation ( org.springframework.stereotype.Repository ) is an
annotation that marks a specific class as a repository.

package com.packt.webstore.domain.repository;
import java.util.List;
import com.packt.webstore.domain.Product;

public interface ProductRepository {
    List<Product> getAllProducts();
    Product getProductById(String productId);
}
package com.packt.webstore.domain.repository.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.packt.webstore.domain.Product;
import com.packt.webstore.domain.repository.ProductRepository;

@Repository
public class InMemoryProductRepository implements ProductRepository {
    private List<Product> listOfProducts = new ArrayList<Product>();
    public InMemoryProductRepository() {
        Product iphone = new Product("P1234","iPhone 5s", new BigDecimal(500));
        iphone.setDescription("Apple iPhone 5s smartphone with 4.00-inch 640x1136 display and 8-megapixel rear camera");
        iphone.setCategory("Smart Phone");
        iphone.setManufacturer("Apple");
        iphone.setUnitsInStock(1000);

        Product laptop_dell = new Product("P1235","Dell Inspiron", new BigDecimal(700));
        laptop_dell.setDescription("Dell Inspiron 14-inch Laptop (Black) with 3rd Generation Intel Core processors");
        laptop_dell.setCategory("Laptop");
        laptop_dell.setManufacturer("Dell");
        laptop_dell.setUnitsInStock(1000);

        Product tablet_Nexus = new Product("P1236","Nexus 7", new BigDecimal(300));
        tablet_Nexus.setDescription("Google Nexus 7 is the lightest 7 inch tablet With a quad-core Qualcomm Snapdragon™ S4 Pro processor");
        tablet_Nexus.setCategory("Tablet");
        tablet_Nexus.setManufacturer("Google");
        tablet_Nexus.setUnitsInStock(1000);
        listOfProducts.add(iphone);
        listOfProducts.add(laptop_dell);
        listOfProducts.add(tablet_Nexus);
    }

    public List<Product> getAllProducts() {
        return listOfProducts;
    }

    @Override
    public Product getProductById(String productId) {
        Product productById = null;

        for(Product product : listOfProducts) {
            if(product!=null && product.getProductId()!=null &&
                    product.getProductId().equals(productId)){
                productById = product;
                break;
                }
            }
        if(productById == null){
            throw new IllegalArgumentException("No products found with the product id: "+ productId);
        }
        return productById;
    }

}

The service layer:

package com.packt.webstore.service;

public interface OrderService {
    void processOrder(String productId, int count);

}
package com.packt.webstore.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.packt.webstore.domain.Product;
import com.packt.webstore.domain.repository.ProductRepository;
import com.packt.webstore.service.OrderService;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ProductRepository productRepository;

    @Override
    public void processOrder(String productId, int quantity) {
        Product productById = productRepository.getProductById(productId);
        if(productById.getUnitsInStock() < quantity){
            throw new IllegalArgumentException("Out of Stock. Available Units in stock"+ productById.getUnitsInStock());
        }
        productById.setUnitsInStock(productById.getUnitsInStock() - quantity);
    }

}

Controller Layer:

package com.packt.webstore.controller;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.packt.webstore.domain.repository.ProductRepository;

@Controller
public class ProductController {

    @Autowired
    private ProductRepository productRepository;

    @RequestMapping("/products")
    public String list(Model model) {
        model.addAttribute("products", productRepository.getAllProducts());
        return "products";
    }

}
package com.packt.webstore.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.packt.webstore.service.OrderService;

@Controller
public class OrderController {
    @Autowired
    private OrderService orderService;

    @RequestMapping("/order/P1234/20")
    public String process() {
        orderService.processOrder("P1234", 20);
        return "redirect:/products";
    }
}

view jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<title>Product</title>
</head>
<body>
    <section>
        <div class="jumbotron">
            <div class="container">
            <h1>Products</h1>
            <p>All the available products in our store</p>
            </div>
        </div>
    </section>
    <section class="container">
        <div class="row">
            <c:forEach items="${products}" var="product">
            <div class="col-sm-6 col-md-3" style="padding-bottom: 15px">
                <div class="thumbnail">
                    <div class="caption">
                    <h3>${product.name}</h3>
                    <p>${product.description}</p>
                    <p>$${product.unitPrice}</p>
                    <p>Available ${product.unitsInStock} units in stock</p>
                    </div>
                </div>
            </div>
            </c:forEach>
        </div>
    </section>
</body>
</html>

一个最简单的SPRINGMVC示例的更多相关文章

  1. Skinned Mesh原理解析和一个最简单的实现示例

    Skinned Mesh 原理解析和一个最简单的实现示例   作者:n5 Email: happyfirecn##yahoo.com.cn Blog: http://blog.csdn.net/n5 ...

  2. springmvc 项目完整示例01 需求与数据库表设计 简单的springmvc应用实例 web项目

    一个简单的用户登录系统 用户有账号密码,登录ip,登录时间 打开登录页面,输入用户名密码 登录日志,可以记录登陆的时间,登陆的ip 成功登陆了的话,就更新用户的最后登入时间和ip,同时记录一条登录记录 ...

  3. springMVC初探--环境搭建和第一个HelloWorld简单项目

    注:此篇为学习springMVC时,做的笔记整理. MVC框架要做哪些事情? a,将url映射到java类,或者java类的方法上 b,封装用户提交的数据 c,处理请求->调用相关的业务处理—& ...

  4. [MySQL5.6] 一个简单的optimizer_trace示例

    [MySQL5.6] 一个简单的optimizer_trace示例   前面已经介绍了如何使用和配置MySQL5.6中optimizer_trace(点击博客),本篇我们以一个相对简单的例子来跟踪op ...

  5. 创建一个可用的简单的SpringMVC项目,图文并茂

    转载麻烦注明下来源:http://www.cnblogs.com/silentdoer/articles/7134332.html,谢谢. 最近在自学SpringMVC,百度了很多资料都是比较老的,而 ...

  6. 一个简单的springmvc例子 入门(1)

    一直是从事棋牌游戏,平常用的东西 大多数只是使用一些javase的一些 api对spring 这方面 用到的比较少,每次学了都忘,始终记不住.为了 更轻松学习springboot,从新学习了sprin ...

  7. 一个简单的CSS示例

    1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 & ...

  8. (转)Web Service入门简介(一个简单的WebService示例)

    Web Service入门简介 一.Web Service简介 1.1.Web Service基本概念 Web Service也叫XML Web Service WebService是一种可以接收从I ...

  9. Web Service入门简介(一个简单的WebService示例)

    Web Service入门简介 一.Web Service简介 1.1.Web Service基本概念 Web Service也叫XML Web Service WebService是一种可以接收从I ...

随机推荐

  1. U盘在电脑上安装CentOS 7 系统过程详解

    U盘制作CentOS系统启动盘 在电脑上下载并安装UltraISO软件,如百度云:http://pan.baidu.com/s/1hrGtvEG 打开UltraISO软件,找到CentOS.iso的映 ...

  2. ShaderLab中vertex fragment类Shader基础格式笔记

    //U3D用的shader语言叫ShaderLab,基础语法官方文档地址 //https://docs.unity3d.com/Manual/SL-Shader.html //开头指明名字,可以在别的 ...

  3. Akka源码分析-官方文档说明

    如果有小伙伴在看官方文档的时候,发现有些自相矛盾的地方,不要怀疑,可能是官方文档写错了或写的不清楚,毕竟它只能是把大部分情况描述清楚.开源代码一直在更新,官方文档有没有更新就不知道了,特别是那些官方不 ...

  4. tomcat生成catalina.out文件

    生成catalina.out方法 导语:本文为Windows下生tomcat将控制台信息输出到catalina.out文件  且 保证能实时查看日志文件的方法. 一.创建catalina.out 1. ...

  5. Node.js的运行

    nodejs的运行 首先要在你的电脑上下载node.js并安装,大家可以去官网下载 1.第一种方法:去官网下载git,安装好后,在桌面上单击鼠标右键,会有一个Git Bash Here,然后在新建一个 ...

  6. ionic2\ionic3 自定义弹窗

    ionic2及ionic3没有了popup及 其templateUrl属性 那我们如何对弹窗里加入自定义元素 从而达到自定义弹窗样式 那么就可以通过写h5页面来实现 自定义弹窗效果: 写个H5的弹窗及 ...

  7. WEB开发模式浅析

    WEB技术随着互联网的崛起而崛起,又随着移动互联网的发展而呈现更加多样化的趋势. 黑暗时代:大约在2005年以前,所谓的WEB开发主要还是美工的活,HTML/CSS占主导,Dreamwaver做为页面 ...

  8. JS高级——变量提升

    JS执行过程 1.首先是预解析:预解析过程最重要的是提升,在JavaScript代码在预解析阶段,会对以var声明的变量名,和function开头的语句块,进行提升操作 2.执行操作 全局中解析和执行 ...

  9. JS高级——逻辑中断

    1.表达式1||表达式2:表达式1为真,返回表达式1:表达式1为假,返回表达式2 2.表达式1&&表达2:表达式1为真,返回表达式2:表达式1为假,返回表达式1

  10. 4xx错误的本质:服务器已经接收到请求

    4xx错误的本质:服务器已经接收到请求, 路径错误! { URL: http://10.100.138.32:8046/3-0/app/account/maxin } { status code: 4 ...