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>
一、静态资源文件的引入
这里我们用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"/>
二、在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 >
三、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>
这里增加了一个登陆按钮,按钮点击向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; }
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等等.一口吃不了胖子,还是需要一点一点的学。
作者:社会主义接班人
出处:http://www.cnblogs.com/5ishare/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果文中有什么错误,欢迎指出。以免更多的人被误导。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?