SpringMVC @ResponseBody 415错误处理

SpringMVC @ResponseBody 415错误处理闲话少说,刚开始用SpringMVC,页面要使用jquery的ajax请求Controller。但总是失败,主要表现为以下两个异常为:异常一:java.lang.ClassNotFoundException:org.springframework.http.converter.json.MappingJacksonHttpMessageConverter异常二

大家好,又见面了,我是你们的朋友全栈君。

闲话少说,刚开始用SpringMVC, 页面要使用jquery的ajax请求Controller。 但总是失败,主要表现为以下两个异常为:

异常一:java.lang.ClassNotFoundException: org.springframework.http.converter.json.MappingJacksonHttpMessageConverter

异常二:SpringMVC @ResponseBody 415错误处理

网上分析原因很多,但找了很久都没解决,基本是以下几类:

  • springmvc添加配置、注解;
  • pom.xml添加jackson包引用;
  • Ajax请求时没有设置Content-Type为application/json
  •  发送的请求内容不要转成JSON对象,直接发送JSON字符串即可

这些其实都没错!!!

以下是我分析的解决步骤方法:

(1)springMVC配置文件开启注解

   <!-- 开启注解-->
    <mvc:annotation-driven />

(2)添加springMVC需要添加如下配置。 (这个要注意spring版本,3.x和4.x配置不同

spring3.x是org.springframework.http.converter.json.MappingJacksonHttpMessageConverter

spring4.x是org.springframework.http.converter.json.MappingJackson2HttpMessageConverter


具体可以查看spring-web的jar确认,哪个存在用哪个!


spring3.x配置:

	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="jsonHttpMessageConverter" />
			</list>
		</property>
	</bean>

	<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>application/json;charset=UTF-8</value>
			</list>
		</property>
	</bean>

spring4.x配置:

	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="jsonHttpMessageConverter" />
			</list>
		</property>
	</bean>

	<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>application/json;charset=UTF-8</value>
			</list>
		</property>
	</bean>

(3)pom.xml添加jackson依赖(这个要注意spring版本,3.x和4.x配置不同

如果是spring 3.x,pom.xml添加如下配置

       <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-lgpl</artifactId>
            <version>1.8.1</version>
         </dependency>


        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-lgpl</artifactId>
            <version>1.8.1</version>
        </dependency></span>

spring4.x,  pom.xml添加如下配置

	    <dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.5.2</version>
		</dependency>
		
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.5.2</version>
		</dependency>

这里要说明一下,spring3.x用的是org.codehaus.jackson的1.x版本,在maven资源库,已经不在维护,统一迁移到com.fasterxml.jackson,版本对应为2.x


SpringMVC @ResponseBody 415错误处理

SpringMVC @ResponseBody 415错误处理SpringMVC @ResponseBody 415错误处理

SpringMVC @ResponseBody 415错误处理

(4)ajax请求要求

  •      dataType 为 json
  •         contentType 为 ‘application/json;charse=UTF-8’
  •         data 转JSON字符串

        我的代码:如下:  (注意:这里只是针对POST +JSON字符串形式请求,后面我会详细讲解不同形式请求,的处理方法和案例)

         var data = {
		userAccount: lock_username,
		userPasswd:hex_md5(lock_password).toUpperCase()
	 }
	 
	 $.ajax({
			url : ctx + "/unlock.do",
			type : "POST",
			data : JSON.stringify(data),
		        dataType: 'json',
	                contentType:'application/json;charset=UTF-8',    
			success : function(result) {
				console.log(result);
			}
	 });

(5)  Controller 接收响应JSON

     以上配置OK,Controller中使用JSON方式有多种。这里简单介绍几种。

这个关键在于ajax请求是将数据以什么形式传递到后台,这里我总结了三种形式

  • POST + JSON字符串形式
  • POST + JSON对象形式
  • GET + 参数字符串

  • 方式一: POST + JSON字符串形式,如下:
//请求数据,登录账号 +密码
	 var data = {
			 userAccount: lock_username,
			 userPasswd:hex_md5(lock_password).toUpperCase()
	 }
	 
	 $.ajax({
			url : ctx + "/unlock.do",
			type : "POST",
			data : JSON.stringify(data), //转JSON字符串
		    dataType: 'json',
	        contentType:'application/json;charset=UTF-8', //contentType很重要   
			success : function(result) {
				console.log(result);
			}
	 });
  • 方式二: POST + JSON对象形式,如下:
	 
	 //请求数据,登录账号 +密码
 var data = {
			 userAccount: lock_username,
			 userPasswd:hex_md5(lock_password).toUpperCase()
	 }
	 
	 $.ajax({
			url : ctx + "/unlock.do",
			type : "POST",
			data : data, //直接用JSON对象
		    dataType: 'json',
			success : function(result) {
				console.log(result);
			}
	 });

代码案例:

5-1: 使用@RequestBody来设置输入 ,@ResponseBody设置输出 (POST + JSON字符串形式

JS请求:

	 //请求数据,登录账号 +密码
	 var data = {
			 userAccount: lock_username,
			 userPasswd:hex_md5(lock_password).toUpperCase()
	 }
	 
	 $.ajax({
			url : ctx + "/unlock.do",
			type : "POST",
			data : JSON.stringify(data), //转JSON字符串
		    dataType: 'json',
	        contentType:'application/json;charset=UTF-8', //contentType很重要   
			success : function(result) {
				console.log(result);
			}
	 });

Controller处理:

    @RequestMapping(value = "/unlock", method = RequestMethod.POST,consumes = "application/json") 
    @ResponseBody
    public Object unlock(@RequestBody User user) {  
		JSONObject jsonObject = new JSONObject();  
		
		try{
			Assert.notNull(user.getUserAccount(), "解锁账号为空");
			Assert.notNull(user.getUserPasswd(), "解锁密码为空");
			
			User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER);
			Assert.notNull(currentLoginUser, "登录用户已过期,请重新登录!");
			
			Assert.isTrue(StringUtils.equals(user.getUserAccount(),currentLoginUser.getUserAccount()), "解锁账号错误");
			Assert.isTrue(StringUtils.equalsIgnoreCase(user.getUserPasswd(),currentLoginUser.getUserPasswd()), "解锁密码错误");
			
jsonObject.put("message", "解锁成功");  
jsonObject.put("status", "success");
		}catch(Exception ex){
			jsonObject.put("message", ex.getMessage());  
		        jsonObject.put("status", "error");
		}
       return jsonObject;  
    }  

浏览器控制台输出:

SpringMVC @ResponseBody 415错误处理

5-2: 使用HttpEntity来实现输入绑定,来ResponseEntit输出绑定POST + JSON字符串形式

JS请求:

	 //请求数据,登录账号 +密码
	 var data = {
			 userAccount: lock_username,
			 userPasswd:hex_md5(lock_password).toUpperCase()
	 }
	 
	 $.ajax({
			url : ctx + "/unlock.do",
			type : "POST",
			data : JSON.stringify(data), //转JSON字符串
		    dataType: 'json',
	        contentType:'application/json;charset=UTF-8', //contentType很重要   
			success : function(result) {
				console.log(result);
			}
	 });

Controller处理:

	
    @RequestMapping(value = "/unlock", method = RequestMethod.POST,consumes = "application/json") 
    public ResponseEntity<Object> unlock(HttpEntity<User> user) {  
		JSONObject jsonObject = new JSONObject();  
		
		try{
			Assert.notNull(user.getBody().getUserAccount(), "解锁账号为空");
			Assert.notNull(user.getBody().getUserPasswd(), "解锁密码为空");
			
			User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER);
			Assert.notNull(currentLoginUser, "登录用户已过期,请重新登录!");
			
			Assert.isTrue(StringUtils.equals(user.getBody().getUserAccount(),currentLoginUser.getUserAccount()), "解锁账号错误");
			Assert.isTrue(StringUtils.equalsIgnoreCase(user.getBody().getUserPasswd(),currentLoginUser.getUserPasswd()), "解锁密码错误");
			
	               jsonObject.put("message", "解锁成功");  
	               jsonObject.put("status", "success");
		}catch(Exception ex){
			jsonObject.put("message", ex.getMessage());  
		        jsonObject.put("status", "error");
		}
		ResponseEntity<Object> responseResult = new ResponseEntity<Object>(jsonObject,HttpStatus.OK);
	        return responseResult;
    }  

5-3: 使用request.getParameter获取请求参数,响应JSONPOST + JSON对象形式) 和(GET + 参数字符串),Controller处理一样,区别在于是否加注解method ,

如果不加适用GET + POST ;

如果 method= RequestMethod.POST,用于POST 请求;

如果method=RequestMethod.GET,用于GET请求;

 POST+ JSON对象形式请求:

 var data = {
			 userAccount: lock_username,
			 userPasswd:hex_md5(lock_password).toUpperCase()
	 }
	 
	 $.ajax({
			url : ctx + "/unlock.do",
			type : "POST",
			data : data,
		    dataType: 'json',
			success : function(result) {
				console.log(result);
			}
	 });

GET + 参数字符串请求:

	 $.ajax({
			url : ctx + "/unlock.do",
			type : "GET",
			dataType: "text", 
			data : "userAccount="+lock_username+"&userPasswd=" + hex_md5(lock_password).toUpperCase(),//等价于URL后面拼接参数
			success : function(result) {
				console.log(result);
			}
	 });

Controller处理:

	
	@RequestMapping(value = "/unlock") 
    public void unlock(HttpServletRequest request,HttpServletResponse response)  throws IOException {  
		JSONObject jsonObject = new JSONObject();  
		
		String userAccount = (String)request.getParameter("userAccount");
		String userPasswd = (String)request.getParameter("userPasswd");
		try{
			Assert.notNull(userAccount, "解锁账号为空");
			Assert.notNull(userPasswd, "解锁密码为空");
			
			User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER);
			Assert.notNull(currentLoginUser, "登录用户已过期,请重新登录!");
			
			Assert.isTrue(StringUtils.equals(userAccount,currentLoginUser.getUserAccount()), "解锁账号错误");
			Assert.isTrue(StringUtils.equalsIgnoreCase(userPasswd,currentLoginUser.getUserPasswd()), "解锁密码错误");
			
	        jsonObject.put("message", "解锁成功");  
	        jsonObject.put("status", "success");
		}catch(Exception ex){
			jsonObject.put("message", ex.getMessage());  
		    jsonObject.put("status", "error");
		}
		
        response.getWriter().print(jsonObject.toString());  
    }  

5-4: 使用@ModelAttribute将参数封装对象,响应JSONPOST + JSON对象形式) 和(GET + 参数字符串),Controller处理一样,区别在于是否加注解method 。

如果不加适用GET + POST ;

如果 method= RequestMethod.POST,用于POST 请求;

如果method=RequestMethod.GET,用于GET请求;


 POST+ JSON对象形式请求:

	 var data = {
			 userAccount: lock_username,
			 userPasswd:hex_md5(lock_password).toUpperCase()
	 }
	 
	 $.ajax({
			url : ctx + "/unlock.do",
			type : "POST",
			data : data,
		    dataType: 'json',
			success : function(result) {
				console.log(result);
			}
	 });

GET + 参数字符串请求:

	 $.ajax({
			url : ctx + "/unlock.do",
			type : "GET",
			dataType: "text", 
			data : "userAccount="+lock_username+"&userPasswd=" + hex_md5(lock_password).toUpperCase(),//等价于URL后面拼接参数
			success : function(result) {
				console.log(result);
			}
	 });

Controller处理:(这个案例只支持POST)

	
	@RequestMapping(value = "/unlock",method = RequestMethod.POST) 
    public void unlock(@ModelAttribute("user") User user,PrintWriter printWriter)  throws IOException {  
		JSONObject jsonObject = new JSONObject();  
		
		try{
			Assert.notNull(user.getUserAccount(), "解锁账号为空");
			Assert.notNull(user.getUserPasswd(), "解锁密码为空");
			
			User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER);
			Assert.notNull(currentLoginUser, "登录用户已过期,请重新登录!");
			
			Assert.isTrue(StringUtils.equals(user.getUserAccount(),currentLoginUser.getUserAccount()), "解锁账号错误");
			Assert.isTrue(StringUtils.equalsIgnoreCase(user.getUserPasswd(),currentLoginUser.getUserPasswd()), "解锁密码错误");
			
	        jsonObject.put("message", "解锁成功");  
	        jsonObject.put("status", "success");
		}catch(Exception ex){
			jsonObject.put("message", ex.getMessage());  
		    jsonObject.put("status", "error");
		}
		printWriter.print(jsonObject.toString());
    }  
	

寻找问题学习过程中参考资料:

SpringMVC @ResponseBody 415错误处理

SpringMVC @ResponseBody 415错误处理

SpringMVC @ResponseBody 415错误处理

其他可以学习参考的博客:


版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/132444.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • LoadLibrary失败

    LoadLibrary失败LoadLibrary失败 今天同事遇到一个问题,经高手指点,完美解决。不过解决方法总是感觉有点不妥,不知道有没有其它方法。 正常情况,在一个exe中LoadLibrary(DLL1)可以获得正常的结果; 但是,当我们需要load的DLL1如果调用了其它的DLL2,那么我们就会得到一个结果:Theprogramcantstartbecause****.dl

    2022年7月26日
    19
  • 关于MIUI12.5或者任何无法使用GMS谷歌全家桶的解决办法[通俗易懂]

    关于MIUI12.5或者任何无法使用GMS谷歌全家桶的解决办法[通俗易懂]首先感谢酷安社区的@兔子吃肉不吃草原文链接:https://www.coolapk.com/feed/24583874由于其文章全部都是图片贴的代码而且没加说明对于小白比较难懂,我在这里对其进行进一步的补充和完善必要条件:手机已经root,电脑安装有adb(不知道adb是什么没关系,下载个小米助手,里边会自带一个adb.exe)开始1.电脑连接手机手机打开usb调试,电脑连接手机2.进入adb命令行如果你之前已经安装了adb并且配置了环境变量,可以直接打开cmd

    2022年6月27日
    139
  • java 长轮询_基于springboot 长轮询的实现操作

    java 长轮询_基于springboot 长轮询的实现操作springboot长轮询实现基于@EnableAsync,@Sync@SpringBootApplication@EnableAsyncpublicclassDemoApplication{publicstaticvoidmain(String[]args){SpringApplication.run(DemoApplication.class,args);}}@Req…

    2022年10月14日
    1
  • 微信小程序快速接口编写

    微信小程序快速接口编写

    2021年9月17日
    88
  • HelloWorld的Java代码[通俗易懂]

    HelloWorld的Java代码[通俗易懂]HelloWorld的Java代码//类名publicclassHelloWorld{//主函数,主方法,程序的入口publicstaticvoidmain(String[]args){//输出语句System.out.println(“HelloWorld!”);}}欢迎使用Markdown编辑器你好!这是你第一次使用Markdown编辑器所展示的欢迎…

    2022年5月28日
    53
  • [MFC]同步对象——CCriticalSection临界区,CSemaphore信号量

    [MFC]同步对象——CCriticalSection临界区,CSemaphore信号量实例——CCriticalSection临界区临界区是保证在某一个时间只有一个线程可以访问数据的方法。使用它的过程中,需要给每个线程提供一个共享的临界区对象,无论哪个线程占有临界区对象,都可以访问受到保护的数据,这时候其他的线程需要等待,直至该线程释放临界区对象为止,临界区被释放后,另外的线程可以强占这个临界区,以便访问共享的数据。临界区对应的一个CCriticalSection对象,

    2022年7月20日
    16

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号