SpringMVC フレームワーク (すべての基本)

目次

MVCとは

Spring MVCの概要

SpringMVCの一般的な開発手法

SpringMVC実行処理

SpringMVC コアコンポーネントの概要

Spring MVC プログラムを迅速に構築する

SpringMVCパラメータバインディング

SpringMVCのジャンプメソッド

SpringMVC は json リクエストとレスポンスを処理します

SpringMVCの静的リソース処理

SpringMVCはセッションとCookieを操作します

SpringMVC インターセプター

SpringMVCファイルのアップロード

SpringMVCグローバル例外統合処理

SSM フレームワークの統合

1. pom 依存関係を導入する

2. 設定ファイルを設定する

3. プロジェクトのディレクトリ構造


MVCとは

MVC デザイン パターンは一般に MVC フレームワークを指し、M (モデル) はデータ モデル層とビジネス モデル層を指し、V (ビュー) はビュー層を指し、C (コントローラー) はコントロール層を指します。MVCを使用する目的は、MとVの実装コードを分離し、同じプログラムでも異なる表現ができるようにすることです。

MVCとはアーキテクチャパターンの一種で、いわゆるアーキテクチャとはプログラムの構造をどのように設計するかということです。MVC はプログラム構造を 3 つの層に分割し、各層は上位層が呼び出すためのインターフェイスを提供します。これにより、3 つの層間の接続が維持されるだけでなく、相対的な独立性も維持されます。

ビジネス ロジック、データ、インターフェイスを分離するこの形式のコード構成により、モジュール間の結合が軽減され、将来のメンテナンスと拡張に役立ちます。

Spring MVCの概要

springmvc は、spring Framwork から派生した mvc フレームワークです。主に、元の mvc アーキテクチャのコントローラー (Controller) の問題を解決します。一般的なコントローラーには、サーブレット、struts2 などが含まれます。コントローラーの中心的な機能は、次に従って、対応するコントローラーを呼び出すことです。ユーザーの要求に応じて業務機能を実行し、業務処理の結果に応じてプログラムの実行プロセスを制御します。

サーブレット実装コントローラーの問題:

1. クライアントリクエストパラメータを受信する際、コードの冗長性が存在します。

2.文字列型のデータのみを受信できます。他のデータ型は手動で変換する必要があります

3. オブジェクト型のパラメータを受信できない

4. ビジネスオブジェクトの呼び出しに結合があります (新規)

5. プロセスジャンプにカップリングがある(パスカップリング、ビューカップリング)

SpringMVCの一般的な開発手法

1. 従来の開発手法

スコープ(リクエスト、セッション)を介したデータ転送を実現

ビュー テクノロジによるビュー レンダリング (jsp thymleaf freeMarker)

2. フロントエンドとバックエンドの分離開発方式

複数の新しいアクセス方法 (get、post、put、delete)

快適なスタイルのアクセス

SpringMVC実行処理

Spring MVC フレームワークは高度に構成可能であり、JSP、FreeMarke、POI などの複数のビュー テクノロジが含まれています。Spring MVC フレームワークは、使用されるビュー テクノロジを考慮せず、開発者に JSP のみの使用を強制しません。

Spring MVC の実行フローを次の図に示します。

 

SpringMVCの実行フローは以下のとおりです。

  1. ユーザーはリクエスト パスをクリックして HTTP リクエスト リクエストを開始します。このリクエストは DispatcherServlet (フロント コントローラ) に送信されます。

  2. DispatcherServlet は 1 つ以上の HandlerMapping (プロセッサ マッパー) を要求し、実行チェーン (HandlerExecutionChain) を返します。

  3. DispatcherServlet は、実行チェーンによって返されたハンドラー情報を HandlerAdapter (プロセッサーアダプター) に送信します。

  4. HandlerAdapter は、ハンドラー情報に従って、対応するハンドラー (コントローラーと呼ばれることが多い) を見つけて実行します。

  5. Handler が実行されると、ModelAndView オブジェクトが HandlerAdapter (Model データ モデルと View ビュー情報を含む Spring MVC の基礎となるオブジェクト) に返されます。

  6. HandlerAdapter は ModelAndView オブジェクトを受信した後、それを DispatcherServlet に返します。

  7. DispatcherServlet が ModelAndView オブジェクトを受信すると、ViewResolver (ビュー リゾルバー) にビューを解決するよう要求します。

  8. ViewResolver は、View 情報に従って、対応するビュー結果を照合し、それを DispatcherServlet に返します。

  9. 特定の View ビューを受信した後、DispatcherServlet はビューをレンダリングし、Model 内のモデル データを View ビューのリクエスト フィールドに入力し、最終的な View (ビュー) を生成します。

  10. ビューはブラウザ (クライアント) に結果を表示する責任があります。

SpringMVC コアコンポーネントの概要

Spring MVC に関係するコンポーネントは、DispatcherServlet (フロント コントローラー)、HandlerMapping (プロセッサ マッパー)、HandlerAdapter (プロセッサ アダプター)、Handler (プロセッサ)、ViewResolver (ビュー リゾルバー)、および View (ビュー) です。各コンポーネントの機能を以下に説明します。

1)Dispatcherサーブレット

DispatcherServlet はフロント コントローラーであり、図 1 からわかるように、Spring MVC のすべてのリクエストは DispatcherServlet を通じて均一に分散される必要があります。DispatcherServlet はフォワーダーまたは中央プロセッサに相当し、プロセス全体の実行を制御し、各コンポーネントを均一にスケジュールして、コンポーネント間の結合を減らし、コンポーネント間の拡張を容易にします。

2) ハンドラーのマッピング

HandlerMapping はハンドラー マッパーであり、その機能は、リクエストの URL パスに従って、アノテーションまたは XML 構成を通じて一致するハンドラー (Handler) 情報を検索することです。

3)ハンドラーアダプター

HandlerAdapter はプロセッサ アダプタであり、その機能は、マッパーによって検出されたプロセッサ (Handler) 情報に従って、特定の規則に従って該当するプロセッサ (Handler) を実行することです。

4)ハンドラー

ハンドラーはプロセッサーであり、Java サーブレットが果たす役割と一致しています。その機能は、関連するリクエスト処理ロジックを実行し、対応するデータと表示情報を返し、それを ModelAndView オブジェクトにカプセル化することです。

5)ビューリゾルバー

ビュー リゾルバーはビュー リゾルバーであり、その役割は解析操作を実行し、ModelAndView オブジェクト内のビュー情報を通じて論理ビュー名を実際のビューに解決することです (JSP パスを通じて実際の JSP ページを返すなど)。

6)見る

View はビューであり、それ自体がインターフェイスであり、実装クラスはさまざまな View タイプ (JSP、FreeMarker、Excel など) をサポートします。

上記のコンポーネントのうち、プロセッサ (ハンドラー、コントローラーと呼ばれることも多い) とビュー (ビュー) は開発者が開発する必要があります。平たく言えば、リクエストを処理するための特定のコード ロジックを開発し、最終的にユーザーにインターフェイスを表示する必要があります。

Spring MVC プログラムを迅速に構築する

構築手順は次のとおりです。

  1. Web アプリケーションを作成し、JAR パッケージをインポートする

    spring-webmvc

  2. Spring MVC 構成: web.xml でサーブレットを構成し、Spring MVC 構成ファイルを作成します

 <servlet> 
  <servlet-name>springmvc</servlet-name> 
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
  <init-param> 
   <param-name>contextConfigLocation</param-名前> 
   <param-value>クラスパス:springmvc-config.xml</param-value> 
  </init-param> 
  <load-on-startup>1</load-on-startup> 
 </servlet> 
 <servlet-mapping > 
  <サーブレット名>springmvc</サーブレット名
  > <url-pattern>/</url-pattern> 
 </servlet-mapping>

springmvc 設定ファイル

<?xml version="1.0"coding="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:mvc="http://www.springframework.org/schema/mvc" 
    xsi:schemaLocation=" http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans.xsd 
        http://www.springframework.org/schema/context 
        http://www .springframework.org/schema/context/spring-context.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc。xsd"> xsd"> 
    <!--アノテーションは mvc を実装します-->
    <!-- 注釈をサポートする IOC を実装するためにパッケージを自動的にスキャンします --> 
    <context:component-scan base-package="cn.kgc.spring" /> 
    <!-- MVC アノテーション駆動の登録プロセッサ マッパー登録処理をサポートします。アダプタパラメータの変換ページジャンプ応答処理 --> 
    <mvc:annotation-driven /> 
    <!-- ビューリゾルバ --> 
    <bean 
        class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
        id ="internalResourceViewResolver" > 
        <!-- プレフィックス--> 
        <property name="prefix" value="/view/" /> 
        <!-- サフィックス--> 
        <property name="suffix" value=".jsp" /> 
    </豆> 
</豆>

コントローラー (リクエストを処理するコントローラー) を作成します。

@Controller 
@RequestMapping("/Hello") 
public class HelloWorld { 
    @RequestMapping("/Say.do") 
    public String SayHi(Model モデル) { 
        return "index"; 
    } 
}

ビューの作成 (JSP をビューとして使用)

<%@ page contentType="text/html;charset=UTF-8" language="java" %> 
<html> 
<head> 
    <title>タイトル</title> 
</head> 
<body> 
    hello springmvc 
</body > 
</html>

デプロイして実行する

@RequestMappingの詳しい説明

1. メソッドは複数のパスに一致します

@RequestMapping(value={"hello1.do","hello2.do"}) 
    public String test01(){ 
System.out.println
        ("hello"); 
//
        ジャンプ パスはデフォルトで転送を使用し、次のようになります。ビューを通じて解析され、
        「インデックス」が返されます; 
    }

2.メソッドで受信したリクエストメソッドを指定する

@RequestMapping(value = "hello1.do",method = RequestMethod.GET) 
    public String test01(){ 
System.out.println
        ("hello GET"); 
//
        ジャンプ パスはデフォルトで転送を使用し、ビューパーサーは
        「インデックス」を返します; 
    }

 

@RequestMapping(value = "hello1.do",method = RequestMethod.POST) public String test02(){ System.out.println("hello POST"); //ジャンプ パスのデフォルトは転送であり、ビューパーサーは「インデックス」を返します; }

 

3. 1 つのメソッドで複数の種類のリクエストを指定する

@RequestMapping(value = "hello1.do", method = {RequestMethod.GET, RequestMethod.POST}) 
    public String test01(){ 
System.out.println
        ("hello GET OR POST"); 
//
        パスをジャンプする Byデフォルトでは、転送はビューリゾルバーを経由して行われます
        。 return "index"; 
    }

 

 

 

SpringMVCパラメータバインディング

ビューからコントローラーにパラメーターを渡す

1. 基本的なデータ型バインディング

仮パラメータの名前は、渡されたパラメータの名前と一致しています。すべてのパラメータを渡す必要があります。渡さないと、500 エラーが報告されます。パラメータを渡さないエラーを解決するには、パラメータのデフォルト値を設定します。パラメータの基本タイプ

/** 
     * 基本パラメータタイプのデフォルト値を設定します @RequestParam(defaultValue = "xx") 
     * パラメータが URL 経由で渡される場合、渡されたパラメータが最終パラメータになります
     * @param age 
     * @param core 
     */ 
    @ RequestMapping(" /login2") 
    public void login2(@RequestParam(defaultValue = "20") int age , @RequestParam(defaultValue = "24.7") double core){ 
        System.out.println(age); 
        System.out.println (スコア) ; 
    }

パラメータのエイリアスを設定します

public void login3(@RequestParam(defaultValue = "20" ,name = "Age") int age , double core) 
 { 
        System.out.println(age); 
        System.out.println(スコア); 
 }

2. パッケージングデータタイプの転送

ラッパー型を使用すると、基本型で値が渡されずに 500 エラーが発生するという問題は解決できますが、パラメーター名と仮パラメーターの一貫性を保つ必要があります。

@RequestMapping("/login4") 
    public void login3(Integer age , Double Score){ 
        System.out.println(age); 
        System.out.println(スコア); 
    }

3.文字列型データのバインド

パッケージングクラスを参照してください

4. 配列型

public void login3(String[] ids){ 
        for (int i = 0; i < ids.length; i++) { 
            System.out.println(ids[i]); 
        } 
  }

5. JavaBeanの型

パラメータ名のフィールドは、Javabean のプロパティと一致している必要があります。

public void login3(ユーザー user){ 
        System.out.println(user); 
    URL 
:http://localhost:8080/user/login6?age=12&username=lisi&height=1.7

データをビューレイヤーに返す

@RequestMapping(path = "/res1") 
    public ModelAndView test01(){ 

        ModelAndView modelAndView = new ModelAndView(); 
        modelAndView.setViewName("こんにちは"); 
        modelAndView.addObject("msg", "ModelAndView"); 
        モデルとビューを返します。
    @RequestMapping(path = "/res2") 
    public String test02(Model モデル){ 
        model.addAttribute("msg", "model") 
    ; 
        「こんにちは」を返します。
    @RequestMapping(path = "/res3") public String 
    test03 
    (ModelMap マップ){ 
        map.addAttribute("msg", "モデルマップ"); 
        「こんにちは」を返します。
    }


SpringMVCのジャンプメソッド

デフォルトでは、Spring MVC はサーバーの内部転送の形式でページ情報を表示し、リダイレクト ページもサポートします。

リダイレクト(ブラウザへの 302 ステータス コード)

@Controller 
public class HelloController3 { 

    @RequestMapping("/r1") 
    public void test01(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { 
        response.sendRedirect("redirect.jsp"); 
    @RequestMapping("/r2") 
    public String test02(){ 
    return 
        "redirect:redirect.jsp"; 
    } 
    @RequestMapping("/f1") 
    public void test03(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { 
        request.getRequestDispatcher("redirect.jsp").forward(request, 応答); 
    @RequestMapping("/f2") は
    " 
        forward:redirect.jsp" を返します。


 
    public String test04(){

    @RequestMapping("/f3") 
    public 
    String test05(){ 
        return "リダイレクト"; 
    }

SpringMVC は json リクエストとレスポンスを処理します

json形式のデータに応答する

public class JsonController { 

    @GetMapping("/login/{username}/{password}") 
    public void login(@PathVariable String ユーザー名, @PathVariable String パスワード, HttpServletResponse res) throws IOException { 
        System.out.println(username+":: "+パスワード); 
        //响应json形式の文字列
        res.setContentType("application/json;charset=utf-8"); 
        JsonResult 結果 = JsonResult.builder().code(200).count(100L).data(null).msg("ok").build(); 
        res.getWriter().write(result.toJSONString()); 
    @GetMapping("/login2/{username}/{password}") public 
    Object 
    login2(@PathVariable String ユーザー名, @PathVariable String パスワード, HttpServletResponse res) throws IOException {
 
    @ResponseBody 
        System.out.println(ユーザー名+"::"+パスワード); 
        return JsonResult.builder().code(200).count(100L).data(null).msg("ok").build(); 
    @RequestMapping("/login3") 
    @ResponseBody 
    public Object login3(User user) { 
        System.out.println(user); 
    } 
        リターンユーザー。
    }


   

リクエストのデータ型はJSONです

/**
     * 接收json格式的参数
     * @param user
     * @return
     */
    @RequestMapping("/login4")
    @ResponseBody
    public Object login4(@RequestBody User user) {
        System.out.println(user);
        return user;
    }
}


前台ajax请求
<script type="text/javascript">
    $(function () {
        $("#jsbutton").click(function () {
            $.ajax({
                    url:'/login3',
                    type:'post',
                    data:{
                        username:"lisi",
                        age:20,
                        height:170,
                        birth:new Date()
                    },
                    dataType:'json',
                    success:function (result) {
                        console.log(result);
                    },
                    error:function () {
                         console.log("请求失败!")
                     }
            })
        })


        $("#jsbutton2").click(function () {
            var user = {
                username:"lisi",
                age:20,
                height:170,
                birth:'1999-9-9'
            }
            $.ajax({
                url:'/login4',
                type:'post',
                data:JSON.stringify(user),
                contentType:'application/json;charset=utf-8',
                dataType:'json',
                success:function (result) {
                    console.log(result);
                },
                error:function () {
                    console.log("请求失败!")
                }
            })
        })

    })

</script>

安らぎのスタイル

ソフトウェアのアーキテクチャ スタイル、設計スタイルは、標準ではなく、一連の設計原則と制約を提供するだけです。主にクライアントとサーバーの対話ソフトウェアに使用されます。このスタイルに基づいて設計されたソフトウェアは、より簡潔で、より階層化され、キャッシュなどのメカニズムを実装しやすくなります。

URL定義

リソース: インターネット上のすべてのものをリソースとして抽象化できます。 リソース操作: POST、DELETE、PUT、GET を使用し、さまざまなメソッドを使用してリソースを操作します。それぞれ追加、削除、変更、クエリに対応

従来の方法でリソースを操作する

http://127.0.0.1/item/queryUser.action?id=1 クエリ、GET 
http://127.0.0.1/item/saveUser.action 追加、POST 
http://127.0.0.1/item/updateUser.action update 、POST 
http://127.0.0.1/item/deleteUser.action?id=1 削除、GET または POST

RestFulリクエストメソッドGET、POST、PUT、PATCH、DELETEなどでサーバー側のリソースを操作できます。の:

  • GET はリソースのクエリに使用されます。

  • POST はリソースの作成に使用されます。

  • PUTはサーバー側のリソースのすべての情報を更新するために使用されます。

  • DELETE は、サーバー側のリソースを削除するために使用されます。

public class RestController {

    @GetMapping("/rest")
    public void test01(){
        System.out.println("test01: ");
    }  

    @PostMapping("/rest")
    public void test02(){
        System.out.println("test02: ");
    }

    @DeleteMapping("/rest")
    public void test03(){
        System.out.println("test03:");
    }

    @PutMapping("/rest")
    public void test04(){
        System.out.println("test04: ");
    }

    @PatchMapping("/rest")
    public void test05(){
        System.out.println("test05: ");
    }

}

フォーム送信PUTリクエスト設定方法

<form action="rest/r" method="post"> 
        <input type="hidden" name="_method" value="PUT"> 
        <p><input type="text" placeholder="请输入id" name="id"></p> 
        <p><input type="text" placeholder="请输入姓名" name="username"></p> <p> 
        <input type="date" placeholder="请输入生日" name="birth"></p> 
        <p><input type="submit"></p> 
 </form>

web.xmlを設定する

<filter>
       <filter-name>Hidden</filter-name>
       <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>

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

REST スタイルのパラメータ受け渡しの問題

 @GetMapping("/login/{username}/{password}")
    public void login(@PathVariable String username, @PathVariable String password, HttpServletResponse res) throws IOException {
        System.out.println(username+"::"+password);
        //响应json格式的字符串
        res.setContentType("application/json;charset=utf-8");
        JsonResult result = JsonResult.builder().code(200).count(100L).data(null).msg("ok").build();
        res.getWriter().write(result.toJSONString());
    }

データ入稿時の中国語文字化けへの対応

<!--解决中文乱码-->
    <filter>
        <filter-name>encoding</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>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

SpringMVCの静的リソース処理

1. 静的リソースのパスを設定する

<mvc:resources マッピング="/static/**" location="/static/"/>

2. Tomcat を使用してサーブレット プロセッサを構成する

<mvc:default-servlet-handler/>

SpringMVCはセッションとCookieを操作します

@Controller
@SessionAttributes({"model1","model2"})
public class SessionController {

    @RequestMapping("/s1")
    public void test01(HttpSession session){
        session.setAttribute("msg", "session attribute");
    }

    @RequestMapping("/s2")
    public void test02(HttpSession session){
        System.out.println(session.getAttribute("msg"));
    }

    /**
     * 将model放入session作用域
     * @param model
     */
    @RequestMapping("/s3")
    public void test03(Model model){
        model.addAttribute("model1", "model1 attribute");
    }

    /**
     * 获取通过注解设置的session域中的值
     * @param session
     */
    @RequestMapping("/s5")
    public void test05(HttpSession session){
        System.out.println("msg: "+session.getAttribute("msg"));
        System.out.println("model1 :"+session.getAttribute("model1"));
        System.out.println("model2 :"+session.getAttribute("model2"));
    }

    /**
     * 通过注解获取session域中的值
     * @param
     */
    @RequestMapping("/s6")
    public void test05(@SessionAttribute(name = "msg") String session){
        System.out.println(session);
    }
   
操作cookie

public class CookieController {

    @RequestMapping("/c1")
    public void test01(HttpServletResponse response){
        Cookie ck = new Cookie("cookie","cookieValue");
        ck.setPath("/");
        ck.setMaxAge(60*60*24*7);
        response.addCookie(ck);
    }

    /**
     * 获取cookie中值的方式1
     * @param request
     */
    @RequestMapping("/c2")
    public void test02(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            System.out.println(cookies[i].getName()+":"+cookies[i].getValue());
        }
    }

    /**
     * 获取cookie中值的方式2  注解方式
     * @param cookie
     */
    @RequestMapping("/c3")
    public void test03(@CookieValue("cookie") String cookie){
        System.out.println(cookie);
    }
}

SpringMVC インターセプター

SpringMVC の Interceptor インターセプターも非常に重要で便利で、その主な機能はユーザーのリクエストをインターセプトし、それに応じて処理することです。たとえば、権限を確認したり、ユーザーがログインしているかどうかを判断したりするために使用します。SpringMVC インターセプターを定義するには 2 つの方法があります

  • インターフェースの実装: org.springframework.web.servlet.HandlerInterceptor

  • 継承アダプター: org.springframework.web.servethandler.HandlerInterceptorAdapter

1. HandlerInterceptor インターフェースを実装する

public class MyIntercepter01 implements HandlerInterceptor {

    /**
     * 目标方法执行前执行  返回false拦截   否则放行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyIntercepter01 ->目标方法前->执行preHandle01 ");
        return true;
    }

    /**
     *
     * 目标方法执行后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyIntercepter01 ->目标方法执行后->执行postHandle01 ");
    }

    /**
     * 视图响应完成后执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyIntercepter01 ->视图渲染完成后->执行afterCompletion01 ");
    }
2.继承HandlerInterceptorAdapter(不建议使用)

public class MyInterceptor2  extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return false;
    }
}
使用拦截器拦截非法请求

/**
 *用户操作模拟实现
 * 用户的登录(无需登录)
 * 用户的添加(登录)
 * 用户修改(登录)
 * 用户删除(登录)
 *
 * @author mosin
 * date 2021/8/22
 * @version 1.0
 */
@Controller
@RequestMapping("/user")
@SessionAttributes("action")
public class UserInfoController {
    /**
     * 用户登录
     */
    @RequestMapping("/login")
    public ModelAndView login(HttpSession session){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("success");

        User user = User.builder().password("123456").username("lisi").build();
        session.setAttribute("user", user);
        modelAndView.addObject("user", user);
        return modelAndView;
    }

    /**
     * 用户添加
     */
    @RequestMapping("/add")
    public String add(Model model){
        model.addAttribute("action", "用户添加成功");
        System.out.println("用户的添加方法");

        return "success";
    }

    /**
     * 用户修改
     */
    @RequestMapping("/update")
    public String update(Model model){
        System.out.println("用户的更新方法");
        model.addAttribute("action", "用户更新成功");
        return "success";
    }

    /**
     * 用户修改
     */
    @RequestMapping("/delete")
    public String delete(Model model){
        System.out.println("用户的删除方法");
        model.addAttribute("action", "用户删除成功");
        return "success";
    }

}

SpringMVCファイルのアップロード

添加坐标依赖

<dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
 </dependency>
配置解析器

<!--    文件上传配置文件解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--       允许上传的最大文件  单位字节-->
        <property name="maxUploadSize" >
            <value>104857600</value>
        </property>
<!--        内存中的最大缓存超出写出临时文件到硬盘-->
        <property name="maxInMemorySize" >
            <value>4096</value>
        </property>
        <property name="defaultEncoding">
            <value>utf-8</value>
        </property>
    </bean>
后台代码

@Controller
@RequestMapping("/upload")
public class UPloadController {

    @RequestMapping("/file")
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request){

        //获取项目的真实路径
        String realPath = request.getSession().getServletContext().getRealPath("/");
        System.out.println(realPath);
        //创建文件上传的目录
        File dir = new File(realPath, "/upload");
        System.out.println(dir);
        //判定文件夹是否存在 不存在创建
        if(!dir.exists()){
            dir.mkdir();
        }

        if(!file.isEmpty()){
            //获取文件的名字
            String fileName = file.getOriginalFilename();
            //截取文件的后缀 生成新的文件名 避免文件名字重复
            String suffix= fileName.substring(fileName.lastIndexOf("."));
            //获取当前系统时间
            String fileLastName = System.currentTimeMillis()+suffix;
            System.out.println(fileLastName);
            //将文件写入目标文件夹
            try {
                file.transferTo(new File(dir,fileLastName));
                request.setAttribute("msg", "文件上传成功");
            } catch (IOException e) {
                e.printStackTrace();
                request.setAttribute("msg", "文件上传失败");
            }
        }else{
            request.setAttribute("msg", "未选择文件");
        }

        return "success";
    }

    @RequestMapping("/files")
    public String uploads(@RequestParam("files") List<MultipartFile> files, HttpServletRequest request){

        //遍历集合
       files.forEach(multipartFile -> {
           FileUploadUtil.upload(multipartFile, request);
       });
        return "success";
    }
}

SpringMVCグローバル例外統合処理

1. 処理方法1 @ExceptionHandler(Exception.class)を使用して、このクラスで指定された例外を処理する例外メソッドをクラス内に定義します。

@RestController
@RequestMapping("/exception")
public class ExceptionController01 {

    @ExceptionHandler(Exception.class)
    public Object handlerException(Exception e){
        return JsonResult.builder().msg("出现"+"异常").code(1).data(e.getMessage()).build();
    }

    @RequestMapping("/e1")
    public Object ex1(){
        int a  = 1/0;
        return null;
    }

    @RequestMapping("/e2")
    public Object ex2() throws FileNotFoundException {
        new FileInputStream("ab");
        return null;
    }
}
2.处理的方式2 全局处理模式 定义ExceptionAdvice类

@RestControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler(value ={Exception.class})
    public Object handlerException(Exception e){
        return JsonResult.builder().msg("出现"+"异常").code(1).data(e.getMessage()).build();
    }
}

SSM フレームワークの統合

1. pom 依存関係を導入する

1. mybatis 依存関係を導入する

<!--    mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.7</version>
    </dependency>
<!--    分页pagehelper-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.2.1</version>
    </dependency>
<!--    mybatis-spring-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.5</version>
    </dependency>
2.引入spring依赖

<!--    spring-context-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.9</version>
    </dependency>
<!--    spring-aspects-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.3.9</version>
    </dependency>
<!--      spring-jdbc-->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>5.3.9</version>
      </dependency>
3.springmvc依赖

<!--    spring-webmvc-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.9</version>
    </dependency>
<!--    jackson-core-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.11.3</version>
    </dependency>
<!--    jackson-databind-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.11.3</version>
    </dependency>
<!--    jackson-annotations-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.11.3</version>
    </dependency>

<!--    文件上传-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>
4.log4j依赖

<dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
 <dependency>
       <groupId>org.apache.logging.log4j</groupId>
       <artifactId>log4j-api</artifactId>
       <version>2.13.3</version>
 </dependency>
  <dependency>
       <groupId>org.apache.logging.log4j</groupId>
       <artifactId>log4j-core</artifactId>
       <version>2.13.1</version>
  </dependency>
5.数据库驱动和连接池

<!--    mysql-connector-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.44</version>
    </dependency>
   
<!--    druid连接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.10</version>
    </dependency>
6.servlet+jsp依赖

<!--servlet-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
    </dependency>
<!--    jsp-->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
    </dependency>
7.jstl依赖

<!--jstl-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
8.其它依赖

<!--    lombok-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.16</version>
    </dependency>
<!--    junit-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

2. 設定ファイルを設定する

1.db.プロパティ

jdbc.driver=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql:///mybatis?useSSL=true&serverTimezone=GMT%2B8 
jdbc.username=root 
jdbc.password=root 

#プール内で確立された接続の数初期化中に。
jdbc.initialSize=2 
#アクティブな接続プールの最大数
jdbc.maxActive=300 
#最大待機時間
jdbc.maxWait=60000

2.log4j.プロパティ

log4j.rootLogger=DEBUG,Console 

#Console 
log4j.appender.Console=org.apache.log4j.ConsoleAppender 
log4j.appender.console.Target=System.out 
log4j.appender.Console.layout=org.apache.log4j.PatternLayout 
log4j。 appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n 

log4j.logger.org.apache=エラー
log4j.logger.org.mybatis=エラー
log4j.logger.org。 springframework=ERROR 

#これが必要
log4j.logger.log4jdbc.debug=ERROR 
log4j.logger.com.gk.mapper=ERROR 
log4j.logger.jdbc.audit=ERROR 
log4j.logger.jdbc.resultset=ERROR 
#この打印SQL语句非常重要
log4j.logger.jdbc.sqlonly=デバッグ
log4j.logger.jdbc.sqltiming=エラー
log4j.logger.jdbc.connection=致命的

3.スプリングコア設定ファイル

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 读取db.properties -->
    <context:property-placeholder location="classpath:db.properties" />

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 数据库驱动 -->
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="initialSize" value="${jdbc.initialSize}" />
        <property name="maxActive" value="${jdbc.maxActive}" />
        <property name="maxWait" value="${jdbc.maxWait}" />
    </bean>

    <!-- 事务管理器,依赖于数据源 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 开启事务注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"  />

    <!-- 配置MyBatis工厂 SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 指定Mybatis核心配置文件位置 -->
        <property name="configLocation" value="classpath:config/mybatis-config.xml" />
        <!-- 扫描模块配置文件:mapper需要的xml文件(如果mapper.xml和接口在一个包下,可以不配置) -->
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>

    <!-- 配置mapper扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.kgc.ssm.dao" />
    </bean>

    <!-- 扫描包-->
    <context:component-scan base-package="cn.kgc.ssm" />
    <!--    开启spring注解支持-->
    <context:annotation-config/>
</beans>

4. spring-mvc設定ファイル

<?xml version="1.0"coding="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:mvc="http://www.springframework.org/schema/mvc" 
       xmlns:tx=" http://www.springframework.org/schema/tx" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans。 xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd 
        http://www.springframework.組織/スキーマ/MVC 
        http://www.springframework.org/スキーマ/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 加载注解驱动 -->
    <mvc:annotation-driven />
    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!--释放静态资源-->
    <mvc:default-servlet-handler/>
    <!--    文件上传配置文件解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--       允许上传的最大文件-->
        <property name="maxUploadSize" >
            <value>104857600</value>
        </property>
        <!--        内存中的最大缓存超出写出临时文件到硬盘-->
        <property name="maxInMemorySize" >
            <value>4096</value>
        </property>
        <property name="defaultEncoding">
            <value>utf-8</value>
        </property>
    </bean>
</beans>

5.mybatis設定ファイル

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- mybatis运行时设置 -->
    <settings>
        <!-- 启用log4j日志 -->
        <setting name="logImpl" value="LOG4J"></setting>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!-- 别名定义 -->
    <typeAliases>
        <package name="cn.kgc.ssm.entity" />
    </typeAliases>

    <!-- mybatis插件 -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 配置mysql方言 -->
            <property name="helperDialect" value="mysql" />
            <!-- 设置为true时,如果pageSize=0就会查询出全部的结果 -->
            <property name="pageSizeZero" value="true" />
            <!-- 3.3.0版本可用,分页参数合理化,默认false禁用 -->
            <!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->
            <!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 -->
            <property name="reasonable" value="true" />
        </plugin>
    </plugins>
</configuration>

6.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>ssm</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/spring-*.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ssm</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

<!--    过滤器解决中文乱码-->
    <filter>
        <filter-name>encoding</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>encoding</filter-name>
        <url-pattern>/</url-pattern>
    </filter-mapping>
</web-app>

3. プロジェクトのディレクトリ構造

 

おすすめ

転載: blog.csdn.net/m0_67979925/article/details/129747743