SpringMVC07处理器方法的返回值

 <body>
  <!--返回值是string的内部视图  -->
   <a href="student/add">add</a>
   
  <!--返回值是string的外部视图  -->
   <a href="student/taobao">淘宝</a>
   
  <!--没有返回值  转发到内部视图  -->
   <a href="student/request">request</a>
  <!--没有返回值  重定向到内部视图  -->
   <a href="student/response">response</a>
  </body>
<?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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd">
  <!-- 配置springmvc的组件  -->
  <context:component-scan base-package="cn.bdqn.controller"/>
  
  
  <!--  视图解析器      后台返回的是  success!  应该拿到的是  /WEB-INF/jsp/success.jsp 
  <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
     <property name="prefix" value="/WEB-INF/jsp/"/>
     <property name="suffix" value=".jsp"/>
  </bean> 
  -->
  
  <!--  配置外部视图解析器   就不需要  视图解析器了! -->
  <bean  class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
  
  <!-- 外部视图 -->
  <bean id="taobao" class="org.springframework.web.servlet.view.RedirectView">
    <property name="url" value="http://www.taobao.com"/>
  </bean>
</beans>
@Controller
@RequestMapping("/student")
public class StudentController {
    
    /**
     * 返回值是string的内部视图  
     */
    @RequestMapping("/add")
    public  String  add(){
        System.out.println("进入了add");
        return  "success";
    }
    
    /**
     * 返回值是string的外部视图 
     */
    @RequestMapping("/taobao")
    public  String  taobao(){
        System.out.println("进入了taobao");
        return  "taobao";
    }
    /**
     * 没有返回值  转发到内部视图
     */
    @RequestMapping("/request")
    public  void  request(HttpServletRequest request,HttpServletResponse response){
        System.out.println("进入了request");
        //转发
        try {
            request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 没有返回值  重定向到内部视图
     */
    @RequestMapping("/response")
    public  void  response(HttpServletRequest request,HttpServletResponse response){
        System.out.println("进入了response");
        //重定向
        try {
            /**
             * 重定向是  客户端的  行为!
             * 能直接访问 web-inf ???  不行!
             * response.sendRedirect("WEB-INF/jsp/success.jsp");
             * 重定向到另一个方法 然后 那个方法做跳转!
             * 
             */
            response.sendRedirect("success.jsp");  //前提是根目录下有 success.jsp
            
            /**
             * 这时候的路径http://localhost:8080/springmvc08/student/success.jsp
             * 为什么会有student/这一层目录
             * 原因:
             *    用户点击的是 student/response
             *    系统会默认拿到student/ 当成目前的路径!
             *    再做重定向的时候会默认加上student/
             */
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  <body>
  <!-- 在controller中  实现 方法之间的跳转  -->
     <form action="student/changeMethod"  method="post">
     学生姓名:<input type="text" name="name"/>
    年龄:  <input type="password" name="age"/>
      <input type="submit" value="新增"/>
   </form> 
  </body>
<?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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd">
  <!-- 配置springmvc的组件  -->
  <context:component-scan base-package="cn.bdqn.controller"/>
  
  
  <!--  视图解析器      后台返回的是  success!  应该拿到的是  /WEB-INF/jsp/success.jsp -->
  <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
     <property name="prefix" value="/WEB-INF/jsp/"/>
     <property name="suffix" value=".jsp"/>
  </bean> 
  
  
</beans>
@Controller
@RequestMapping("/student")
public class StudentController {
    
    /**
     * 转发是默认的格式
     * 01.看路径
     * 02.看数据是否传递
     */
    @RequestMapping("/addRequest")
    public  ModelAndView  addRequest(Student student){
        System.out.println("进入了addRequest");
       ModelAndView  mv=new ModelAndView();
        mv.addObject("student", student).setViewName("success");
        return  mv;
    }
    
    /**
     * 重定向
     * 01.客户端行为 不能访问WEB-INF
     * 02.以访问的路径为准,所以上个例子中的student/  会出现!
     * 03.如果使用重定向 不加/  就是以上次访问的路径为准
     *    如果加上了/    就是以项目的跟路径为准
     */
    @RequestMapping("/addResponse")
    public  ModelAndView  addResponse(Student student){
        System.out.println("进入了addResponse");
        ModelAndView  mv=new ModelAndView();
        //需要在 webroot下 创建  success.jsp
        mv.addObject("student", student).setViewName("redirect:/success.jsp");
        return  mv;
    }
    /**
     * 跳转到内部方法
     */
    @RequestMapping("/changeMethod")
    public  String  changeMethod(Student student){
        System.out.println("进入了changeMethod");
        ModelAndView  mv=new ModelAndView();
        mv.addObject("student", student);
        //return  "redirect:list";   重定向 不能使用  /  跳转到当前controller中的list方法 ! 数据丢失
        return  "forward:list";//  转发list方法   数据肯定保留
    }
    
    @RequestMapping("/list")
    public  String  list(Student student){
        System.out.println("进入了list");  
        System.out.println(student.getName());
        System.out.println(student.getAge());
        return  "success";
    }
    
}

==================接收并返回json数据======================

需要导入jquery和 Gson的jar包

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    
    
  <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
    <script type="text/javascript">
      $(function(){
       $("button").click(function(){ //按钮的点击事件
           $.ajax({
                url:"user/doAjax",
                data:{
                 name:"小黑",
                 age:50
                },
                success:function(data){
                /*  01.在前台转换成json数据
                var json=eval("("+data+")");
                alert(json.name+ "       "+json.age);  */
                /*
                02.在后台设置response.setContentType("application/json");
                  */
                alert(data.name+ "       "+data.age); 
                }
           })
       })
      
      })
     
    
    </script>
  </head>
  <body>
  <button>提交ajax请求</button>
  </body>
</html>
index.jsp页面
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">


<!-- 配置需要扫描的包 -->
<context:component-scan base-package="cn.bdqn.controller"/>
<!-- 允许静态资源的访问  -->
<mvc:resources location="/js/" mapping="/js/**"/>
<!-- 开启注解 -->
<mvc:annotation-driven/>
<!-- 
之前的
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>
 -->
</beans>
springmvc-servlet.xml文件
@Controller
@RequestMapping("/user")
public class MyController {

    @RequestMapping("doAjax")
    public void doAjax(String name, int age, HttpServletResponse response)
            throws IOException {
        System.out.println("进入了doAjax......");
        System.out.println(name);
        System.out.println(age);
        // 放入map集合
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", name);
        map.put("age", age);

        // response.setHeader("Content-type", "text/html;charset=utf-8");
        response.setContentType("application/json"); // 设置返回的是json页面
        Gson gson = new Gson();
        String json = gson.toJson(map);
        System.out.println("json=====" + json);
        // 把json数据返回给界面
        PrintWriter writer = response.getWriter();
        writer.print(json);
    }
}
Controller中的代码

=================ajax验证用户名是否存在====================

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'success.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
    <script type="text/javascript">
      $(function(){
      //验证用户名是否存在
       $("#userName").blur(function(){ //按钮的点击事件
       var name= $("#userName").val();
           $.ajax({
                url:"user/addUser",
                type:"post",
                data:"userName="+name,
                success:function(data){
                    alert(data);
                }
           })
       })
      
      })
     
    
    </script>
  </head>
  
  <body>
  <h1>json验证</h1>
  
  用户名:<input type="text" id="userName" name="userName">
  </body>
</html>
创建一个对应的login.jsp
/**
     * 用户名验证 ajax
     */
    @RequestMapping("/addUser")
    public void doAjax(String name, HttpServletResponse response)
            throws IOException {
        System.out.println("进入了addUser......");
        System.out.println(name);
        boolean flag = false;
        if (name.equals("admin")) {
            flag = true;
        }
        response.setContentType("application/json"); // 设置返回的是json页面
        Gson gson = new Gson();
        String json = gson.toJson(flag);
        System.out.println("json=====" + json);
        // 把json数据返回给界面
        PrintWriter writer = response.getWriter();
        writer.write(json);
    }
在Controller中增加代码

==================处理器返回Object对象=====================

导入需要的Jackson   jar包 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    
    
  <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
    <script type="text/javascript">
      $(function(){
       $("button").click(function(){ //按钮的点击事件
           $.ajax({
                url:"user/doAjax",
                success:function(data){
                // alert(data) 返回单个数据 使用
                // alert(data.name+"   "+data.age);返回一个对象使用
                //alert(data.user1.name+"   "+data.user2.name);  返回一个map集合
                
                $(data).each(function(i){
                   alert(data[i].name+"  "+data[i].age);  //返回一个list集合
                })
                }
           })
       })
      
      })
     
    
    </script>
  </head>
  <body>
  <button>提交ajax请求</button>
  </body>
</html>
index.jsp页面
package cn.bdqn.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.bdqn.bean.User;

@Controller
@RequestMapping("/user")
public class MyController {

    /**
     * 01.返回的是一个Object对象
     * @return
     */
    /**    @RequestMapping("/doAjax")
        @ResponseBody
        // 把我们的返回的数据 放在相应体中
        public Object doAjax() {
            System.out.println("进入了doAjax......");
            return 45454.2515;
        }*/

    /**
     * 02.返回的是一个Object对象
     * produces :响应的界面格式
     */
    /**@RequestMapping(value = "/doAjax", produces = "text/html;charset=utf-8")
    @ResponseBody
    // 把我们的返回的数据 放在相应体中
    public Object doAjax() {
        System.out.println("进入了doAjax......");
        return "大家辛苦了";
    }*/

    /**
     * 03.返回的是一个Object对象
     */
    /**@RequestMapping(value = "/doAjax")
    @ResponseBody
    // 把我们的返回的数据 放在相应体中
    public Object doAjax() {
        System.out.println("进入了doAjax......");
        return new User("小黑", 50);
    }*/
    /**
     * 04.返回的是一个Map集合
     */
    /**@RequestMapping(value = "/doAjax")
    @ResponseBody
    // 把我们的返回的数据 放在相应体中
    public Object doAjax() {
        System.out.println("进入了doAjax......");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("user1", new User("小黑1", 50));
        map.put("user2", new User("小黑2", 50));
        return map;
    }*/

    /**
     * 05.返回的是一个list集合
     */
    @RequestMapping(value = "/doAjax")
    @ResponseBody
    // 把我们的返回的数据 放在相应体中
    public Object doAjax() {
        System.out.println("进入了doAjax......");
        List<User> list = new ArrayList<User>();
        list.add(new User("小黑1", 50));
        list.add(new User("小黑2", 60));
        return list;
    }

}
Controller代码
原文地址:https://www.cnblogs.com/999-/p/6139877.html