springmvc ajax post请求

先去http://mvnrepository.com/搜索fastjson,jackson-annotations,jackson-databind,jackson-core这几个库,根据对应的版本号拿到pom.xml中dependency标签内容,然后复制到项目中的pom.xml中

项目的pom.xml如下:


  4.0.0
  com.springdemo
  demo
  war
  0.0.1-SNAPSHOT
  demo Maven Webapp
  http://maven.apache.org
  
    
      junit
      junit
      3.8.1
      test
    
    
    	javax.servlet
    	javax.servlet-api
    	3.1.0
    
    
    	org.springframework
    	spring-webmvc
    	4.2.4.RELEASE
    
    
    	com.fasterxml.jackson.core
    	jackson-core
    	2.9.0
    
    
    	com.fasterxml.jackson.core
    	jackson-databind
    	2.9.0
    
    
    	com.fasterxml.jackson.core
    	jackson-annotations
    	2.9.0
    
    
    	com.alibaba
    	fastjson
    	1.2.41
    
  
  
    demo
  
    
    UTF-8  
    
然后项目maven install下载库


编写controller,使用@Responsebody注解,指定返回内容

代码,World.java:

package com.springmvc.controller;

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

@Controller
public class World {
    @RequestMapping(value="/hworld",method = RequestMethod.POST)
    @ResponseBody
    public  String sayHello(String pagenum){
    	//获得post参数
    	System.out.println(pagenum);
        return "{\"returncode\":0,\"message\":\"hello world\"}";
    }
}



因为跨域问题要在同目录下配置CORS的Java代码,WebConfig.java:

package com.springmvc.controller;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}


html文件,test.html



	
		
		aaaa
		
	
	
		
		

启动服务

springmvc ajax post请求_第1张图片







你可能感兴趣的:(springmvc)