SpringMVC筆記1

来源:https://www.cnblogs.com/train99999/archive/2019/07/21/11223309.html
-Advertisement-
Play Games

SpringMVC是一個一種基於Java的實現MVC設計模型的請求驅動類型的輕量級web框架 SpringMVC的入門案例 1. 2.導入相關jar包 3,在web.xml中配置前端控制器 4.編寫控制器類 5.開啟掃描註解 6.編寫兩個JSP 首頁 成功頁面 入門案例的流程總結 1.伺服器啟動,加 ...


SpringMVC是一個一種基於Java的實現MVC設計模型的請求驅動類型的輕量級web框架

SpringMVC的入門案例

img

2.導入相關jar包

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>cn.itcast</groupId>
  <artifactId>springmvc_day01_01_start</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>springmvc_day01_01_start Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

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

  <dependencies>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>${spring.version}</version>
      </dependency>

      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>${spring.version}</version>
      </dependency>

      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${spring.version}</version>
      </dependency>

      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
          <version>2.5</version>
          <scope>provided</scope>
      </dependency>

      <dependency>
          <groupId>javax.servlet.jsp</groupId>
          <artifactId>jsp-api</artifactId>
          <version>2.0</version>
          <scope>provided</scope>
      </dependency>
  </dependencies>

  <build>
    <finalName>springmvc_day01_01_start</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

3,在web.xml中配置前端控制器

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springmvc.xml</param-value>
  </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

4.編寫控制器類

package cn.itcast.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

//控制器類
@Controller
public class HelloController {
    //用來接收請求
    @RequestMapping(path = "/hello")
    public String sayHello(){
        System.out.println("Hello SpringMVC");
        return "success";
    }
}

5.開啟掃描註解

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc ">
    <!--開啟註解掃描-->
    <context:component-scan base-package="cn.itcast"></context:component-scan>

    <!--視圖解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--開啟SpringMVC框架的支持-->
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>

6.編寫兩個JSP

首頁

<%--
  Created by IntelliJ IDEA.
  User: Yuan
  Date: 2019/7/21
  Time: 14:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入門程式</h3>
    <a href="hello">入門程式</a>
</body>
</html>

成功頁面

<%--
  Created by IntelliJ IDEA.
  User: Yuan
  Date: 2019/7/21
  Time: 15:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入門成功</h3>
</body>
</html>

img

入門案例的流程總結

1.伺服器啟動,載入配置

img

2.DispatcherServlet對象創建

image

3.springmvc.xml會開啟註解掃描

4.找到HelloController,把他變成對象,載入進入IOC容器當中,

5.InternalResourceViewResolver視圖解析器也會變成對象,誰調用該對象,就會幫他跳轉頁面img

RequestMapping註解的作用:用於建立請求URL和處理請求方法之間的對應關係,註解位置用在方法上或者類上

請求參數綁定入門

1.請求地址攜帶參數username

<body>
    <%--請求參數綁定--%>
    <a href="param/testParam?username=hehe">請求參數綁定</a>
</body>

2.方法帶有參數username

package cn.itcast.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/param")
public class ParamController {
    //請求參數綁定入門
    @RequestMapping("/testParam")
    public String testParam(String username){
        System.out.println("執行了....");
        System.out.println(username);
        return "success";
    }
}

3.自動給方法的參數賦值

//輸出結果
//執行了....   
//hehe

配置解決中文亂碼的過濾器

  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
  </init-param>
  </filter>

  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

引用類型的封裝

public class User implements Serializable {
    private String uname;
    private String age;
}

img

集合類型封裝

img

編寫自定義類型轉換器

//兩個泛型,S表示字元串,T表示想要轉換的類型
public interface Converter<S, T> 
    

1.實現介面Converter

package cn.itcast.utils;

import org.springframework.core.convert.converter.Converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//字元串轉日期
public class StringToDateConverter implements Converter<String, Date> {
    @Override
    //實現介面方法
    public Date convert(String source) {
        if(source == null){
            throw new RuntimeException("沒有日期");
        }

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return df.parse(source);
        } catch (Exception e) {
            throw new RuntimeException("日期轉換異常");
        }
    }
}

2.配置自定義類型轉換器

<!--配置自定義類型轉換器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="cn.itcast.utils.StringToDateConverter"></bean>
            </set>
        </property>
    </bean>

3.開啟SpringMVC框架的支持

<!--開啟SpringMVC框架的支持-->
    <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

img

常用註解

RequestParam註解

作用:把請求中指定名稱的參數給控制器中的形參賦值

屬性:

value,請求參數中的名稱,

required:請求參數中是否必須提供此參數,預設值:trueimg

RequestBody註解

作用:用於獲取請求體內容,直接使用得到是key=value&key=value...結構的數據get請求不適用(get請求沒有請求體,把參數都封裝到地址欄上)

屬性:

required:是否必須有請求體,預設值true,當取值為true時,get請求會報錯,如果取值為false,get請求得到是null

PathVariable註解

作用:用於綁定url中的占位符,例如:請求url中/delete{id},這個{id}就是url占位符。url支持占位符是spring3.0之後加入的。是springmvc支持rest風格URL的一個重要標誌。

屬性:

value:用於指定url中占位符名稱

required:是否必須提供占位符

 @RequestMapping("/testPathVariable/{sid}")
    public String testPathVariable(@PathVariable(name="sid") String id){
        System.out.println("執行了");
        System.out.println(id);
        return "success";
    }
<a href="anno/testPathVariable/10">testPathvariable</a>

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 舉個慄子 問題描述 畫一個小人,有頭、身體、兩手、兩腳就可以了。 簡單實現 人類 測試 測試結果 存在問題 畫人的時候,頭身手腳是必不可少的,不管什麼人物,開發時是不能少的。但上面測試代碼中時各部分堆積起來,很容易漏寫,比如導致健全的人物卻少了一條“腿”。而且如果需要在別的地方用這些畫小人的程式怎麼 ...
  • 第一篇博客(無關技術) 第一篇博客不知從何入手,有寫博客的想法是因為想要記錄自己學習Java的歷程及總結,2019年7月21,寫這篇博客的時間是大三的暑假。 由於大學是學的軟體工程,所以日後想要從事IT行業,大一學的一門語言是C基礎,大三學的一門語言是Java,後續感覺在學校也學了很多關於電腦相關 ...
  • Java面試題經常會問的問題 面試官Q1:請問StringBuffer和StringBuilder有什麼區別? 這是一個老生常談的話題,筆者前幾年每次面試都會被問到,作為基礎面試題,被問到的概率百分之八九十。下麵我們從面試需要答到的幾個知識點來總結一下兩者的區別有哪些? 繼承關係? 如何實現的擴容?... ...
  • 看到一篇非常全面的SQL優化文章,在開發的工作中往往不考慮性能上的缺失(在一開始的時候數據量不大也看不出速度上的區別)。但寫的越多越應該規範一下寫法。 原文鏈接:http://www.jfox.info/SQL-you-hua.html By Lee - Last updated: 星期五, 五月 ...
  • 最近在網上偶然看到此題: 有兩個序列a,b,大小都為n,序列元素的值任意整形數,無序; 要求:通過交換a,b中的元素,使[序列a元素的和]與[序列b元素的和]之間的差最小 經過一番思索,我試著用窮舉法來解一下這道題,大概思路如下: 1、分別求a,b序列元素之和sum_a、sum_b2、算出min = ...
  • 微服務高可用方案 一、微服務的高可用 在註冊中心、配置中心高可用方案之前,瞭解一下註冊中心的工作原理,下麵分為兩個部分來解釋,一是註冊中心和各個微服務的註冊表的獲取與同步,二是註冊中心如何去維護註冊表。 1.1、註冊表的獲取與同步 Eureka Server和Eureka Client之間的關係,通 ...
  • 異常   Java虛擬機異常使用Throwable或其子類的實例來表示,拋異常本質上是程式控制權的一種即時的、非局部的轉換,即從拋出的地方轉換至處理異常的地方。   導致異常的原因 執行了athrow位元組碼指令。 虛擬機同步檢測到程式發生了非正常的執行情況,這 ...
  • \t製表符>>> print('python')python>>> print("python")python>>> print('\tpython') python\n換行符>>> print("Languages:\nPython\nC\nJavaScript")Languages:Python... ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...