SpringMVC---請求與響應的處理(實戰一)

前期準備

使用環境

  • JDK:1.8
  • Tomcat:9.0.3
  • Spring:5.2.8
  • Maven:3.6.3
  • 編譯器:IntelliJ IDEA 2019

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
 version="4.0">
     
     <servlet> 
        <servlet-name>mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param> 
            <param-name>contextConfigLocation</param-name>
        <param-value>classpath:ApplicationContext.xml</param-value>
        </init-param> 
    </servlet>
    <servlet-mapping> 
        <servlet-name>mvc</servlet-name>
        <url-pattern>*.do</url-pattern>
     </servlet-mapping>
</web-app>

ApplicationContext.xml配置(Spring核心配置文件)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 開啓spring註解驅動-->
     <context:component-scan base-package="com.cjh"/>
    <!-- 開啓mvc註解驅動-->
     <mvc:annotation-driven></mvc:annotation-driven>
</beans>

請求

1. 請求的發送與接收

如下寫的瀏覽器和服務器的方式是相對應的,好比第一種請求就對應着第一種接收html

  • 1)瀏覽器發送請求的方式:java

    • 第一種:請求資源名(找的是具體的處理類),請求的方法上寫上@RequestMapping註解web

      • 這種形式要求請求的處理類下只有一個方法
    • 第二種:請求資源名?method=具體執行方法(找的是具體的處理類中的方法)
    • 第三種:請求資源名(找的是具體的執行方法)-----經常使用
  • 2)服務器接收請求的方式:spring

    • 不管是對應瀏覽器的哪一種發送方式,都須要使用@RequestMapping註解
    • 第一種:在類上寫上@RequestMapping(請求資源名)註解
    • 第二種:在類上寫上@RequestMapping(請求資源名)註解,在方法上也要寫上@RequestMapping(params = {method=方法名})註解(method也能夠換成其餘名字)
    • 第三種:直接在方法上寫上@RequestMapping(請求資源名)
  • 3)@RequestMapping註解中的其餘方法後端

    • path/value:用來存儲請求資源名
    • params:要求瀏覽器必須發送的參數,參數的形式是{"key=value",""},
    • method:要求瀏覽器請求的方法(GET/POST)
    • headers:要求瀏覽器必須攜帶的請求頭({"Accept-Language",""})
    • 注意:後面三個一旦寫明,就是要求瀏覽器必須攜帶的東西,若是沒有攜帶,那麼服務器是不處理的
  • 4)具體示例代碼:瀏覽器

    • 第一種方式:spring-mvc

      • JSP
      <%@ page contentType="text/html; charset=UTF-8" language="java" %>
      <html>
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>cai jin hong</title>
       <style>
       </style>
      </head>
      <body>
       <a href="userController.do">測試第一種請求方式</a>
      </html>
      • java
      @Controller
      @RequestMapping("userController.do")
      public class UserController {
      
          @RequestMapping
          public void testOne(){
              System.out.println("test方法執行了");
          }
      }
      • 測試結果:瀏覽器顯示404,服務器控制檯打印出test方法執行了
    • 第二種方式:服務器

      • JSP
      <%@ page contentType="text/html; charset=UTF-8" language="java" %>
      <html>
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>cai jin hong</title>
       <style>
       </style></head>
      <body>
       <a href="userController.do?method=testOne">測試userController下的testOne方法</a><br>
       <a href="userController.do?method=testTwo">測試userController下的testTwo方法</a>
      </body>
      </html>
      • java
      @Controller
      @RequestMapping("userController.do")
      public class UserController {
          @RequestMapping(params = {"method=testOne"})
          public void testOne(){
              System.out.println("testOne方法執行了");
          }
          @RequestMapping(params = {"method=testTwo"})
          public void testTwo(){
              System.out.println("testTwo方法執行了");
          }
      }
      • 測試結果:瀏覽器顯示404,服務器控制檯打印出輸出的語句
    • 第三種方式:mvc

      • JSP:
      <%@ page contentType="text/html; charset=UTF-8" language="java" %>
      <html>
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>cai jin hong</title>
       <style>
       </style></head>
      <body>
       <a href="testOne.do">testOne方法</a><br>
       <a href="testTwo.do">testTwo方法</a>
      </body>
      </html>
      • Java:
      @Controller
      public class UserController {
          @RequestMapping("testOne.do")
          public void testOne(){
               System.out.println("testOne方法執行了");
          }
          @RequestMapping("testTwo.do")
          public void testTwo(){
              System.out.println("testTwo方法執行了");
          }
      }
      • 測試結果:瀏覽器顯示404,服務器端控制檯正常打印
    • @RequestMapping的其餘用法app

      • JSP:
      <%@ page contentType="text/html; charset=UTF-8" language="java" %>
      <html>
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>cai jin hong</title>
       <style>
       </style></head>
      <body>
       <a href="testOne.do?user=123&password=123">測試參數攜帶的請求</a><br>
       <a href="testOne.do">測試不攜帶參數的請求</a>
      <%--    a標籤的請求方式是GET請求--%>
       <a href="testGetMethod.do">測試服務器要求的請求方式</a>
       <a href="testPostMethod.do">測試服務器要求的請求方式</a>
       <a href="testHeader.do">測試服務器要求的攜帶的請求頭</a>
      </body>
      </html>
      • Java:
      @Controller
      public class UserController {
          //請求必須攜帶user和password這兩個參數key,並且必須有value值
          @RequestMapping(value = "testOne.do", params = {"user=123", "password=123"})
          public void testOne(){
              System.out.println("這是測試是否攜帶參數的請求方法");
           }
          @RequestMapping(value = "testGetMethod.do", method = {RequestMethod.GET})
          public void testGetMethod(){
              System.out.println("這是測試Get的請求方法");
          }
          @RequestMapping(value = "testPostMethod.do", method = {RequestMethod.POST})
          public void testPostMethod(){
              System.out.println("這是測試Post的請求方法");
          }
          @RequestMapping(value = "testHeader.do", headers = {"Accept-Language"})
          public void testHeader(){
              System.out.println("這是測試是否攜帶請求頭");
          }
      }
      • 測試結果:
      • 測試參數攜帶的請求

        • 瀏覽器顯示404,客戶端正常打印
      • 測試不攜帶參數的請求

        • 瀏覽器顯示400報錯,不知足客戶端要求的格式
      • 測試服務器要求的GET請求方式

        • 瀏覽器顯示404,客戶端正常打印
      • 測試服務器要求的POST請求方式

        • 瀏覽器顯示405,請求的資源要求用Post方式,不支持GET請求
      • 測試服務器要求攜帶的請求頭

        • 瀏覽器顯示404,客戶端正常打印

2. 請求參數的處理

  • 1)方法中傳入變量

    • 要求傳入的變量與瀏覽器發送請求傳遞的參數key一致,即使key只有一個
    • 利用@RequestParam("key"),那麼只需註解裏面的key和瀏覽器傳遞的參數key一致便可
    • 代碼以下:

      • JSP:
      <%@ page contentType="text/html; charset=UTF-8" language="java" %>
      <html>
      <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>cai jin hong</title>
       <style>
       </style></head>
      <body>
       <form action="testOne.do" method="post">
       <input type="text" name="account" value=""><br>
       <input type="text" name="password" value=""><br>
       <input type="text" name="balance" value=""><br>
       <input type="submit" value="submit">
       </form>
       <form action="testTwo.do" method="post">
       <input type="text" name="account" value=""><br>
       <input type="text" name="password" value=""><br>
       <input type="text" name="balance" value=""><br>
       <input type="submit" value="submit">
       </form>
        </body>
      </html>
      • Java:
      @Controller
      public class UserController {
          //方法中傳入變量:參數名與請求傳遞參數的名字一致
          @RequestMapping("testOne.do")
          public void testOne(String account, String password, float balance){
              System.out.println("testOne:"+ "account = " + account + " password = " + password + " balance" + balance);
       }
          //方法中傳入變量:參數名與請求傳遞參數的名字不一致
          @RequestMapping("testTwo.do")
          public void testTwo(@RequestParam("account") String xxx,    @RequestParam("password") String yyy, @RequestParam("balance") float zzz){
              System.out.println("testTwo:" + "account = " + xxx + " password = " + yyy + " balance" + zzz);
          }
      
      }
      • input標籤裏的內如本身輸入,點擊submit,在後端的控制檯上就能看到打印出來的結果
  • 2)方法中傳入實體對象

    • 直接用對象接收,要求對象中的屬性名與瀏覽器傳遞過來的參數key一致

      • 代碼以下:
      • JSP:(代碼太多了,這裏只給出form表單)
      <form action="testThree.do" method="post">
       <input type="text" name="account" value=""><br>
       <input type="text" name="password" value=""><br>
       <input type="text" name="balance" value=""><br>
       <input type="submit" value="submit">
      </form>
      • Java:
      public class User {
          private String account;
       private String password;
       private Float balance;
       public User(String account, String password, Float balance) {
              System.out.println("User:帶參的構造方法");
       this.account = account;
       this.password = password;
       this.balance = balance;
       }
          public User(){
              System.out.println("User:無參的構造方法");
       }
          public void init(){
              System.out.println("初始化了");
       }
          public void destroy(){
              System.out.println("被銷燬了");
       }
          @Override
       public String toString() {
              return "User{" +
                      "account='" + account + ''' +
                      ", password='" + password + ''' +
                      ", balance=" + balance +
                      '}';
       }
          public String getAccount() {
              return account;
       }
          public void setAccount(String account) {
              System.out.println("set方法調用了");
       this.account = account;
       }
          public String getPassword() {
              return password;
       }
          public void setPassword(String password) {
              this.password = password;
       }
          public Float getBalance() {
              return balance;
       }
          public void setBalance(Float balance) {
              this.balance = balance;
       }
      }
      @Controller
      public class UserController {
      
          @RequestMapping("testThree.do")
          //方法中傳入實體對象:要求對象中的屬性名與瀏覽器傳遞過來的參數key一致
           public void testThree(User user){
                  System.out.println("testThree:"+ user);
           }
      }
    • 對象套對象的狀況:Spring會根據傳遞過來的參數,將對象裏對象屬性自動包裝(若是參數名和屬性名都對應的話)

      • 代碼以下:
      • JSP:
      <form action="testThree.do" method="post">
       account:<input type="text" name="account" value=""><br>
       password:<input type="text" name="password" value=""><br>
       balance:<input type="text" name="balance" value=""><br>
       address:<input type="text" name="address" value=""><br>
       <input type="submit" value="submit">
      </form>
      • Java:(User裏面套着Address)
      public class Address {
          private String address;
           public Address(){}
              public Address(String address){
                  this.address = address;
           }
              @Override
           public String toString() {
                  return "Address{" +
                          "address='" + address + ''' +
                          '}';
           }
              public void setAddress(String address) {
                  this.address = address;
           }
              public String getAddress() {
                  return address;
           }
      }
      public class User {
          private String account;
           private String password;
           private Float balance;
           private Address address;
           public User(String account, String password, Float balance) {
                  System.out.println("User:帶參的構造方法");
           this.account = account;
           this.password = password;
           this.balance = balance;
           }
              public User(){
                  System.out.println("User:無參的構造方法");
           }
              public void init(){
                  System.out.println("初始化了");
           }
              public void destroy(){
                  System.out.println("被銷燬了");
           }
              @Override
           public String toString() {
                  return "User{" +
                          "account='" + account + ''' +
                          ", password='" + password + ''' +
                          ", balance=" + balance +
                          ", address=" + address +
                          '}';
           }
              public String getAccount() {
                  return account;
           }
              public void setAccount(String account) {
                  System.out.println("set方法調用了");
           this.account = account;
           }
              public String getPassword() {
                  return password;
           }
              public void setPassword(String password) {
                  this.password = password;
           }
              public Float getBalance() {
                  return balance;
           }
              public void setBalance(Float balance) {
                  this.balance = balance;
           }
              public void setAddress(Address address) {
                  this.address = address;
           }
              public Address getAddress() {
                  return address;
           }
          }
      @Controller
          public class UserController {
              //方法中傳入實體對象:對象裏面依賴了其餘對象
           @RequestMapping("testFour.do")
              public void testFour(User user){
                  System.out.println("testFour:" + user);
           }
      }
      • 注意:輸入中文會出現亂碼的問題,由於這裏沒有處理中文字符集
    • 對象套list集合<對象>:

      • 代碼以下:
      • JSP:(addressList[i]表明addressList集合中的一個對象,經過.獲取對象的屬性,addressList是user對象中的屬性名)
      <form action="testFive.do" method="post">
       account:<input type="text" name="account" value=""><br>
       password:<input type="text" name="password" value=""><br>
       balance:<input type="text" name="balance" value=""><br>
       address1:<input type="text" name="addressList[0].address" value=""><br>
       address2:<input type="text" name="addressList[1].address" value=""><br>
       <input type="submit" value="submit">
      </form>
      • Java:(Address類代碼不變)
      public class User {
          private String account;
           private String password;
           private Float balance;
           private List<Address> addressList;
           public User(String account, String password, Float balance) {
                  System.out.println("User:帶參的構造方法");
           this.account = account;
           this.password = password;
           this.balance = balance;
           }
              public User(){
                  System.out.println("User:無參的構造方法");
           }
              public void init(){
                  System.out.println("初始化了");
           }
              public void destroy(){
                  System.out.println("被銷燬了");
           }
              @Override
           public String toString() {
                  return "User{" +
                          "account='" + account + ''' +
                          ", password='" + password + ''' +
                          ", balance=" + balance +
                          ", addressList=" + addressList +
                          '}';
           }
              public String getAccount() {
                  return account;
           }
              public void setAccount(String account) {
                  System.out.println("set方法調用了");
           this.account = account;
           }
              public String getPassword() {
                  return password;
           }
              public void setPassword(String password) {
                  this.password = password;
           }
              public Float getBalance() {
                  return balance;
           }
              public void setBalance(Float balance) {
                  this.balance = balance;
           }
              public void setAddressList(List<Address> addressList) {
                  this.addressList = addressList;
           }
              public List<Address> getAddressList() {
                  return addressList;
           }
      }
      @Controller
      public class UserController {
      
          //方法中傳入實體對象:對象裏面有list集合
       @RequestMapping("testFive.do")
          public void testFive(User user){
              System.out.println("testFive:" + user);
       }
      
      }
  • 3)方法中傳入Map集合

    • 直接在方法參數前加上@RequestParam註解(這裏就不寫了)
  • 4)方法中傳入Request、Response對象

    • 代碼以下:
    @RequestMapping("testFive.do")
    public void testFive(HttpServletRequest request, HttpServletResponse response){
        System.out.println(request.getParameter("account"));
     System.out.println(response);
    }

本篇文章到這就結束了,由於篇幅比較長,把響應的處理放在下一篇文章中!!!

相關文章
相關標籤/搜索