• 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+'
    password : '+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等等.一口吃不了胖子,还是需要一点一点的学。

  • 相关阅读:
    PG-日常管理
    PG-高可用(pgpool-Ⅱ)
    PG-基准测试
    PG-备份恢复
    PG-并发问题
    Go-常量
    Go-变量
    Oracle-11g升级PSU补丁
    Oracle-`sqlplus`工具使用技巧
    [CF1051F] The Shortest Statement
  • 原文地址:https://www.cnblogs.com/5ishare/p/8976476.html
Copyright © 2020-2023  润新知