一、项目搭建

同:http://www.cnblogs.com/bjlhx/p/8324971.html

1)新建maven项目→使用默认配置即可

定义好项目名称等

2)修改jdk版本

    <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>

3)增加spring-boot-dependencies

    <dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.5.9.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

4)在pom的dependencies增加依赖

    <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

不需要增加spring-boot-starter包,在spring-boot-starter-web中已经包含了

5)增加main方法启动程序即可

@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}

可增加一个示例,增加一个UserController

@Controller
public class UserController { @RequestMapping("/user/home")
@ResponseBody
public String home() {
return "user home";
} }

访问:http://127.0.0.1:8080/user/home即可

二、基本配置

1.启动端口

默认配置文件在src/main/resource下的application.properties

服务启动端口

server.port=80

2.请求路径与方式

    @RequestMapping(value = "/user/home", method = RequestMethod.GET)
@ResponseBody
public String home() {
return "user home";
}

以前的方式使用RequestMapping

在4.3以后提供以下方式

    @GetMapping(value = "/user/show")
@ResponseBody
public String show() {
return "user show";
} @PostMapping(value = "/user/create")
@ResponseBody
public String create() {
return "user create";
}

即:GetMapping、PostMapping

3、获取请求参数

根据处理的Request的不同内容部分分为四类:(主要讲解常用类型)

A、处理requet uri 部分(这里指uri template中variable,不含queryString部分)的注解:   @PathVariable;

B、处理request header部分的注解:   @RequestHeader, @CookieValue;

C、处理request body部分的注解:@RequestParam,  @RequestBody;

D、处理attribute类型是注解: @SessionAttributes, @ModelAttribute;

3.1、获取url参数@PathVariable

当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId}, 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。

@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController { @RequestMapping("/pets/{petId}")
public void findPet(@PathVariable("ownerId") String ownerId, @PathVariable String petId, Model model) {
// implementation omitted
}
}

上面代码把URI template 中变量 ownerId的值和petId的值,绑定到方法的参数上。若方法参数名称和需要绑定的uri template中变量名称不一致,需要在@PathVariable("name")指定uri template中的名称。

3.2、获取请求头中参数@RequestHeader、@CookieValue

@RequestHeader 注解,可以把Request请求header部分的值绑定到方法的参数上。

示例代码:

这是一个Request 的header部分:

Host                    localhost:8080
Accept text/html,application/xhtml+xml,application/xml;q=0.9
Accept-Language fr,en-gb;q=0.7,en;q=0.3
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 300
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive) {
//...
}

上面的代码,把request header部分的 Accept-Encoding的值,绑定到参数encoding上了, Keep-Alive header的值绑定到参数keepAlive上。

JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84  

参数绑定的代码:

@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie) {
//...
}

即把JSESSIONID的值绑定到参数cookie上。

3.3、获取请求参数@RequestParam, @RequestBody

@RequestParam

A) 常用来处理简单类型的绑定,通过Request.getParameter() 获取的String可直接转换为简单类型的情况( String--> 简单类型的转换操作由ConversionService配置的转换器来完成);因为使用request.getParameter()方式获取参数,所以可以处理get 方式中queryString的值,也可以处理post方式中 body data的值;

B)用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST;

C) 该注解有两个属性: value、required; value用来指定要传入值的id名称,required用来指示参数是否必须绑定;

示例代码:

@Controller
@RequestMapping("/pets")
@SessionAttributes("pet")
public class EditPetForm {
@RequestMapping(method = RequestMethod.GET)
public String setupForm(@RequestParam("petId") int petId, ModelMap model) {
Pet pet = this.clinic.loadPet(petId);
model.addAttribute("pet", pet);
return "petForm";
}

@RequestBody

该注解常用来处理Content-Type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;

它是通过使用HandlerAdapter 配置的HttpMessageConverters来解析post data body,然后绑定到相应的bean上的。

因为配置有FormHttpMessageConverter,所以也可以用来处理 application/x-www-form-urlencoded的内容,处理完的结果放在一个MultiValueMap<String, String>里,这种情况在某些特殊需求下使用,详情查看FormHttpMessageConverter api;

示例代码:

@RequestMapping(value = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
writer.write(body);
}
@RequestMapping(value = "/getUser", method = RequestMethod.POST)
public void handle2(@RequestBody User user) throws IOException {
//....
}

3.4、处理attribute类型@SessionAttributes, @ModelAttribute

@SessionAttributes:

该注解用来绑定HttpSession中的attribute对象的值,便于在方法中的参数里使用。

该注解有value、types两个属性,可以通过名字和类型指定要使用的attribute 对象;

示例代码:

@Controller
@RequestMapping("/editPet.do")
@SessionAttributes("pet")
public class EditPetForm {
// ...
}

@ModelAttribute

该注解有两个用法,一个是用于方法上,一个是用于参数上;

用于方法上时: 通常用来在处理@RequestMapping之前,为请求绑定需要从后台查询的model;

用于参数上时: 用来通过名称对应,把相应名称的值绑定到注解的参数bean上;要绑定的值来源于:

A) @SessionAttributes 启用的attribute 对象上;

B) @ModelAttribute 用于方法上时指定的model对象;

C) 上述两种情况都没有时,new一个需要绑定的bean对象,然后把request中按名称对应的方式把值绑定到bean中。

用到方法上@ModelAttribute的示例代码:

// Add one attribute
// The return value of the method is added to the model under the name "account"
// You can customize the name via @ModelAttribute("myAccount") @ModelAttribute
public Account addAccount(@RequestParam String number) {
return accountManager.findAccount(number);
}

这种方式实际的效果就是在调用@RequestMapping的方法之前,为request对象的model里put(“account”, Account);

用在参数上的@ModelAttribute示例代码:

@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@ModelAttribute Pet pet) { }

首先查询 @SessionAttributes有无绑定的Pet对象,若没有则查询@ModelAttribute方法层面上是否绑定了Pet对象,若没有则将URI template中的值按对应的名称绑定到Pet对象的各属性上。

3.5、支持注入Servletapi,HttpServletRequest

    @GetMapping(value = "/user/ip")
@ResponseBody
public String edit(HttpServletRequest req) {
return "user edit " + req.getRemoteHost();
}

注:支持混用

@RequestBody和@RequestParam同时使用

请求

post http://url?age=123
{
id: "",
username: "",
email: "",
phone: ""
}

spring接收

@RequestMapping(value = "", method = RequestMethod.POST)
public Result get(@RequestBody User user,
@RequestParam("age") String age) throws Exception { }

4、RestController

为了简化每一个都加@ResponseBody

表明了当前Controller的方法返回值可以直接作为ResponseBody输出。

@ResponseBody

@Responsebody 注解表示该方法的返回的结果直接写入 HTTP 响应正文(ResponseBody)中,一般在异步获取数据时使用,通常是在使用 @RequestMapping 后,返回值通常解析为跳转路径,加上 @Responsebody 后返回结果不会被解析为跳转路径,而是直接写入HTTP 响应正文中。
作用:
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。
使用时机:
返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

三、Spring boot中

1.使用jsp

1.1、增加maven:tomcat-embed-jasper;【版本可以根据具体是否添加】

<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>

1.2、增加配置

spring.mvc.view.prefix=/WEB-INF/jsp
spring.mvc.view.suffix=.jsp/

1.3、增加Controller

@Controller
public class LoginController {
@PostMapping("/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
if (username.equals(password)) {
return "/ok";
}
return "/fail";
}
}

注:方法直接返回String,就代表路径+jsp页面名【不含扩展名】

注意:注解使用Controller,不是RestController

1.4、增加jsp页面

位置:src/main/webapp下简历WEB-INF/jsp文件夹

ok.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>Insert title here</title>
</head>
<body>ok
</body>
</html>

fail.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>Insert title here</title>
</head>
<body>
fail
</body>
</html>

2、给jsp传递参数

java端,Model 的addAttribute,相当于request.setAttribute

    @GetMapping("/login")
public String loginIndex(Model model) {
model.addAttribute("username","root");
return "/login";
}

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>Insert title here</title>
</head>
<body>
${username}
</body>
</html>

3、模板freemarker

注:尽量先注释掉jsp的设置,pom,配置文件设置

3.1、增加pom

        <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

3.2、默认位置于classpath的templates下

reg.ftl

<h1>reg page</h1>

可以查看spring-boot-autoconfigure包,在org.springframework.boot.autoconfigure.freemarker.FreeMarkerProperties中查看

@ConfigurationProperties(prefix = "spring.freemarker")
public class FreeMarkerProperties extends AbstractTemplateViewResolverProperties { public static final String DEFAULT_TEMPLATE_LOADER_PATH = "classpath:/templates/"; public static final String DEFAULT_PREFIX = ""; public static final String DEFAULT_SUFFIX = ".ftl";

路径:classpath:/templates,默认扩展名:.ftl

模板路径配置:spring.freemarker.templateLoaderPath=classpath:/ftl

4、模板freemarker参数传递

同2一致

5、web容器

5.1、默认是tomcat,更换jetty

排除tomcat。将web修改

        <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>

增加jetty

        <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

注意查看

spring-boot-autoconfigure包,在org.springframework.boot.autoconfigure.web.ServerProperties中查看,如何配置web容器配置

server.port=8080
server.contextPath=/

注意:善用contextPath做虚拟目录

012-Spring Boot web【一】web项目搭建、请求参数、RestController、使用jsp、freemarker,web容器tomcat和jetty的更多相关文章

  1. Spring Boot + MyBatis 多模块项目搭建教程

    一.前言 1.开发工具及系统环境 IDE:IntelliJ IDEA 2020.2.2 系统环境:Windows 2.项目目录结构 biz层:业务逻辑层 dao层:数据持久层 web层:请求处理层 二 ...

  2. How to configure spring boot through annotations in order to have something similar to <jsp-config> in web.xml?

    JSP file not rendering in Spring Boot web application You will need not one but two dependencies (ja ...

  3. Spring Boot 2+gRPC 学习系列1:搭建Spring Boot 2+gRPC本地项目

    Spring Boot 2+gRPC 学习系列1:搭建Spring Boot 2+gRPC本地项目 https://blog.csdn.net/alinyua/article/details/8303 ...

  4. [转] 使用Spring Boot和Gradle创建项目

    Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的 ...

  5. Spring Boot微服务框架的搭建

    (1)spring boot简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发 ...

  6. Spring Boot 创建hello world项目

    Spring Boot 创建hello world项目 1.创建项目 最近在学习Spring Boot,这里记录使用IDEA创建Spring Boot的的过程 在1出勾选,选择2,点击Next 这里填 ...

  7. 10个Spring Boot快速开发的项目,接私活利器(快速、高效)

    本文为大家精选了 码云 上优秀的 Spring Boot 语言开源项目,涵盖了企业级系统框架.文件文档系统.秒杀系统.微服务化系统.后台管理系统等,希望能够给大家带来一点帮助:) 1.项目名称:分布式 ...

  8. 八个开源的 Spring Boot 前后端分离项目,一定要收藏!

    八个开源的 Spring Boot 前后端分离项目 最近前后端分离已经在慢慢走进各公司的技术栈,不少公司都已经切换到这个技术栈上面了.即使贵司目前没有切换到这个技术栈上面,我们也非常建议大家学习一下前 ...

  9. spring boot用ide新建项目遇到的restcontroller不能导入的问题

    才开始学习spring boot,第一个程序helloworld就碰到@RestController和@RequestMapping(/hello)的注解都会报错的问题. 我个人的解决方法: 1.sp ...

  10. spring cloud和spring boot两个完整项目

    spring cloud和spring boot两个完整项目 spring cloud 是基于Spring Cloud的云分布式后台管理系统架构,核心技术采用Eureka.Fegin.Ribbon.Z ...

随机推荐

  1. 怎么处理Win10系统更新提示代码0x80070057的错误?

    在使用好系统重装助手重装了Win10系统后,由于每个用户的电脑配置不同,有些用户会在更新时出现0x80070057的错误代码.下面就教大家Win10系统更新出现0x80070057错误该怎么解决. W ...

  2. Qt 4.8.5 + MinGW32 + Qt creater 安装

    Qt 4.8.5 + MinGW32 + Qt creater 安装 下载文件 文件版本 Qt 4.8.5 MinGW 0.4.4 Qt Creator 2.8或2.8.1 gdb-7.4-MinGW ...

  3. 从c到c++<四>

    总结一下:内联函数实际上就是用inline修饰的函数,这些函数会在编译时由编译器来将代码展开,而不用像上面第二点提到的人工展开,它的使用场景:代码很短.使用频率高. 具体代码如下: 对于这两者实际上还 ...

  4. PHP 基础知识-数组

    PHP 的数组主要分为: 索引数组 - 带有数字索引的数组 关联数组 - 带有指定键的数组 多维数组 - 包含一个或多个数组的数组   索引数组:   有两种创建索引数组的方法: 索引是自动分配的(索 ...

  5. Nginx中ngx_http_headers_module

    *向由代理理服务器器响应给客户端的响应报⽂文添加⾃自定义⾸首部,或修改指定⾸首部的值**指令:14.1 add_header添加⾃自定义⾸首部Syntax: add_header name value ...

  6. idea 复制多条字符串

    ctrl+c复制信息后可以通过ctrl+shift+v查看最近复制的字符串

  7. SEERC 2018 B. Broken Watch (CDQ分治)

    题目链接:http://codeforces.com/gym/101964/problem/B 题意:q 种操作,①在(x,y)处加一个点,②加一个矩阵{(x1,y1),(x2,y2)},问每次操作后 ...

  8. angularjs 动态计算平均值

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  9. flutter布局-1-column

    1.mainAxisAlignment:主轴布局方式,column主轴方向是垂直的方向   mainaxis.png 默认值:MainAxisAlignment.start: start ,沿着主轴方 ...

  10. HTML的列表,表格与媒体元素

    一.无序列表 <ul>                            <li>无序列表</li>                            &l ...