springMVC和json结合传递数据
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结合传递数据的更多相关文章
- 9.SpringMVC和json结合传递数据 && 10.SpringMVC获取controller中json的数据
- SpringMVC跨重定向请求传递数据
(1)使用URL模板以路径变量和查询参数的形式传递数据(一些简单的数据) @GetMapping("/home/index") public String index(Model ...
- springmvc接收JSON类型的数据
1.在使用AJAX传递JSON数据的时候要将contentType的类型设置为"application/json",否则的话会提示415错误 2.传递的data需要时JSON类型的 ...
- php和js如何通过json互相传递数据
当我们在结合php和javascript实现某些功能时,经常会用到json.json是js的一种数据格式,可以直接被js解析.而php无法直接读取json数据,但是php提供了json_decode函 ...
- C#开发的WebService使用JSON格式传递数据+Ajax测试
[C#] WebService 使用 JSON 格式傳遞筆記 + JQuery 測試 0 2 因為一些因素,必須改寫WebService,很傳統,但是很多公司還在用.. 因為XML 的關係,不想讓他 ...
- 9.SpringMVC和json结合传递参数
input的值一定要用.attribute来取值.val( )只能用可以看看开源社区jQuery的ajax请求.html():读取和修改一个元素的HTML内容,详情.html():.text():读取 ...
- SpringMVC使用POST方法传递数据,却出现Request method 'GET' not supported?
转自:https://segmentfault.com/q/1010000011245770 问题:没有使用get获取当前页面解决方案: @RequestMapping(value = " ...
- springMVC接受json类型数据
springMVC接受json格式的数据很简单 使用@RequestBody 注解,标识从请求的body中取值 服务端示例代码 @RequestMapping(value = "/t4&qu ...
- Spring MVC 处理JSON | JSONP类型数据
SpringMVC返回JSON格式的数据: 1 添加jar包(gson-2.8.0.jar): <dependency> <groupId>com.google.code.gs ...
随机推荐
- how to stop a thread
it seems all stop methods of thread have been deprecated by java. so how to stop a thread then? it i ...
- unknown filesystem type ‘iso9660’类型问题--Ubuntu
unknown filesystem type ‘iso9660’是指系统不支持这种类型的文件, 用以下命令更新内核即可: sudo aptitude update sudo aptitude upg ...
- style控制打印分页
[转载地址:http://www.cnblogs.com/JustinYoung/articles/710734.html]page-break-before和page-break-after CSS ...
- access的保留关键字
access的保留关键字 -A ADD ALL Alphanumeric ALTER AND ANY Application AS ...
- Sql server 开窗函数over()的语法
用法一:与ROW_NUMBER()函数结合用,给结果进行排序编号,如图: 代码如下: SELECT ROW_NUMBER() over(order by RequiredDate) num ,* fr ...
- sql server获取当前年月日 时分秒
获取当前年月日(字符串): ),) 获取当前时间的时分秒(':'隔开): ),) 将年月日时分秒拼接成一条字符串: ),)),),':','')
- Spring MVC中,事务是否可以加在Controller层
一般而言,事务都是加在Service层的,但是爱钻牛角尖的我时常想:事务加在Controller层可不可以.我一直试图证明事务不止可以加在Service层,还可以加在Controller层,但是没有找 ...
- ignite通过注解配置查询
官方文档的叙述可能有些不清楚,我做了一个测试,并且可以成功运行,待会儿后面贴出小栗子. 两步操作: 第一步在属性值处贴上@QuerySqlField注解 第二部设置key和value类型 Person ...
- PHP全选择删除功能
<script type="text/javascript" language="javascript"> function selectBox(s ...
- 自动打开notepad 并写入数据
import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.io. ...