spring mvc ajax请求

jar包中增加

jackson-annotations-2.5.0.jar

jackson-core-2.5.0.jar

jackson-databind-2.5.0.jar

springmvx.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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc
     http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd">
    <!-- spring mvc 注解驱动 -->
    <mvc:annotation-driven />
    <!-- 扫描器 -->
    <context:component-scan base-package="com" />

    <!-- 配置视图 解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀和后缀 -->
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 从请求和响应读取/编写字符串 -->
    <bean id="stringHttpMessage"
        class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/plain;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <!-- 用于将对象转换为JSON -->
    <bean id="jsonConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>

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

</beans>

handler

package com.stone.controller;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

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

import com.stone.bean.UserInfo;

/**
 */
@Controller
public class UserController {

    @RequestMapping("/ajaxUser.do")
    public void userNumber(String num, HttpServletResponse response) {
        System.out.println(num);
        try {
            // 响应
            response.setContentType("text/html");
            response.setCharacterEncoding("utf-8");
            PrintWriter out = response.getWriter();
            if ("stone".equals(num)) {
                out.println("对不起,请重新输入账号!");
            } else {
                out.println("恭喜你,账号可以使用!");
            }
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/ajaxUser2.do")
    public @ResponseBody
    UserInfo ajaxUser(Integer userId) {
        System.out.println("-------bianhao:" + userId);
        UserInfo user = new UserInfo();
        user.setUserId(userId);
        user.setUserName("张三");
        user.setUserSex("男");
        return user;
    }

}

js

function btn01Click() {
    var num = $(‘#userNumber‘).val();
    if (num === ‘‘) {
        alert(‘请输入账号!‘);
    } else {
        $.post(‘ajaxUser.do‘, {
            num : num
        }, function(data) {
            alert(data);
        });
    }
}

function btn02Click() {
    var num = $(‘#userId‘).val();
    if (num === ‘‘) {
        alert(‘请输入账号!‘);
    } else {
        $.post(‘ajaxUser2.do‘, {
            userId : num
        }, function(data) {
            alert(data.userId+‘----‘+data.userName+‘----‘+data.userSex);
        }, "json");
    }
}

java bean

package com.stone.bean;

import java.util.Arrays;
import java.util.Date;

import org.springframework.format.annotation.DateTimeFormat;

public class UserInfo {

    private Integer userId;
    private String userName;
    private String userSex;
    private String[] userxq;
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date userTime;

    @Override
    public String toString() {
        return "UserInfo [userId=" + userId + ", userName=" + userName
                + ", userSex=" + userSex + ", userxq="
                + Arrays.toString(userxq) + ", userTime=" + userTime + "]";
    }

    public Date getUserTime() {
        return userTime;
    }

    public void setUserTime(Date userTime) {
        this.userTime = userTime;
    }

    public String[] getUserxq() {
        return userxq;
    }

    public void setUserxq(String[] userxq) {
        this.userxq = userxq;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserSex() {
        return userSex;
    }

    public void setUserSex(String userSex) {
        this.userSex = userSex;
    }

}
时间: 2024-10-12 11:24:19

spring mvc ajax请求的相关文章

spring mvc+ajax 实现json格式数据传递

使用ajax传递JSON对象 下面示例为ajax发送json对象,返回json格式数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 $.ajax({ url: "api/user", type: "POST", timeout: txnTimeOut, async: true, dataType: "json", data: {username : "lucy"}

spring mvc get请求也可以接受DTO对象

spring mvc get请求也可以接受DTO对象,比如:url上面你还是将参数&符号连接起来,并自动封装进一个DTO对象里. 只有@RequestBody注解spring mvc才会从http body里去拿数据. 默认不填注解的参数都会从url上面去拿. @ApiOperation(value = "查询卡券详情接口", consumes = "application/x-www-form-urlencoded") @RequestMapping(va

研究 Spring MVC 将请求分发到 Spring 依赖注入的类实例

太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS.Android.Html5.Arduino.pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作. 一上午时间,碰了 N 个钉子,不断地把钉子拨掉,记录一下选择的工具和方法: 1.首先 Spring Mvc 框架的下载,那么有三个包是必不可少的:

Spring Mvc——处理请求过程

1.概述 下面这张图是Spring mvc处理请求的整体流程,其中Front controller指的是DispatcherServlet类. 1.客户端所有的请求都会发送到DispatcherServlet,由DispacherServlet处理. 2.DispacherServlet将请求分发到不同的Controller类,由Controller类去处理对应的请求. 3.Controller类将对应的请求处理完后,将处理后对应的model或者视图信息给将DispatcherServlet类.

spring mvc ajax 提交复杂数组类型

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method 1.Spring Mvc 配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp

spring mvc ajax success不执行 反倒执行error

问题描述:spring mvc中前端使用ajax发送请求,后台使用@ResponseBody直接写数据到响应体中, 返回一个字符串,ajax的success回调函数不执行,反而执行error的回调函数 上代码: ajax请求: $.ajax({                url:"/eCommerceSSM/updateAdmin",                type:"put",                data:JSON.stringify({a

Spring MVC HTTP请求数据绑定

package com.springmvc.controller; import com.springmvc.model.UserInfo; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Controller; import org.springframework.uti

Spring MVC http请求地址映射(三)

Spring MVC框架通过扫描将带有@Controller的类中的@RequestMapping的方法进行映射,然后调用映射的方法处理请求,这个分发过程默认是由DispaterServlet处理的. http请求映射原理 Spring MVC进行映射的依据 通过URL限定:URL表达式 Spring MVC的地址映射支持标准的URL,同时默认支持是ant风格的URL.列如: URL 说明 /account/*/create 匹配/account/aaa/create./account/bbb/

Spring MVC ajax:post/get 的具体实现

Post 方式 1.自动注入 a. pom.xml ---- 配置Maven,添加必要的jar包 1 <!--用于 String-JSONObject 转换 --> 2 <dependency> 3 <groupId>org.json</groupId> 4 <artifactId>org.json</artifactId> 5 <version>chargebee-1.0</version> 6 </d