700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > SpringMVC之数据传递三Ajax与Controller交互

SpringMVC之数据传递三Ajax与Controller交互

时间:2023-10-19 07:27:48

相关推荐

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" "/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':'-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请求。这里写时间参数的话也需要注意一下,我开始是/05/01这种,但发现后端不能转换,提示需要转成-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.

<!-- /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等等.一口吃不了胖子,还是需要一点一点的学。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。