一个最简单的SPRINGMVC示例

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

这个分得确实比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>

时间: 2024-10-08 00:10:58

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

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

注:此篇为学习springMVC时,做的笔记整理. MVC框架要做哪些事情? a,将url映射到java类,或者java类的方法上 b,封装用户提交的数据 c,处理请求->调用相关的业务处理—>封装响应的数据 d,将响应的数据进行渲染 springMVC框架有什么优点? 性能比struts2好 简单便捷易学,能进行更简洁的web层开发 天生和spring无缝集成 使用约定优于配置 能够进行简单junit测试 支持restful风格 异常处理,本地化国际化,数据验证,拦截器 提供一套强大的JSP

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

[MySQL5.6] 一个简单的optimizer_trace示例 前面已经介绍了如何使用和配置MySQL5.6中optimizer_trace(点击博客),本篇我们以一个相对简单的例子来跟踪optimizer_trace的产生过程. 本文的目的不是深究查询优化器的实现,只是跟踪optimizer trace在优化器的那一部分输出,因此很多部分只是一带而过,对于需要深究的部分,暂时标注为红色,后续再扩展阅读;之前一直没看过这部分代码,理解起来还是比较困难的… 我们以一个简单的表为例过一下opti

一个超级简单的HTML模板框架源代码以及使用示例

HTML模板框架源代码 var HtmlTemplate = (function () { function HtmlTemplate(htmlSource) { this.htmlSource = htmlSource; } HtmlTemplate.prototype.toHTML = function (params) { var reg = HtmlTemplate.REG_FILTER_PARAM; var m = this.htmlSource.replace(reg, functi

一个简单的CRUD示例:使用PHP+MySQL

一个简单的CRUD示例:使用PHP+MySQL 前情 总是听说CRUD,但一直不清楚是做什么的,就去查了一下,大概的意思是一组常见的数据库操作:增(create).查(read).改(update)删(delete),大概是,也有其他的翻译,这里大概了解一下就好.截止到现在,网上好像没有什么很小的示例来阐述CRUD这个概念的,然后就去查了一番资料,写了一个真的很小白的.很简单.未使用任何框架的案例. 前端准备 由于笔者对前端知识并不熟悉,这里只贴容器(传输/返回数据的容器)代码,在服务器根目录下

使用Maven搭建简单的SpringMVC

之前想用Maven搭建个简单的SpringMVC框架,一直没成功,上网搜索了好多,不知道是自己操作的问题还是怎么,就是报错,或者运行不了. 今天偶得一篇教程,写的极好.晚上试着自己从新来一遍. 一. 安装SpringMVC所需jar包 配置pom.xml文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&quo

Epii.js 一个极其简单的Js模板引擎

Epii.js 简约而不简单的JavaScript模板引擎 项目地址 https://github.com/epaii/epii.js 极低门槛,拿来即用,别忘记star 特性 一个轻量级模板引擎,可快速实现数据与ui绑定(数据变动,UI自动变动),快速实现事件绑定和处理,不依赖任何第三方库,仅仅8k. 可快速应用于web开发,native+webapp开发,h5微网页开发,不与其它框架冲突. 让开发者更多关注与应用本身,而不用花费大量时间实现数据与ui的,和事件处理.效率大幅度提升. 名字由来

C# 一个WCF简单实例

C# 一个WCF简单实例 作者: 字体:[增加 减小] 类型:转载 时间:2012-10-27我要评论 以订票为例简单应用wcf程序,需要的朋友可以参考下 WCF实例(带步骤) 复制代码代码如下: <xmlnamespace prefix ="o" ns ="urn:schemas-microsoft-com:office:office" /> 本篇转自百度文档,自己试过,确实可以用. 以订票为例简单应用wcf 新建一个wcf服务应用程序 在IServi

unity Dotween插件的简单介绍及示例代码

unity里面做插值动画的插件有许多,比较常见的有itween.hotween.dotween.根据大家的反馈和实际体验来说,dotween插件在灵活性.稳定性.易用性上都十分突出.这里简单介绍下它的用法,并在后文做了一些效果示例,还是不错的. 所谓"插值动画",顾名思义就是在两个值中插入其他的值来实现动画.原理非常简单,比如想让某个物体从A地到达B地,我们只知道A和B的坐标,插值动画就可以根据"缓动函数"确定A.B间的其他值,来实现物体从A到B的"运动过

C#实现一个最简单的HTTP服务器

简介 本文用C#实现了一个最简单的HTTP服务器类,你可以将它嵌入到自己的项目中,或者也可以阅读代码来学习关于HTTP协议的知识. 背景 高性能的WEB应用一般都架设在强大的WEB服务器上,例如IIS, Apache, 和Tomcat.然而,HTML是非常灵活的UI标记语言,也就是说任何应用和后端服务都可以提供HTML的生成支持.在这个小小的例子中,像IIS,.Apache这样的服务器消耗的资源太大了,我们需要自己实现一个简单的HTTP服务器,将它嵌入到我们的应用中用来处理WEB请求.我们仅需要