Object处理方法的返回值
创建一个User实体类,并在其中写上属性值,并将其进行封装:
public class User { private String name; private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
首先创建一个包,并在该包中创建一个类,并写上返回值为Object的方法
@Controller public class Firstconobjectreturn { @RequestMapping("/ent") @ResponseBody //响应体 public Object doFirst(){ return 1; } //处理器返回值 Map @RequestMapping(value = "/pent",produces = "text/html;charset=utf-8") //解决乱码 @ResponseBody public Object doSecond(){ Map<String,User> map=new HashMap<String, User>(); User info=new User(); info.setName("赵天宇"); info.setAge(20); User us=new User(); info.setName("毛不易"); us.setAge(22); map.put(info.getName(),info); map.put(us.getName(),us); return map; } //处理器返回值 List @RequestMapping(value = "/lit") @ResponseBody public Object doList(){ List<User> list=new ArrayList<User>(); User info=new User(); info.setName("孟子坤"); info.setAge(17); return list; } @RequestMapping("/yun") @ResponseBody public Object dopecond(){ User info=new User(); info.setName("啦啦"); info.setAge(23); return info; } }
在xml中必须要加上<mvc:annotation-drivern/>
<context:component-scan base-package="cn.happy.conobject"></context:component-scan> <mvc:annotation-driven/>
创建一个jsp页面,并在该页面中写上如下代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jQuery1.11.1.js"></script> <script type="text/javascript"> $(function () { $("#tn").click(function () { $.ajax({ url:"${pageContext.request.contextPath}/pent", success:function (data) { //data指的是从server打印到浏览器的数据 $.each(data,function (i,dom) { alert(dom.name); }) /* alert(data);*/ } }); }); }); </script> </head> <body> <h3>ResponseBody</h3> <input type="button" id="tn" value="Ajax"/> </body> </html>
------------------------SpringMVC核心技术 转发,重定向---------------------------
重定向:不能携带数据
转发:携带数据
@Controller public class twocontroller { //SpringMVC 转发 @RequestMapping("/addUser") //转发视图 public String addRealUser(){ return "/WEB-INF/insert.jsp"; } @RequestMapping("/listUser") public String lidtUder(HttpServletRequest request){ //转发处理器 request.setAttribute("happy","goodgril"); return "addUser"; } //------------------------重定向----------------------- @RequestMapping("/addent") public String alist(){ return "redirect:/list.jsp"; } @RequestMapping("/addlist") public String addli(HttpServletRequest request){ request.setAttribute("happy","goodgril"); return "redirect:/addent"; } //------------------------异常------------------------------ @RequestMapping("/err") public String doErr(){ int i=5/0; return "/WEB-INF/list.jsp"; } }
xml配置中的异常操作如下:
<!--注册系统异常处理器--> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="defaultErrorView" value="errer.jsp"></property> </bean>