SpringMVC的返回值类型有MedelAndView,String,void,Object数值型,集合类型等等
前两种我们之前写案例的时候一直在用,现在看一下返回值是void的
返回值是void的话,就要结合ajax来写
准备一个用户类
package demo09Return; /** * Created by mycom on 2018/3/26. */ public class UserInfo { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
和控制器类
package demo09Return; import com.alibaba.fastjson.JSON; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Created by mycom on 2018/3/26. */ @Controller public class ReturnController { @RequestMapping("/one") public void doFirst(HttpServletResponse response) throws IOException { List<UserInfo> list=new ArrayList<UserInfo>(); UserInfo user=new UserInfo(); user.setUsername("敖"); user.setPassword("1225"); list.add(user); String data = JSON.toJSONString(list); response.getWriter().write(data); } }
在页面上
<%-- Created by IntelliJ IDEA. User: mycom Date: 2018/3/26 Time: 17:13 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.min(1).js"></script> <script type="text/javascript"> $(function () { $("input").click(function () { $.ajax({ url:"/one", type:"POST", success:function (data) { $.each(eval("("+data+")"),function (i,dom) { alert(dom.username); }) } }) }) }) </script> <head> <title>Title</title> </head> <body> <input type="button" value="按钮"> </body> </html>
在配置文件中
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="demo09Return"></context:component-scan> <!--视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
注意不要忘记修改web.xml中的classpath的值