开发web应用

# 开发Spring web应用,最基本的需要构建以下组件:

  1.pojo类(从数据库获取数据)

   2.pringmvc控制器

   3.视图模板(页面)

##第一步 构建pojo类  

package tacos.pojo;

import lombok.Data;
import lombok.RequiredArgsConstructor; @Data
@RequiredArgsConstructor
public class Ingredient { private final String id; @SuppressWarnings("unused")
private final String name; private final Type type; public static enum Type{
WARP,PROTEIN,VEGGIES,CHEESE,SAUCE
} }

###1.lombok 

 https://www.cnblogs.com/jthr/p/14139880.html

##第二步 构建控制器类,控制器类的作用是处理请求

 ###例子

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import lombok.extern.slf4j.Slf4j;
import tacos.Ingredient;
import tacos.Ingredient.Type; @Slf4j
@Controller
@RequestMapping("/design")
public class DesignTacoController { @ModelAttribute //会在这个controller类中每个请求方法执行前被执行
public void addIngredientsToModel(Model model) {
    List<Ingredient> ingredients = Arrays.asList(
      new Ingredient("FLTO", "Flour Tortilla", Type.WRAP),
      new Ingredient("COTO", "Corn Tortilla", Type.WRAP),
      new Ingredient("GRBF", "Ground Beef", Type.PROTEIN),
      new Ingredient("CARN", "Carnitas", Type.PROTEIN),
      new Ingredient("TMTO", "Diced Tomatoes", Type.VEGGIES),
      new Ingredient("LETC", "Lettuce", Type.VEGGIES),
      new Ingredient("CHED", "Cheddar", Type.CHEESE),
      new Ingredient("JACK", "Monterrey Jack", Type.CHEESE),
      new Ingredient("SLSA", "Salsa", Type.SAUCE),
      new Ingredient("SRCR", "Sour Cream", Type.SAUCE)
    );
    
    Type[] types = Ingredient.Type.values();
    for (Type type : types) {
      model.addAttribute(type.toString().toLowerCase(),
          filterByType(ingredients, type));
    }
}
    

  @GetMapping("showDesignForm")
  public String showDesignForm(Model model) {
    model.addAttribute("design", new Taco());
    return "design";
  }

 @PostMapping
  public String processDesign(Design design) {
    // Save the taco design...
    // We'll do this in chapter 3
    log.info("Processing design: " + design);

    return "redirect:/orders/current"; //重定向
  }

private List<Ingredient> filterByType(
List<Ingredient> ingredients, Type type) {
return ingredients
.stream()
.filter(x -> x.getType().equals(type))
.collect(Collectors.toList());
}
}

 ###1.注解说明

  @Slf4j注解说明:相当于 private static final Logger log = LoggerFactory.getLogger(Slf4jDemo.class);

  springmvc常用注解

  @RequestMapping   通用的梳理请求

  @GetMapping  处理get请求

  @PostMapping  处理Post请求

  @PutMapping  处理Put请求

  @DeleteMapping  处理Delete请求

  @PatchMapping  处理Patch请求

  通常我们可以在类上使用@RequestMapping指定通用路径,然后在方法上使用下面几个注解细化请求形式和具体路径

 注解:@ModelAttribute
  
该注解会使该方法在这个controller类中每个请求方法执行前被执行,如访问/design/showDesignForm,会先经过addIngredientsToModel方法

  springmvc参数接收常用方法 - https://www.cnblogs.com/jthr/p/13476648.html

###2.参数返回视图

@GetMapping("showDesignForm")
public String showDesignForm(Model model) {
model.addAttribute("design", new Taco());
return "design";
}

  这个接口直接返回的视图路径。没有返回参数。像Thymeleaf这样的视图库无法与控制器放到modal中的数据协同工作,但是它可以与request属性写作,所以,在spring返回视图前,它会将模型数据赋值到request属性中。这样在视图中可以获取到modal的数据。

###3.表单校验

  在pojo类上加上注解-设置校验规则

@Data
public class Order { @NotBlank(message="Name is required") //非空校验
private String name; @NotBlank(message="Street is required")
private String street; @NotBlank(message="City is required")
private String city; @NotBlank(message="State is required")
private String state; @NotBlank(message="Zip code is required")
private String zip; @CreditCardNumber(message="Not a valid credit card number") //信用卡号校验
private String ccNumber; @Pattern(regexp="^(0[1-9]|1[0-2])([\\/])([1-9][0-9])$", //正则校验
message="Must be formatted MM/YY")
private String ccExpiration; @Digits(integer=3, fraction=0, message="Invalid CVV")
private String ccCVV; }

在表单绑定的时候执行校验

  

  @PostMapping
public String processOrder(@Valid Order order, Errors errors) {
if (errors.hasErrors()) {
return "orderForm";
} log.info("Order submitted: " + order);
return "redirect:/";
}

  @Valid Order order

  这个注解告诉springmvc对Order 进行校验,如果校验存在错误,会捕捉一个error对象,返回视图

##对于某些请求,他们不需要填充模型,也不需要处理输入,也就是一个请求进来,不用参数,且直接返回视图 ,我们可以声明视图控制器

  这个类我们实现了WebMvcConfigurer接口,它定义了多个方法来配置springmvc

@Configuration
public class WebConfig implements WebMvcConfigurer { @Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("homeview");  //这里它会处理/home这个请求,并且返回到/homeview这个视图
} }

这里就要用到配置类了@Configuration,在这个新的配置类中声明视图控制器

  

  

      

 

   

spring-in-action_day02的更多相关文章

  1. 基于spring注解AOP的异常处理

    一.前言 项目刚刚开发的时候,并没有做好充足的准备.开发到一定程度的时候才会想到还有一些问题没有解决.就比如今天我要说的一个问题:异常的处理.写程序的时候一般都会通过try...catch...fin ...

  2. 玩转spring boot——快速开始

    开发环境: IED环境:Eclipse JDK版本:1.8 maven版本:3.3.9 一.创建一个spring boot的mcv web应用程序 打开Eclipse,新建Maven项目 选择quic ...

  3. Spring基于AOP的事务管理

                                  Spring基于AOP的事务管理 事务 事务是一系列动作,这一系列动作综合在一起组成一个完整的工作单元,如果有任何一个动作执行失败,那么事务 ...

  4. [Spring]IoC容器之进击的注解

    先啰嗦两句: 第一次在博客园使用markdown编辑,感觉渲染样式差强人意,还是github的样式比较顺眼. 概述 Spring2.5 引入了注解. 于是,一个问题产生了:使用注解方式注入 JavaB ...

  5. 学习AOP之透过Spring的Ioc理解Advisor

    花了几天时间来学习Spring,突然明白一个问题,就是看书不能让人理解Spring,一方面要结合使用场景,另一方面要阅读源代码,这种方式理解起来事半功倍.那看书有什么用呢?主要还是扩展视野,毕竟书是别 ...

  6. 学习AOP之深入一点Spring Aop

    上一篇<学习AOP之认识一下SpringAOP>中大体的了解了代理.动态代理及SpringAop的知识.因为写的篇幅长了点所以还是再写一篇吧.接下来开始深入一点Spring aop的一些实 ...

  7. 学习AOP之认识一下Spring AOP

    心碎之事 要说知道AOP这个词倒是很久很久以前了,但是直到今天我也不敢说非常的理解它,其中的各种概念即抽象又太拗口. 在几次面试中都被问及AOP,但是真的没有答上来,或者都在面上,这给面试官的感觉就是 ...

  8. 为什么做java的web开发我们会使用struts2,springMVC和spring这样的框架?

    今年我一直在思考web开发里的前后端分离的问题,到了现在也颇有点心得了,随着这个问题的深入,再加以现在公司很多web项目的控制层的技术框架由struts2迁移到springMVC,我突然有了一个新的疑 ...

  9. Spring之旅(2)

    Spring简化Java的下一个理念:基于切面的声明式编程 3.应用切面 依赖注入的目的是让相互协作的组件保持松散耦合:而AOP编程允许你把遍布应用各处的功能分离出来形成可重用的组件. AOP面向切面 ...

  10. Spring之旅

    Java使得以模块化构建复杂应用系统成为可能,它为Applet而来,但为组件化而留. Spring是一个开源的框架,最早由Rod Johnson创建.Spring是为了解决企业级应用开发的复杂性而创建 ...

随机推荐

  1. 第2-3-1章 文件存储服务系统-nginx/fastDFS/minio/阿里云oss/七牛云oss

    目录 文件存储服务 1. 需求背景 2. 核心功能 3. 存储策略 3.1 本地存储 3.2 FastDFS存储 3.3 云存储 3.4 minio 4. 技术设计 文件存储服务 全套代码及资料全部完 ...

  2. 二叉树总结——BiTree

    在C++编译器下可直接运行 #include <stdio.h> #include <malloc.h> //算法思想:先读入根结点数据,并且创建根结点,在读入左子树数据并创建 ...

  3. 【深入浅出 Yarn 架构与实现】3-3 Yarn Application Master 编写

    本篇文章继续介绍 Yarn Application 中 ApplicationMaster 部分的编写方法. 一.Application Master 编写方法 上一节讲了 Client 提交任务给 ...

  4. ubuntu undefined reference to

    温馨提示,请使用ctrl+F进行快速查找 libdl.so undefined reference to `dlsym' undefined reference to `dlopen' undefin ...

  5. vue 3.0 常用api 的简介

    vue3.0 生命周期 写法一 和vue2.x 一致 区别在于(beforeUnmount.unmount)名称不一样 写法二 在setup 中使用, 需要引用 如: import { onBefor ...

  6. ElasticSearch7.6.1学习笔记-狂神

    ElasticSearch:7.6.1 https://gitee.com/yujie.louis/elastic-search 笔记,代码,安装包等 什么是ElasticSearch? Elasti ...

  7. Vue 双向绑定数据已经更新,但是视图更新:

    使用ElementUI做动态增减表单项的时候,发现数据刷新后视图未更新 Vue包装了数个数组操作函数,使用这些方法操作的数组去,其数据变动时会被vue监测: push() pop() shift() ...

  8. 关于CSDN博客上传图片的接口研究

    代码实现 import requests from requests_toolbelt import MultipartEncoder import urllib.parse fields = { ' ...

  9. MySQL锁,锁的到底是什么?

    MySQL锁系列文章已经鸽了挺久了,最近赶紧挤了挤时间,和大家聊一聊MySQL的锁. 只要学计算机,「锁」永远是一个绕不过的话题.MySQL锁也是一样. 一句话解释MySQL锁: MySQL锁是解决资 ...

  10. 【sqoop】简介、原理、安装配置测试、导入导出案例、脚本打包、常见命令及参数介绍、常用命令举例

    一.sqoop简介 用于在Hadoop(Hive)与传统的数据库(mysql.oracle...)之间进行数据的传递,可以将一个关系型数据库(例如 : MySQL ,Oracle ,Postgres等 ...