SpringBoot2.0系列--02--Controller

SpringBoot2.0系列–02–Controller

写在前面

controller是web项目中的控制器,就是和网络请求直接相关联的一环

示例

@RestController
@RequestMapping("/view")
public class HelloWorldController {

  @RequestMapping("/hello")
  public String index() {
    // 这里访问地址是 http://127.0.0.1:8080/view/hello
    return "Hello World";
  }

  @RequestMapping("/hello2")
  public String hello2() {
    // 这里访问地址是 http://127.0.0.1:8080/view/hello2
    return "Hello World 2";
  }
}  

比如我们现在又这么一个Controller,那么访问路径就是有:

http://127.0.0.1:8080/view/hello
http://127.0.0.1:8080/view/hello2

对应的方法就是index()和hello2()。

对于整个Controller类

关键代码请看最后

Controller注解

这个注解表示这个类会被当成一个controller,用于处理http请求。

可以返回一个页面,也可以返回一个字符串。

RestController注解

这个注解表示这个类会被当成一个controller。

并且返回的数据只会是一个字符串。

RequestMapping注解

表示这一个层级的目录。

比如设置值为aaa,那么这个类中所有的请求都是需要加上这一层的,

http://ip:port/aaa/xxx

对于Controller类中的方法

关键代码请看最后

RequestMapping

这个是网址最关键的一层,也是最后一层

如@RequestMapping("/hello2"),那么请求网址对应的就是

http://127.0.0.1:8080/view/hello2

 @RequestMapping("/hello2")
  public String hello2() {
    // 这里访问地址是 http://127.0.0.1:8080/hello2
    return "Hello World 2";
  }

RequestParam

这个是用?和&连接的参数:

http://127.0.0.1:8080/request-param?id=sadho

@RequestMapping("/request-param")
  public String requestParam(@RequestParam("id") String id) {
    // 这里访问地址是 http://127.0.0.1:8080/request-param?id=sadho
    return "requestParam id = " + id;
  }

PathVariable

这个是写在网址里面的参数

这里访问地址是 http://127.0.0.1:8080/path-param/sadho

@RequestMapping("/path-param/{id}")
  public String pathParam(@PathVariable("id") String id) {
    // 这里访问地址是 http://127.0.0.1:8080/path-param/sadho
    return "pathParam id = " + id;
  }

返回一个页面

这个类上面都需要加上@controller注解

返回静态页面–html

什么配置都不用搞,直接对应static下面的层级就好

@Controller
@RequestMapping("/view")
public class ViewController {

  @RequestMapping("/index")
  public String index() {
    // 返回的是一个静态页面
    // 对应static/view/index.html
    // 这里访问地址是 http://127.0.0.1:8080/view/index
    return "index.html";
  }


  @RequestMapping("/login")
  public String login() {
    // 返回的是一个静态页面
    // 对应static/login.html
    // 这里访问地址是 http://127.0.0.1:8080/view/login
    return "/login.html";
  }
}  

返回动态页面–freemarker

  1. 配置pom文件,添加freemarker
<!-- 添加视图模板 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
  1. 在templates下面添加freemarkerview.ftl
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>
<body>
show:${message}
</body>
</html>
  1. 在代码中进行映射
  @RequestMapping("/freemarker")
  public ModelAndView freemarker() {

    // 返回的是一个模板页面(动态)
    // 这里访问地址是 http://127.0.0.1:8080/view/freemarker
    ModelAndView mav = new ModelAndView();
    mav.addObject("message", "SpringBoot freemarker!");
    mav.setViewName("freemarkerview");
    return mav;
  }

全部代码

代码结构

重点看

  • HelloWorldController.java
  • ViewController.java
  • login.html
  • index.html
  • freemarkerview.ftl
D:.
│  .gitignore
│  mvnw
│  mvnw.cmd
│  pom.xml
│  pro002-controller.iml
│  
├─.mvn
│  └─wrapper
│          maven-wrapper.jar
│          maven-wrapper.properties
│          
├─src
│  ├─main
│  │  ├─java
│  │  │  └─com
│  │  │      └─lizhaoblog
│  │  │          └─pro002controller
│  │  │              │  Pro002ControllerApplication.java
│  │  │              │  
│  │  │              └─controller
│  │  │                      HelloWorldController.java
│  │  │                      ViewController.java
│  │  │                      
│  │  └─resources
│  │      │  application.properties
│  │      │  
│  │      ├─static
│  │      │  │  login.html
│  │      │  │  
│  │      │  └─view
│  │      │          index.html
│  │      │          
│  │      └─templates
│  │              freemarkerview.ftl
│  │              

代码

  • HelloWorldController.java
/*
 * Copyright (C), 2015-2018
 * FileName: HelloWorldController
 * Author:   zhao
 * Date:     2018/10/9 17:53
 * Description: HelloWorld控制器
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.lizhaoblog.pro002controller.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.server.PathParam;

/**
 * 〈一句话功能简述〉<br>
 * 〈HelloWorld控制器〉
 *
 * @author zhao
 * @date 2018/10/9 17:53
 * @since 1.0.1
 */
@RestController
public class HelloWorldController {

  @RequestMapping("/hello")
  public String index() {
    // 这里访问地址是 http://127.0.0.1:8080/hello
    return "Hello World";
  }

  @RequestMapping("/hello2")
  public String hello2() {
    // 这里访问地址是 http://127.0.0.1:8080/hello2
    return "Hello World 2";
  }

  @RequestMapping("/request-param")
  public String requestParam(@RequestParam("id") String id) {
    // 这里访问地址是 http://127.0.0.1:8080/request-param?id=sadho
    return "requestParam id = " + id;
  }

  @RequestMapping("/path-param/{id}")
  public String pathParam(@PathVariable("id") String id) {
    // 这里访问地址是 http://127.0.0.1:8080/path-param/sadho
    return "pathParam id = " + id;
  }

}

  • ViewController.java
/*
 * Copyright (C), 2015-2018
 * FileName: ViewController
 * Author:   zhao
 * Date:     2018/10/9 19:00
 * Description: 返回网页
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.lizhaoblog.pro002controller.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 〈一句话功能简述〉<br>
 * 〈返回网页〉
 *
 * @author zhao
 * @date 2018/10/9 19:00
 * @since 1.0.1
 */
@Controller
@RequestMapping("/view")
public class ViewController {

  @RequestMapping("/index")
  public String index() {
    // 返回的是一个静态页面
    // 对应static/view/index.html
    // 这里访问地址是 http://127.0.0.1:8080/view/index
    return "index.html";
  }


  @RequestMapping("/login")
  public String login() {
    // 返回的是一个静态页面
    // 对应static/login.html
    // 这里访问地址是 http://127.0.0.1:8080/view/login
    return "/login.html";
  }

  @RequestMapping("/freemarker")
  public ModelAndView freemarker() {

    // 返回的是一个模板页面(动态)
    // 这里访问地址是 http://127.0.0.1:8080/view/freemarker
    ModelAndView mav = new ModelAndView();
    mav.addObject("message", "SpringBoot freemarker!");
    mav.setViewName("freemarkerview");
    return mav;
  }


  @ResponseBody
  @RequestMapping("/stringbuf")
  public String stringbuf() {
    // 这里访问地址是 http://127.0.0.1:8080/view/stringbuf
    return "index.html";
  }

}

  • login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
login
</body>
</html>
  • index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
        @RequestMapping("/html")
        public ModelAndView html() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("index.html");
        return mav;
        }
</body>
</html>
  • freemarkerview.ftl
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>
<body>
show:${message}
</body>
</html>

联系方式

项目代码路径码云:https://gitee.com/lizhaoandroid/Springboot-Learning-lz

联系方式:QQ3060507060

查看下一篇或者其他文章,可点击目录或者专栏查看

发布了214 篇原创文章 · 获赞 166 · 访问量 227万+
展开阅读全文

Springboot controller问题

02-28

### 目前自己搭建了一个OA系统,还在搭建中,然后前端使用的是thymeleaf,我把前端的公共页面head,foot,和左边导航栏全部提取出来,放在IndexController中返回,然后head的导航栏上有一个天气实时展示,主页的时候能展示,但是我打开其他界面就不能展示,其他界面在不同的controller里面,请问一下这种是什么情况,希望大神帮忙解决! --- #### 下面是打开其他页面天气预报无响应代码 ``` @Controller @RequestMapping("/") public class CustomerController { @Resource private IOaCustomerInfoService oaCustomerInfoService; /** * 客户数据展示 */ @GetMapping("/customer") public String allCustomer(Model model) { List<OaCustomerInfo> allList = oaCustomerInfoService.getAllCustomerInfo(); model.addAttribute("customers",allList); return "more/customer"; } } ``` ### 下面是主页可以出现天气预报的代码 ``` @Controller @RequestMapping("/") public class IndexController { @Resource private IOaCustomerService oaCustomerService; @Resource private IOaCityCodeService oaCityCodeService; @Resource private IOaCustomerInfoService oaCustomerInfoService; @Resource private IOaUserPerfService oaUserPerfService; /** * 主页 */ @RequestMapping(value = "/index") public String index() { return "index"; } /** * 公共头head页面 */ @RequestMapping(value = "/head") public String test() { return "head"; } /** * 公共左导航栏left页面 */ @RequestMapping(value = "/left") public String left() { return "left"; } /** * 公共尾部foot页面 */ @RequestMapping(value = "/foot") public String foot() { return "foot"; } /** * 账户设置界面 */ @RequestMapping(value = "/settings") public String settings() { return "more/settings"; } /** * 网页头部Head天气预报展示 * * @param request * @param model */ // @GetMapping(value = "/head") @ModelAttribute public void addressAndWeather(HttpServletRequest request, Model model) { String ip = IPUtil.getIpAddrByRequest(request); System.out.println("登录IP:" + ip); JSONObject address = AddressAndWeatherUtils.returnAddress(ip); String cityName = address.getString("city"); System.out.println("城市:" + cityName); cityName = cityName.substring(0, cityName.length() - 1); OaCityCode code = oaCityCodeService.getCodeByName(cityName); try { String str = AddressAndWeatherUtils.returnWeatherJson(code.getCityCode().toString()); JSONObject weatherJson = JSONObject.parseObject(str); JSONObject today = weatherJson.getJSONObject("data").getJSONArray("forecast").getJSONObject(0); String high = today.getString("high"); String low = today.getString("low"); // 截掉多余字符 high = high.substring(3); low = low.substring(3); String returnWeb = cityName + " " + low + "~" + high; model.addAttribute("weather", returnWeb); } catch (Exception e) { e.printStackTrace(); } } } ``` html ``` <!doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>客户管理</title> <link th:href="@{/vendor/simple-line-icons/css/simple-line-icons.css}" rel="stylesheet"/> <link th:href="@{/vendor/font-awesome/css/fontawesome-all.min.css}" rel="stylesheet"/> <link th:href="@{/css/styles.css}" rel="stylesheet"/> <link th:href="@{/css/customerButton.css}" rel="stylesheet"/> </head> <body class="sidebar-fixed header-fixed"> <div th:replace="head::header-body"></div> <div th:replace="left::left-body"></div> <div class="page-wrapper"> <div class="content"> <div class="col-md-12"> <div class="card"> <div class="card-header bg-light"> 客户管理 </div> <div class="card-body"> <div class="table-responsive"> <button type="button" class="btn btn-primary" ><span class="fa fa-plus-square"></span> 客户新增 </button> <table class="table table-striped"> <thead> <tr> <th>序号</th> <th>姓名</th> <th>手机号</th> <th>添加日期</th> <th>修改日期</th> <th>意向度</th> <th>操作</th> </tr> </thead> <tbody> <tr th:each="customer,iterStat:${customers}"> <td th:text="${iterStat.count}"></td> <td th:text="${customer.occupation}"></td> <td class="text-nowrap" th:text="${customer.tel}"></td> <td th:text="${#dates.format(customer.opentime,'yyyy-MM-dd HH:mm:ss')}"></td> <td th:text="${#dates.format(customer.updatetime,'yyyy-MM-dd HH:mm:ss')}"></td> <td th:text="${customer.intention}"></td> <td> <button type="button" class="customerbuttonGreen"><span class="fa fa-search"></span> 跟进详情 </button> <button type="button" class="customerbutton"><span class="fa fa-eraser"></span> 修改跟进 </button> <button type="button" class="customerbuttonRed"><span class="fa fa-trash"></span> 删除客户 </button> </td> </tr> </tbody> </table> </div> </div> </div> </div> <div th:replace="foot::foot-body"></div> </div> </div> <script th:src="@{/vendor/jquery/jquery.min.js}"></script> <script th:src="@{/vendor/popper.js/popper.min.js}"></script> <script th:src="@{/vendor/bootstrap/js/bootstrap.min.js}"></script> <script th:src="@{/vendor/chart.js/chart.min.js}"></script> <script th:src="@{/js/carbon.js}"></script> <script th:src="@{/js/demo.js}"></script> </body> </html> ``` #### 公共类 ``` <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>head</title> <link th:href="@{/vendor/simple-line-icons/css/simple-line-icons.css}" rel="stylesheet"/> <link th:href="@{/vendor/font-awesome/css/fontawesome-all.min.css}" rel="stylesheet"/> <link th:href="@{/css/styles.css}" rel="stylesheet"/> </head> <body> <div th:fragment="header-body"> <nav class="navbar page-header"> <a href="#" class="btn btn-link sidebar-mobile-toggle d-md-none mr-auto"> <i class="fa fa-bars"></i> </a> <a class="navbar-brand" href="/index"> <img th:src="@{/img/logo.png}" alt="logo"> </a> <a href="#" class="btn btn-link sidebar-toggle d-md-down-none"> <i class="fa fa-bars"></i> </a> <ul class="navbar-nav ml-auto"> <li class="nav-item d-md-down-none"> <a href="#"> <i class="fa fa-location-arrow"></i> <span class="small ml-1 d-md-down-none"> <span style="padding-right:20px;" href="#" th:text="${weather}"></span> </span> </a> </li> <li class="nav-item d-md-down-none"> <a href="#"> <i class="fa fa-bell"></i> <span class="badge badge-pill badge-danger">5</span> </a> </li> <li class="nav-item d-md-down-none"> <a href="#"> <i class="fa fa-envelope-open"></i> <span class="badge badge-pill badge-danger">4</span> </a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <img th:src="@{/img/avatar-1.png}" class="avatar avatar-sm" alt="logo"> <span class="small ml-1 d-md-down-none">xx,欢迎登录</span> </a> <div class="dropdown-menu dropdown-menu-right"> <div class="dropdown-header">账户</div> <a href="#" class="dropdown-item"> <i class="fa fa-bell"></i> 通知 </a> <a href="#" class="dropdown-item"> <i class="fa fa-envelope"></i> 邮件 </a> <a href="#" class="dropdown-item"> <i class="fa fa-bell"></i> 工资详情 </a> <div class="dropdown-header">设置</div> <a href="#" class="dropdown-item"> <i class="fa fa-user"></i> 个人资料 </a> <a href="/settings" class="dropdown-item"> <i class="fa fa-wrench"></i> 设置 </a> <a href="#" class="dropdown-item"> <i class="fa fa-lock"></i> 注销 </a> </div> </li> </ul> </nav> </div> <script th:src="@{/vendor/jquery/jquery.min.js}"></script> <script th:src="@{/vendor/popper.js/popper.min.js}"></script> <script th:src="@{/vendor/bootstrap/js/bootstrap.min.js}"></script> <script th:src="@{/vendor/chart.js/chart.min.js}"></script> <script th:src="@{/js/particles.min.js}"></script> <script th:inline="javascript"> $(function () { var weather = [[${addressAndWeather}]]; }) </script> </body> </html> ``` 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 像素格子 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览