SpringMVC之數據傳遞三Ajax與Controller交互


前面學習了攔截器,通過攔截器我們可以攔截請求,做進一步處理之后再往下進行,這里我們使用Ajax的時候會有一個問題就是會把js、css這些靜態資源文件也進行了攔截,這樣在jsp中就無法引入的靜態資源文件。所以在spring-mvc.xml配置攔截器時需要進行優化。

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**/*"/>
        <mvc:exclude-mapping path="/**/fonts/*"/>
        <mvc:exclude-mapping path="/**/*.css"/>
        <mvc:exclude-mapping path="/**/*.js"/>
        <mvc:exclude-mapping path="/**/*.png"/>
        <mvc:exclude-mapping path="/**/*.gif"/>
        <mvc:exclude-mapping path="/**/*.jpg"/>
        <mvc:exclude-mapping path="/**/*.jpeg"/>
        <mvc:exclude-mapping path="/**/*login*"/>
        <mvc:exclude-mapping path="/**/*Login*"/>
        <bean class="com.cyw.web.Intercepter.LoginIntercepter"></bean>
    </mvc:interceptor>
</mvc:interceptors>
View Code

一、靜態資源文件的引入

這里我們用jquery.js文件為例子。如下圖把js文件放在了webapp下的js文件夾下.除了配置攔截器外還需要在spring-mvc.xml中配置對靜態資源文件的訪問.

    <!-- 對靜態資源文件的訪問 方案一 (二選一) -->
 
    <mvc:default-servlet-handler />
    
    <!-- 對靜態資源文件的訪問 方案二 (二選一) -->
   
    <mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/> 
    <mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/> 
    <mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/>
    
View Code

二、在jsp頁面引入靜態資源文件

下面代碼寫了兩種方式引入,第一種是相對路徑,第二種是絕對路徑.

<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-3.3.1.min.js"></script>
<%
      String path = request.getContextPath();
      String basePath = request.getScheme() + "://"
                  + request.getServerName() + ":" + request.getServerPort()
                  + path + "/";
%>
<script type= "text/javascript" src= "<%=basePath %>js/jquery-3.3.1.min.js"></script >
View Code

三、Ajax與Controller交互

 1.jsp頁面發起json請求

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-3.3.1.min.js"></script>
<%
      String path = request.getContextPath();
      String basePath = request.getScheme() + "://"
                  + request.getServerName() + ":" + request.getServerPort()
                  + path + "/";
%>
<script type= "text/javascript" src= "<%=basePath %>js/jquery-3.3.1.min.js"></script >
<script type="text/javascript">
$(document).ready(function(){
      $("#btnlogin").click(function(){
            var json = {  
                    'name':$(':input[name=username]').val(),  
                'pwd':$(':input[name=password]').val(),
                'birthday':'2018-05-01'
                };
                var postdata = JSON.stringify(json);//json對象轉換json字符串  
                alert(postdata);  
                
                $.ajax({  
                type : 'POST',  
                contentType : 'application/json;charset=UTF-8',//注意類型  
                processData : false,  
                url : '<%=path%>/login/requestbodybind',  
                dataType : 'json',  
                data : postdata,  
                success : function(data) {  
                    alert('username : '+data.name+'\npassword : '+data.pwd);  
                },  
                error : function(err) {  
                    console.log(err.responseText);
                    alert(err.responseText);
                    
                }  
              }); 
      });
    });

</script>
<title>Insert title here</title>
</head>

<body>
<form action="../login/login.action" method="post">  
         姓名:<input type="text" name="username"> <br><br>  
         密碼:   <input type="text" name="password"> <br><br>  
       <input type="button" value="登陸" id="btnlogin">    <input type="submit" value="登陸">  
</form> 
</body>
</html>
View Code

這里增加了一個登陸按鈕,按鈕點擊向Controller發生post請求。這里寫時間參數的話也需要注意一下,我開始是2018/05/01這種,但發現后端不能轉換,提示需要轉成2018-05-01這種。

2.Controller接收json請求

這里主要是有兩個注解:@RequestBody和@ResponseBody。

@RequestBody是作用在形參列表上,用於將前台發送過來固定格式的數據【xml 格式或者 json等】封裝為對應的 JavaBean 對象,封裝時使用到的一個對象是系統默認配置的 HttpMessageConverter進行解析,然后封裝到形參上。
@ResponseBody是作用在方法上的,@ResponseBody 表示該方法的返回結果直接寫入 HTTP response body 中,一般在異步獲取數據時使用【也就是AJAX】,在使用 @RequestMapping后,返回值通常解析為跳轉路徑,但是加上 @ResponseBody 后返回結果不會被解析為跳轉路徑,而是直接寫入 HTTP response body 中。 比如異步獲取 json 數據,加上 @ResponseBody 后,會直接返回 json 數據。@RequestBody 將 HTTP 請求正文插入方法中,使用適合的 HttpMessageConverter 將請求體寫入某個對象。

    @RequestMapping(value="requestbodybind", method = {RequestMethod.POST})  
    @ResponseBody  
    public User requestBodyBind(@RequestBody User user){  
          System.out.println("requestbodybind:" + user);  
          return user;  
    }
View Code

3.運行

當啟動點擊登錄按鈕時報錯.百度了下是需要在maven中引入jackson-databind。

HTTP Status 415 – Unsupported Media Type.The origin server is refusing to service the request because the payload is in a format not supported by this method on the target resource.
 <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.5</version>
</dependency>

 四、小結

基本把springmvc大致過了一遍,今天大概了解了后續的,發現還有好多要學的,springboot、springcloud等等.一口吃不了胖子,還是需要一點一點的學。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM