Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Springmvc to complete ajax function

Shulou Source: shulou.com Published: 2022-06-03 09:25:35 11月15日 Update

Xiaobian to share with you how to use Springmvc to complete the Ajax function, I hope you have some gains after reading this article, let's discuss it together!

1. Add Jackson's jar package

2. Add @ResponseBody to the response method: convert java objects to json objects

3. The return value of the method can be an object collection string

$.post("ajax/Ajax1",{"name":"zhu"},function(data){ $.each(data,function(i,n){ alert(n.name); }) })

Can return strings

@RequestMapping(value="Ajax1", products = "text/html;charset=UTF-8") @ResponseBody public String ajax1(String name) { System.out.println(name); return "hello"; }

You can also return objects.

@RequestMapping("Ajax2") @ResponseBody public User ajax2(String name) { User user=new User("中","1"); return user; }

You can also return collections

@RequestMapping("Ajax3") @ResponseBody public List ajax3(String name) { User user1 =new User("中","1"); User user2 =new User("","2"); User user3 =new User("","3"); List list=new ArrayList(); list.add(user1); list.add(user2); list.add(user3); return list; }

When returning a character string, if the input Chinese characters will appear garbled, the solution is as follows

1. Change @RequestMapping

@RequestMapping(value="Ajax1",produces="text/html;charset=UTF-8")

2. Rewrite the code in the springMVC configuration file with the org.springframework.web.servlet.view.InternalResourceViewResolver class.

After reading this article, I believe you have a certain understanding of "how to use Springmvc to complete the Ajax function". If you want to know more about it, welcome to pay attention to the industry information channel. Thank you for reading!

Tags: Objects characters strings methods functions articles random codes codes finished documents more knowledge coding industry information information channels channels Zhongtong Hualong Chinese characters Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Huawei Shulou Technology vpn Docker