$(document).ready(function() {
$('#btn').on('click',() {
$.ajax('http://localhost:8081/springmvc/my/my2/1/1',{
dataType : 'jsonp'"aa"(data,status) {
console.log('111:'+data.Hello+' '+data);
}
})
})
})
@RequestMapping("my2/{courseId}/{name}")
@ResponseBody
public String method2(@PathVariable("courseId") String courseId,@PathVariable("name") String name){
//必须是这种形式的字符串,其中小括号内的字符串必须是标准的json格式的
String str="aa({\"Hello\":\"World\"})";
return str;
}
package com.cn.my.filter;
import java.io.IOException;
javax.servlet.Filter;
javax.servlet.FilterChain;
javax.servlet.FilterConfig;
javax.servlet.ServletException;
javax.servlet.ServletRequest;
javax.servlet.ServletResponse;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
public class CORSFilter implements Filter {
@Override
void destroy() {
// TODO Auto-generated method stub
}
实现向响应头部添加Access-Control-Allow-Origin属性,实现跨域访问。
@Override
doFilter(ServletRequest sRequest,ServletResponse sResponse,FilterChain chain) throws IOException,ServletException {
HttpServletRequest request=(HttpServletRequest)sRequest;
HttpServletResponse response=(HttpServletResponse)sResponse;
response.setHeader("Access-Control-Allow-Origin","*");
chain.doFilter(sRequest,sResponse);
}
@Override
void init(FilterConfig arg0) ServletException {
}
}
<!--跨域访问-->
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.cn.my.filter.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
$('#btn').on('click',{
type : 'get'data);
}
})
})
@RequestMapping("my2/{courseId}/{name}"public Map<String,String> method2(@PathVariable("courseId") String courseId,1)">) String name){
HashMap<String,String> map=new HashMap<String,String>();
map.put("name","刘三");
map.put("sex","女");
map.put("age","47");
map;
}