整合營銷服務商

          電腦端+手機端+微信端=數據同步管理

          免費咨詢熱線:

          Spring MVC 框架學習-返回頁面+加載靜態資源

          章目錄

          • Spring 框架學習(六)---- 返回頁面+加載靜態資源
          • 2、返回 application/json
          • 1、請求轉發forword 和 重定向的區別2、請求轉發的訪問資源問題演示

          Spring 框架學習(六)---- 返回頁面+加載靜態資源

          一、返回頁面

          不加 @ResponseBody ,默認是返回一個網頁

          @RequestMapping("/getPage")
              public String getPage(){
           
                  return "index.html";
              }

          二、返回非頁面的數據

          ??返回非頁面的數據,必須在方法或者類上加 @ResponseBody,同時 我們返回的類型 springmvc會自動解析成對應的格式,不需要我們進行手動指定

          1、返回 text/html

          @RequestMapping("/getText")
              @ResponseBody
              public String getHTML(String name){
           
                  return "<h1>你好,歡迎用戶:"+name+"<h1>";
              }

          訪問接口,自動解析成 html格式

          通過 Fiddler 進行抓包,查看返回響應的格式為 text/html。

          2、返回 application/json

          使用map存儲數據,返回map

          @RequestMapping("/getmap")
              @ResponseBody
              public Object getJson(){
           
                  HashMap<Object,Object> map = new HashMap<>();
                  map.put("msg","登陸成功");
                  map.put("status",200);
          
                  return map;
              }

          自動解析稱為 json 格式的數據

          三、加載靜態資源

          咱們就直接定死了寫的格式

          在webapp目錄下創建static文件夾保存 css、js、html 資源

          同時在spring-mvc.xml 文件中加入 過濾靜態資源、加載靜態資源的配置

          <!--    過濾靜態資源,  /.jsp  /.html 不會經過-->
              <mvc:default-servlet-handler/>
          
          
           <!--加載靜態資源location表示訪問的路徑return"/static/login.html",mapping表示映射的靜態資源位置-->
              <mvc:resources location="/static/css/" mapping="/static/css/**"/>
              <mvc:resources location="/static/js/" mapping="/static/js/**"/>
              <mvc:resources location="/static/" mapping="/static/**"/>

          我們來試一下訪問靜態資源

          在wbeapp目錄下創建static文件,將css/js/html等文件添加進去

          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>springmvc</servlet-name>
              <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
              <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:spring-mvc.xml</param-value>
              </init-param>
              <load-on-startup>1</load-on-startup>
              <multipart-config>
                <max-file-size>20848820</max-file-size>
                <max-request-size>418018841</max-request-size>
                <file-size-threshold>1048576</file-size-threshold>
              </multipart-config>
            </servlet>
          
            <servlet-mapping>
              <servlet-name>springmvc</servlet-name>
              <url-pattern>/</url-pattern>
            </servlet-mapping>
          
          </web-app>

          spring-mvc.xml 配置文件

          <?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"
                 xsi:schemaLocation="http://www.springframework.org/schema/beans
                  http://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/mvc
                  http://www.springframework.org/schema/mvc/spring-mvc.xsd">
              
          
              <!--    開啟注解掃描,將使用注解的類托管到spring 容器中-->
              <context:component-scan base-package="com.*"/>
          
              <!--    過濾靜態資源,  /.jsp  /.html 不會經過-->
              <mvc:default-servlet-handler/>
          
          <!--    加載靜態資源文件-->
              <mvc:resources location="/static/css/" mapping="/static/css/**"/>
              <mvc:resources location="/static/js/" mapping="/static/js/**"/>
              <mvc:resources location="/static/" mapping="/static/**"/>
          
              <!--    開啟mvc注解驅動-->
              <mvc:annotation-driven>
                  <mvc:message-converters register-defaults="true">
                      <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                          <property name="supportedMediaTypes">
                              <list>
                                  <value>text/html;charset=UTF-8</value>
                                  <value>application/json;charset=UTF-8</value>
                              </list>
                          </property>
                      </bean>
                  </mvc:message-converters>
          
          
          
              </mvc:annotation-driven>
          
          </beans>

          在controller層進行訪問靜態html文件(經過css、js渲染)

          @RequestMapping("/login")
              public String getLog(){
           
                  return "redirect:/static/login.html";
              }

          四、轉發和重定向

          1、請求轉發forword 和 重定向的區別

          (1) 重定向 將請求重新定位到資源的位置,請求轉發是服務器端進行轉發的

          (2)請求重定向url地址發生改變,請求轉發地址不發生變化

          (3)請求重定向于直接訪問新地址的效果一樣,不存在原來的外部資源不能訪問,請求轉發服務器端的轉發可能會造成外部資源不能訪問(js、css)

          如果外部資源與轉發訪問的頁面不在同一級目錄下,會造成外部資源不可訪問。

          2、請求轉發的訪問資源問題演示

          通過轉發的請求資源都直接通過 8080:/a/login 這個接口的同一級目錄下直接訪問,當然找不到資源

          請求重定向相當于 輸入的url變了,直接訪問到 /static/login/html,同時附帶的資源在在這一目錄下能夠訪問到。

          3、頁面跳轉

          1、請求轉發: 服務器放客戶進行請求轉發并將結果響應給客戶端,URL是不會變的

          2、請求重定向:服務器端請求重新定義到要訪問的地址。URL會放生改變。

          總結:

          • 請求轉發的URL地址不變,因為是服務器端進行轉發和響應的,所以重定向URL地址會發生改變,因為服務器端直接將請求重定向到具體的地址上
          • 使用請求轉發那么有可能會發生資源丟失,訪問不到外部資源。請求重定向是直接重定向到URL地址,所以請求重定向和直接訪問目標地址的效果是一樣的,所以不會存在外部資源丟失的情況。

          五、組合注解

          @RestController

          相當于 @Controller + @ResponseBody

          只能加到類上

          • 回JSON對象,我們就需要用到@ResponseBody注解,如果接收JSON數據封裝成JavaBean的話,我們就需要用到@RequestBody注解。隨后在配置文件上創建對應的bean即可。


          • 一、通過json數據傳輸
          $("#submit_bt").click(function(){
           var data = {
           title: $("#title").val(),
           dm_label: $("#dm_label").val(),
           url: $("#url").val(),
           img_url: $("#img_url").html(),
           state: 0
           }
           $.ajax({
           type:'post',
           url:'${ctx}/admin/dynamic/message/add',
           dataType : 'json',
           data: JSON.stringify(data),
           contentType: "application/json; charset=utf-8",
           success:function(data){
           if (data.mark=="0") {
           window.location.href="${ctx}/admin/dynamic/message/list?state=0&page_size=10&father_id=24";
           } else {
           alert(data.tip);
           }
           },
           error: function(textStatus) {
           alert(textStatus);
           }
           });
          });
          @RequestMapping(value = "/admin/dynamic/message/add", method = {RequestMethod.GET, RequestMethod.POST})
          @ResponseBody
          @Authority(AuthorityType.NoAuthority)
          public RetInfo insert(@Valid @RequestBody TsJzDynamicMessage tsJzDynamicMessage, BindingResult result, HttpServletRequest request) {
           RetInfo retInfo = new RetInfo();
           if (result.hasErrors()) {
           List<FieldError> err = result.getFieldErrors();
           FieldError fe = err.get(0);
           retInfo.setMark("1");
           retInfo.setTip(fe.getDefaultMessage());
           } else {
           TsJzAdmin tsJzAdmin = AdminSession.getAdmin(request);
           retInfo = dynamicMessageService.insertDynamicMessage(tsJzDynamicMessage, tsJzAdmin);
           }
           return retInfo;
          }
          

          二、通過url數據傳輸

          本文中,讓我們嘗試構建自定義 HTML Hepler以在 .NET Core MVC 應用程序中提供分頁。首先對不熟悉的人簡單介紹一下,什么是HTML Helper(助手):

          • HTML 助手使開發人員可以輕松快速地創建 HTML 頁面。
          • 在大多數情況下,HTML 助手只是一個返回字符串的方法。
          • MVC 帶有內置的 HTML 幫助器,例如 @Html.TextBox()、@Html.CheckBox()、@Html.Label 等。
          • HTML 助手在 razor 視圖中呈現 html 控件。例如,@Html.TextBox() 渲染 <input type="textbox"> 控件,@Html.CheckBox() 渲染 <input type="checkbox"> 控件等。

          需求

          在Web應用程序中,如果要顯示大量記錄,則需要提供分頁。在本文中,我們通過創建自定義 HTML Helper 在 .NET Core MVC 應用程序中實現分頁。為了簡單起見,我們只能使用數字來表示數據。

          假設我們需要在多頁中顯示 55 條記錄,每頁有 10 個項目,如上所示。

          開始

          打開 Visual Studio 2019 > 創建 .NET Core MVC 應用程序,如下所示。

          項目命名為 HTMLHelpersApp。

          選擇 .NET 框架版本。

          創建所需的模型和幫助文件。

          1. 創建一個新模型“Number”。
          2. 右鍵單擊 Model 文件夾并添加“Number”類。

          在 Number.cs 中添加代碼。該模型捕獲用戶輸入。它只有一個屬性:“InputNumber”。

          using System;
          using System.ComponentModel.DataAnnotations;
          
          
          namespace HTMLHelpersApp.Models
          {
              public class Number
              {
                  //validation for required, only numbers, allowed range-1 to 500
                  [Required(ErrorMessage = "Value is Required!. Please enter value between 1 and 500.")]
                  [RegularExpression(@"^\d+$", ErrorMessage = "Only numbers are allowed. Please enter value between 1 and 500.")]
                  [Range(1, 500, ErrorMessage = "Please enter value between 1 and 500.")]
                  public int InputNumber = 1;
              }
          }

          現在讓我們添加一個公共類 PageInfo.cs。創建新文件夾 Common 并添加 PageInfo.cs 類。

          1. 右鍵單擊項目文件夾并添加一個新文件夾。

          在 PageInfo.cs 中添加代碼:

          1. Page Start 表示當前頁面上的第一項。
          2. Page End 表示當前頁面的最后一項。
          3. 每頁項目數表示要在頁面上顯示的項目數。
          4. Last Page 表示頁數/最后頁碼。
          5. Total Items 表示項目的總數。

          根據總項目數和每頁項目數,計算頁面的總頁數、第一個項目和最后一個項目。

          using System;
          using System.Collections.Generic;
          using System.Linq;
          using System.Threading.Tasks;
          
          
          namespace HTMLHelpersApp.Common
          {
              public class PageInfo
              {
                  public int TotalItems { get; set; }
                  public int ItemsPerPage { get; set; }
                  public int CurrentPage { get; set; }
          
          
                  public PageInfo()
                  {
                      CurrentPage = 1;
                  }
                  //starting item number in the page
                  public int PageStart
                  {
                      get { return ((CurrentPage - 1) * ItemsPerPage + 1); }
                  }
                  //last item number in the page
                  public int PageEnd
                  {
                      get
                      {
                          int currentTotal = (CurrentPage - 1) * ItemsPerPage + ItemsPerPage;
                          return (currentTotal < TotalItems ? currentTotal : TotalItems);
                      }
                  }
                  public int LastPage
                  {
                      get { return (int)Math.Ceiling((decimal)TotalItems / ItemsPerPage); }
                  }
                  
              }
          }

          現在我們來到最重要的部分:創建自定義 HTML 助手。

          1. 創建自定義 HTML 幫助程序 PageLinks,它呈現頁碼、上一個和下一個鏈接。
          2. 在“Common”文件夾中添加一個新類“PagingHtmlHelpers.cs”。
          3. 在“PagingHtmlHelpers.cs”中添加代碼。
          4. 擴展 HtmlHelper 并添加新功能以添加頁面鏈接。
          public static IHtmlContent PageLinks(this IHtmlHelper htmlHelper, PageInfo pageInfo, Func<int, string> PageUrl)

          5.取2個參數

          1. pageInfo:添加頁碼
          2. 委托給函數:將整數和字符串作為參數添加控制器操作方法中所需的參數

          使用標簽構建器創建錨標簽。

          TagBuilder tag = new TagBuilder("a");
          Add attributes
          tag.MergeAttribute("href", hrefValue);
          tag.InnerHtml.Append(" "+ innerHtml + " ");

          樣式也可以用作屬性。

          using Microsoft.AspNetCore.Html;
          using Microsoft.AspNetCore.Mvc.Rendering;
          using System;
          using System.Text;
          
          
          namespace HTMLHelpersApp.Common
          {
              public static class PagingHtmlHelpers
              {
                  public static IHtmlContent PageLinks(this IHtmlHelper htmlHelper, PageInfo pageInfo, Func<int, string> PageUrl)
                  {
                      StringBuilder pagingTags = new StringBuilder();
                      //Prev Page
                      if (pageInfo.CurrentPage > 1)
                      {
                          pagingTags.Append(GetTagString("Prev", PageUrl(pageInfo.CurrentPage - 1)));
          
          
                      }
                      //Page Numbers
                      for (int i = 1; i <= pageInfo.LastPage; i++)
                      {
                          pagingTags.Append(GetTagString(i.ToString(), PageUrl(i)));
                      }
                      //Next Page
                      if (pageInfo.CurrentPage < pageInfo.LastPage)
                      {
                          pagingTags.Append(GetTagString("Next", PageUrl(pageInfo.CurrentPage + 1)));
                      }
                      //paging tags
                      return new HtmlString(pagingTags.ToString());
                  }
          
          
                  private static string GetTagString(string innerHtml, string hrefValue)
                  {
                      TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag
                      tag.MergeAttribute("class","anchorstyle");
                      tag.MergeAttribute("href", hrefValue);
                      tag.InnerHtml.Append(" "+ innerHtml + "  ");
                      using (var sw = new System.IO.StringWriter())
                      {
                          tag.WriteTo(sw, System.Text.Encodings.Web.HtmlEncoder.Default);
                          return sw.ToString();            
                      }
                  }
              }
          }

          在“Models”文件夾中添加一個新類“ShowPaging.cs”。

          • DisplayResult將在每一頁上顯示數字列表。
          • PageInfo將捕獲所有頁面詳細信息,例如每頁上的頁數、總項目、開始項目和最后一個項目等。
          using HTMLHelpersApp.Common;
          using System;
          using System.Collections.Generic;
          using System.ComponentModel.DataAnnotations;
          
          
          namespace HTMLHelpersApp.Models
          {
              public class ShowPaging
              {
                  
                  //validation for required, only numbers, allowed range-1 to 500
                  [Required(ErrorMessage = "Value is Required!. Please enter value between 1 and 500.")]
                  [RegularExpression(@"^\d+$", ErrorMessage = "Only positive numbers are allowed. Please enter value between 1 and 500.")]
                  [Range(1, 500, ErrorMessage = "Please enter value between 1 and 500.")]
                  public int InputNumber { get; set; }
          
          
                  public List<string> DisplayResult { get; set; }
          
          
                  public PageInfo PageInfo;
              }
          }
          
          

          添加新控制器

          添加一個新控制器:“HTMLHelperController”

          右鍵單擊控制器文件夾并在上下文菜單中選擇控制器。

          選擇“MVCController-Empty”。

          在“HTMLHelperController”中添加代碼。

          using HTMLHelpersApp.Common;
          using HTMLHelpersApp.Models;
          using Microsoft.AspNetCore.Mvc;
          using System.Collections.Generic;
          
          
          namespace HTMLHelpersApp.Controllers
          {
              public class HTMLHelperController : Controller
              {
                  private const int PAGE_SIZE = 10;
                  public IActionResult Number()
                  {
                      return View();
                  }
          
          
                  public IActionResult ShowPaging(ShowPaging model, int page = 1, int inputNumber = 1)
                  {
                      if (ModelState.IsValid)
                      {
                          var displayResult = new List<string>();
                          string message;
          
          
                          //set model.pageinfo
                          model.PageInfo = new PageInfo();
                          model.PageInfo.CurrentPage = page;
                          model.PageInfo.ItemsPerPage = PAGE_SIZE;
                          model.PageInfo.TotalItems = inputNumber;
          
          
                          //Set model.displayresult - numbers list
                          for (int count = model.PageInfo.PageStart; count <= model.PageInfo.PageEnd; count++)
                          {
                              message = count.ToString();
                              displayResult.Add(message.Trim());
                          }
                          model.DisplayResult = displayResult;
                      }
                      //return view model
                      return View(model);
                  }
              }
          }

          在 Views 文件夾中創建一個新文件夾“HTMLHelper”,并創建一個新視圖“Number.cshtml”。

          在“Number.cshtml”中添加代碼。

          @model HTMLHelpersApp.Models.Number
          
          
          <h4>Number</h4>
          <hr />
          <div class="row">
              <div class="col-md-4">
                  <form asp-action="ShowPaging" method="get">
                      <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                      <div class="form-group">
                          <input asp-for="InputNumber" class="form-control"/>
                      </div>
                      <div class="form-group">
                          <input type="submit" value="Submit" class="btn btn-primary" />
                      </div>
                  </form>
              </div>
          </div>

          同樣,創建一個新視圖“ShowPaging.cshtml”。

          @model HTMLHelpersApp.Models.ShowPaging
          @using HTMLHelpersApp.Common
          
          
          <link rel="stylesheet" href ="~/css/anchorstyles.css"/>
          <form>
              <h4>Show Paging</h4>
              <hr />
              <div asp-validation-summary="All" class="text-danger"></div>
              <dl class="row">
                  <dt class="col-sm-2">
                      <b>Number: </b> @Html.DisplayFor(model => model.InputNumber)
                  </dt>
                  <dd>
                      <a asp-action="Number">Change Number</a>
                  </dd>
              </dl>
          
          
              <div>
                  @if (Model != null && Model.DisplayResult != null)
                  {
                      <ul>
                          @foreach (var item in Model.DisplayResult)
                          {
                              <li>@Html.Raw(item)</li>
                          }
                      </ul>
                      <div>
                          @Html.PageLinks(@Model.PageInfo, x => Url.Action("ShowPaging",
                              new { page = x.ToString(), inputNumber = @Model.InputNumber }))
                      </div>
                  }
              </div>        
           </form>

          解決方案資源管理器如下所示:

          在“startup.cs”中配置默認控制器和操作。

          編譯并運行應用程序,輸入數字 35。

          點擊提交。

          你會在底部看到分頁,每頁顯示10個數字,一共4頁,且每頁都一個鏈接。


          主站蜘蛛池模板: 精品无码一区二区三区在线 | 亚洲爆乳精品无码一区二区| 久久亚洲综合色一区二区三区| 无码国产精成人午夜视频一区二区 | 在线电影一区二区三区| 一区二区日韩国产精品| 夜精品a一区二区三区| 久久久久成人精品一区二区| 国产成人精品视频一区| 天堂资源中文最新版在线一区| 视频一区二区在线播放| 成人中文字幕一区二区三区| 国产在线一区二区三区| 国产成人精品无人区一区| 在线不卡一区二区三区日韩| 精品欧洲AV无码一区二区男男| 中文字幕在线无码一区二区三区| 婷婷国产成人精品一区二| 免费高清av一区二区三区| 国产精品一区二区不卡| 夜夜嗨AV一区二区三区| 怡红院一区二区在线观看| 97人妻无码一区二区精品免费 | 国产熟女一区二区三区五月婷| 精品一区二区三区在线播放视频| 日本高清不卡一区| 精品一区二区久久久久久久网站| 国产成人精品久久一区二区三区av| 丰满爆乳无码一区二区三区| 中文精品一区二区三区四区| 日韩一区二区超清视频| 亚洲美女视频一区二区三区| 成人国内精品久久久久一区| 狠狠色婷婷久久一区二区三区 | 国产精品一区二区av| 久久青青草原一区二区| 高清一区二区三区日本久| 一区二区免费国产在线观看| 亚洲综合av一区二区三区不卡| 亚洲综合av永久无码精品一区二区| 国产一区二区草草影院|