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代码
SpringMVC07处理器方法的返回值的更多相关文章
- 11.SpringMVC注解式开发-处理器方法的返回值
处理器方法的返回值 使用@Controller 注解的处理器的处理器方法,其返回值常用的有四种类型 1.ModelAndView 2.String 3.void 4.自定义类型对象 1.返回Model ...
- SSM-SpringMVC-21:SpringMVC中处理器方法之返回值Object篇
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 今天要记录的是处理方法,返回值为Object的那种,我给它分了一下类: 1.返回值为Object数值(例如1) ...
- SSM-SpringMVC-20:SpringMVC中处理器方法之返回值void篇
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 处理器的方法我们之前做过,返回值为String的,返回值为ModelAndView的,我们这个讲的这个返回 ...
- SpringMVC_处理器方法的返回值
一.返回ModelAndView 若处理器方法处理完后,需要跳转到其他资源,且又要在跳转的资源间传递数据,此时处理器方法返回ModelAndView比较好.当然,若要返回ModelAndView ...
- springmvc 注解式开发 处理器方法的返回值
1.返回void -Ajax请求 后台: 前台: 返回object中的数值型: 返回object中的字符串型: 返回object中的自定义类型对象: 返回object中的list: 返回object中 ...
- Controller方法的返回值
方法的返回值1.ModelAndView这个就不多说,这是最基础的,前面定义一个ModelAndView,中途使用addObject方法添加属性,再返回.视图解析器会自动扫描到的.2.String这个 ...
- SpringMVC由浅入深day01_10@RequestMapping_11controller方法的返回值
10 @RequestMapping 10.1 Url路径映射 @RequestMapping(value="/item")或@RequestMapping("/item ...
- 一个方法中的ajax在success中renturn一个值,但是方法的返回值是undefind?
https://segmentfault.com/q/1010000003762379 A页面 console.log(handleData("search_list", &quo ...
- java中Arrays类中,binarySearch()方法的返回值问题
最近在复习Java知识,发现果然不经常使用忘得非常快... 看到binarySearch()方法的使用时,发现书上有点错误,于是就自己上机实验了一下,最后总结一下该方法的返回值. 总结:binaryS ...
随机推荐
- ES5严格模式
http://www.cnblogs.com/snandy/p/3428171.html 介绍了由ECMA262规范定义的Javascript标准,旨在改善错误检查功能并且标识不会延续到未来js版本的 ...
- mysql报Fatal error encountered during command execution的解决办法
连接字符串里加上 Allow User Variables=True 解决. 否则时不时的报错,存储过程名长一点也报错,又有时报有时不报,参数传1位数就正常2位数就报错等…… 折腾mysql蛋疼啊
- HTML5 QQ登录背景动态图片
预览效果如图所示: 代码如下: <!DOCTYPE html> <head> <meta http-equiv="Content-Type" cont ...
- python文件处理
python中对文件处理需要涉及到os模块和shutil模块得到当前工作目录路径:os.getcwd()获取指定目录下的所有文件和目录名:os.listdir(dir)删除文件:os.remove(f ...
- 堆排序(Heap Sort)的C语言实现
堆排序(Heap Sort)具体步骤为 将无序序列建成大顶堆(小顶堆):从最后一个非叶子节点开始通过堆调整HeapAdjust()变成小顶堆或大顶堆 将顶部元素与堆尾数组交换,此是末尾元素就是最大值, ...
- ARM内核和架构都是什么意思,它们到底是什么关系?
ARM产品越来越丰富,命名也越来越多.很多朋友提问: ARM内核和架构都是什么意思?内核和架构的关系是什么?比如ARMv7架构,这个架构指的是什么?小编选出了几个精彩回答!希望对嵌友们在选择设计电路时 ...
- RESTful API -备
网络应用程序,分为前端和后端两个部分.当前的发展趋势,就是前端设备层出不穷(手机.平板.桌面电脑.其他专用设备......). 因此,必须有一种统一的机制,方便不同的前端设备与后端进行通信.这导致AP ...
- 如何将github上的微信客户端类库能够通过composer工具下载
我将自己开发的微信客户端类库放到了github上面去了. 然后我在我的项目里面添加了一个composer.json文件 内容如下 { "require": { "weix ...
- 最近国外很拉风的,,基于.net 的一个手表
site:http://agentwatches.com/ 这个项目是一个国外工作室,筹集资金 创立的. 直接用c# 代码编译显示在手机上.能和智能手机通信等. 并且是开源的. 很酷 其次.它提供了. ...
- 【转】Android点击空白区域,隐藏输入法软键盘
原文网址:http://www.2cto.com/kf/201505/401382.html 很多时候,我们在使用应用时,会出现输入法软键盘弹出的问题,通常情况下,我们默认会使用户点击返回键或者下一步 ...