1. 新建web project

2. 增加jar

3. 改写web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> </web-app>

4. 新建config包下的spring-servlet.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 注解扫描包 -->
<context:component-scan base-package="com.tgb.web.controller" /> <!-- 开启注解 -->
<mvc:annotation-driven/> <!-- 静态资源访问 -->
<mvc:resources location="/img/" mapping="/img/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:resources location="/css/" mapping="/css/**"/> <!-- ViewResolver 视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean> </beans>

5. 新建UserController.java, 在com.tgb.web.controller包下

package com.tgb.web.controller;
import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import com.tgb.web.controller.entity.User; @Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/addUser")
public String addUser(User user,HttpServletRequest request){
String result = "this is addUser---------优化版";
request.setAttribute("userName", user.getUserName());
request.setAttribute("age", user.getAge());
return "/userManager";
} @RequestMapping("/addUserJson")
public void addUserJson(User user,HttpServletRequest request, HttpServletResponse response){ String result = "{\"userName\":\" "+ user.getUserName()+" \", \"age\":\" "+ user.getAge()+" \"}";
  PrintWriter out = null;
  response.setContentType("application/json");
  try {
out=response.getWriter();
out.write(result);
  } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
  }
    } @RequestMapping("/toUser")
public String toUser(){
return "/json";
}
}

  

6. 创建json.jsp文件

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.4.2.min.js"></script>
<title>My JSP 'addUser.jsp' starting page</title>
<script type="text/javascript">
$(document).ready(function(){
$("#add").click(function(){
var userName=$("#userName").attr("value");
var age=$("#age").attr("value");
var user={userName:userName,age:age};
$.ajax({
url:"/springMVC5/user/addUserJson",
type:"POST",
data: user,
success:function(data){
<%--alert("userName--->"+data.userName +"age--->"+data.age);--%>
document.getElementById("div").innerHTML="<font color='red'>"+data.userName+data.age+"</font>"+"添加成功";
}
});
});
});
</script>
</head>
<body>
<h> json添加用户 </h> <br>
姓名: <input type="text" id="userName" name="userName">
年龄: <input type="text" id="age" name="age"> <br/>
<input type="button" id="add" value="添加">
<div id="div"> </div>
</body>
</html>

  

7.IE端验证

http://localhost:8080/springMVC5/user/toUser

  

springMVC和json结合传递数据的更多相关文章

  1. 9.SpringMVC和json结合传递数据 && 10.SpringMVC获取controller中json的数据

  2. SpringMVC跨重定向请求传递数据

    (1)使用URL模板以路径变量和查询参数的形式传递数据(一些简单的数据) @GetMapping("/home/index") public String index(Model ...

  3. springmvc接收JSON类型的数据

    1.在使用AJAX传递JSON数据的时候要将contentType的类型设置为"application/json",否则的话会提示415错误 2.传递的data需要时JSON类型的 ...

  4. php和js如何通过json互相传递数据

    当我们在结合php和javascript实现某些功能时,经常会用到json.json是js的一种数据格式,可以直接被js解析.而php无法直接读取json数据,但是php提供了json_decode函 ...

  5. C#开发的WebService使用JSON格式传递数据+Ajax测试

    [C#]  WebService 使用 JSON 格式傳遞筆記 + JQuery 測試 0 2 因為一些因素,必須改寫WebService,很傳統,但是很多公司還在用.. 因為XML 的關係,不想讓他 ...

  6. 9.SpringMVC和json结合传递参数

    input的值一定要用.attribute来取值.val( )只能用可以看看开源社区jQuery的ajax请求.html():读取和修改一个元素的HTML内容,详情.html():.text():读取 ...

  7. SpringMVC使用POST方法传递数据,却出现Request method 'GET' not supported?

    转自:https://segmentfault.com/q/1010000011245770 问题:没有使用get获取当前页面解决方案:   @RequestMapping(value = " ...

  8. springMVC接受json类型数据

    springMVC接受json格式的数据很简单 使用@RequestBody 注解,标识从请求的body中取值 服务端示例代码 @RequestMapping(value = "/t4&qu ...

  9. Spring MVC 处理JSON | JSONP类型数据

    SpringMVC返回JSON格式的数据: 1 添加jar包(gson-2.8.0.jar): <dependency> <groupId>com.google.code.gs ...

随机推荐

  1. how computer boot up?

    The power button activates the power supply in the PC, sending power to the motherboard and other co ...

  2. 25个超有用的 AngularJS Web 开发工具

    AngularJS是为了克服HTML在构建应用上的不足而设计的.HTML是一门很好的为静态文本展示设计的声明式语言,改善了JavaScript. 下面我要说的就是25个超有用的AngularJS工具, ...

  3. 在Linux系统如何让程序开机时自动启动

    在Linux系统如何让程序开机时自动启动      核心提示:系统的服务在开机时一般都可以自动启动,那在linux系统下如果想要程序在开机时自动启动怎么办?我们知道在 windows系统“开始”--& ...

  4. windowSoftInputMode键盘把输入框挡住了

    android:windowSoftInputMode="stateHidden|adjustResize" >

  5. C#中使用正则表达式提取超链接地址的集中方法

    一般在做爬虫或者CMS的时候经常需要提取 href链接或者是src地址.此时可以使用正则表达式轻松完成. Regex reg = new Regex(@"(?is)<a[^>]* ...

  6. c++11 对象池的实现

    ; template <typename T> class ObjectPool { template <typename... Args> using Constructor ...

  7. 常见html标签

    1.flash嵌入标签 <object> <embed allowscriptaccess="always" allowfullscreen="true ...

  8. 3.1 cron表达式

    1.Cron在线生成网址:      http://cron.qqe2.com/   http://www.pdtools.net/tools/becron.jsp#cron 2.Cron 概要 3. ...

  9. 使用btoa和atob来进行Base64转码和解码

      btoa: 将普通字符串转为Base64字符串 atob: 将Base64字符串转为普通字符串   说明:window.btoa不支持汉字:   ===>使用window.encodeURI ...

  10. ignite中的消息使用实例

    消息很简单,跟其他的mq相仿,关键点: 一,添加监听,订阅主题 二,发送消息 写了一个简单的示例: Receiver.java package test.ignite.broadcast; impor ...