zoukankan      html  css  js  c++  java
  • 012-Spring Boot web【一】web项目搭建、请求参数、RestController、使用jsp、freemarker,web容器tomcat和jetty

    一、项目搭建

    同: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>
    View Code

    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>
    View Code

    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);
        }
    }
    View Code

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

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

    访问: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";
        }
    View Code

    即: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";
        }
    }
    View Code

    注:方法直接返回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>
    View Code

    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>
    View Code

    2、给jsp传递参数

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

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

    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>
    View Code

    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";
    View Code

    路径: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>
    View Code

    增加jetty

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

    注意查看

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

    server.port=8080
    server.contextPath=/

    注意:善用contextPath做虚拟目录

  • 相关阅读:
    常用的清理 Kubernetes 集群命令
    mask彻底禁用systemctl服务
    ansibleplaybook指定role limit
    极速理解设计模式系列:16.迭代器模式(Iterator Pattern)
    极速理解设计模式系列:19.备忘录模式(Memento Pattern)
    极速理解设计模式系列:8.策略模式(Strategy Pattern)
    极速理解设计模式系列:6.适配器模式(Adapter Pattern)
    PostSharp AOP编程:2.PostSharp的OnMethodBoundaryAspect类基本组成
    极速理解设计模式系列:18.访问者模式(Visitor Pattern)
    极速理解设计模式系列:10.抽象工厂模式(Abstract Factory Pattern)
  • 原文地址:https://www.cnblogs.com/bjlhx/p/8372584.html
Copyright © 2011-2022 走看看