异步发送表单数据到JavaBean,并响应JSON文本返回
1) 提交表单后,将JavaBean信息以JSON文本形式返回到浏览器
<form> 编号:<input type="text" name="id" value="1"/><br/> 姓名:<input type="text" name="name" value="哈哈"/><br/> 薪水:<input type="text" name="sal" value="5000"/><br/> <input type="button" value="异步提交注册"/> </form> <script type="text/javascript"> $(":button").click(function(){ var url = "${pageContext.request.contextPath}/user/add.action"; var sendData = { "id":1, "name":"哈哈", "sal":5000 }; $.post(url,sendData,function(backData,textStatus,ajax){ alert(ajax.responseText); }); }); </script>
public class User { private Integer id; private String name; private Double sal; public User(){} public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getSal() { return sal; } public void setSal(Double sal) { this.sal = sal; } }
@Controller @RequestMapping(value="/user") public class UserAction { @RequestMapping(value="/add") public @ResponseBody User add(User user) throws Exception{ System.out.println(user.getId()+":"+user.getName()+":"+user.getSal()); return user; } }
spring.xml
<!-- Action控制器 --> <context:component-scan base-package="loaderman.javaee.springmvc.app25"/> <!-- 配适器 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> </list> </property> </bean>
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!