SpringMVC中接收后端的JSON

读者按

我相信很多同学在学习SpringMVC的时候,可能思路是通的,但是在实际调试的时候,就会遇到各种各样的问题,有的在按照被人的程序走下去,但是就是运行不出正常的结果,前几天,**我在学习SpringMVC中接收后端JSON数据的时候,程序一直调试不同,报各中各样的问题,因为接收后端的JSON数据的时候,**需要用到AJAX,更是让很多没有学过AJAX的同学觉得很难,可能网上的教程出现一点问题,就会导致整个程序运行不出来,进而无法修改,所以我当时也是面临了很多苦难。
当时我在网上搜了很多知识,但是感觉网上的资料真的是千篇一律,都是一个程序,都是相互复制的,没有任何意义,所以今天我想把我调试通的程序展现给大家,大家只需要按照我的步骤做就会看到对应的结果,进而分析里边的原理。毕竟能看到结果,才会更好的激励自己分析结果,如果结果都看不到,就会让自己感觉到很挫败!

实体类的建立(POJO)

这也是非常常规的一步。我自己建立的实体类名为Person,对应的字段有姓名、密码和年龄。具体的代码如下:

package pojo;

public class Person {
	private String pname;
	private String password;
    private Integer page;
    
    public String getPname() {
		return pname;
	}
	public void setPname(String pname) {
		this.pname = pname;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Integer getPage() {
		return page;
	}
	public void setPage(Integer page) {
		this.page = page;
	}
	
}

Controller

这一层的代码也是非常重要的,我当时看到很多网上的资料都是有问题,我直接复制他们的,通过调试就发现是这里的问题,我自己整理的完整的代码如下:

package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import pojo.Person;

@Controller
public class TestController {
	@RequestMapping("/showIndex")
	public String showIndex(){
		return "index";
	}
    /**
     * 接收页面请求的JSON参数,并返回JSON格式的结果
     */
	@RequestMapping(value ="/testJson")
    @ResponseBody
    public Person testJson(@RequestBody Person user) {
    	System.out.println("pname=" + user.getPname() + ",password="
                + user.getPassword() + ",page=" + user.getPage());
		return user;
    }	
}

xml文件的设置

xml文件的配置也是非常重要的,因为可能应为xml配置错误,导致程序运行不出来,这也是运用框架的弊端,必须要按照他们的规定来写程序,具体的xml配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 使用扫描机制扫描控制器类,控制器类都在controller包及其子包下 -->
    <context:component-scan base-package="controller" />
    <mvc:annotation-driven />
   
    <mvc:default-servlet-handler/>
    <!-- annotation-driven用于简化开发的配置,注解DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
    <!-- 使用resources过滤掉不需要dispatcherservlet的资源(即静态资源,例如css、js、html、images)。
        在使用resources时必须使用annotation-driven,否则resources元素会阻止任意控制器被调用 -->
    <!-- 允许js目录下的所有文件可见 -->
    <mvc:resources location="/js/" mapping="/js/**" />
    <!-- 配置视图解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

js文件的选择

js就是让前端的页面动起来,向后端传递对饮的JSON数据,这里用的是jquery-1.8.3.min.js。对应在项目中的存放位置如下所示:
js文件在项目中的位置
这个也是非常简单的,直接可以在网上搜索jquery,然后找到对应的版本,直接将对应的网页上的内容另存为js文件就可以了,我会专门给大家分享出这样的文件,可以看我其他的blog。

JSP页面的设置

JSP页面里包含了相关的JS代码,我看到网上很多都是错误,不是缺少这个就是缺少那个,所以通过我自己的调试和代码书写,将调整好的代码展示给大家,大家直接用就好了,具体的代码如下:

<%@ 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">
<title></title>
<script type="text/javaScript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.min.js"  ></script>
</head>
<body>
   <form method="post" action="${pageContext.request.contextPath}/testJson">
        用户名:<input type="text" name="pname" id="pname" /><br> 
        密码:<input type="password" name="password" id="password" /> <br> 
        年龄:<input type="text" name="page" id="page"><br> 
        <input type="button" value="测试" onclick="testJson()" />
    </form>
</body>
<script type="text/javaScript">
    function testJson() {
        //获取输入的值pname为id
        alert($("#pname").val());
        var pname = $("#pname").val();
        var password = $("#password").val();
        var page = $("#page").val();
        $.ajax({
            //请求路径
            url : "${pageContext.request.contextPath}/testJson",
            //请求类型
            type : "POST",
            //data表示发送的数据
            data : JSON.stringify({
                pname : pname,
                password : password,
                page : page
            }), //定义发送请求的数据格式为JSON字符串
            contentType : "application/json;charset=utf-8",
            //定义回调响应的数据格式为JSON字符串,该属性可以省略
            dataType : "json",
            //成功响应的结果
            success : function(data) {
                if (data != null) {
                    alert("输入的用户名:" + data.pname + ",密码:" + data.password
                            + ", 年龄:" + data.page);
                }
                else{
                    alert("数据没有传过来");
                }
            }
        });
    }
</script>
</html>

运行过程

以上是我的代码,运行的过程如下所示:
输入对应的URL,输入对应的数据项
点解测试,得到结果:
第一个alert
点解确定后:
alert,显示具体的数据项
后天console为:
后台的console数据
以上是我个人整理的代码,能够运行出完整的结果,中间很多知识,大家可以进行深入分析,看到结果了,再去分析代码也是非常有意义了,我这里做的就是这个工作,帮助大家把程序运行出来,激励自己的继续下去!

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值