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 ...
随机推荐
- 【USACO 1.2.4】回文平方数
[题目描述] 回文数是指从左向右念和从右向左念都一样的数.如12321就是一个典型的回文数. 给定一个进制B(2<=B<=20,由十进制表示),输出所有的大于等于1小于等于300(十进制下 ...
- Hibernate的CRUD
1.CRUD: C:sesion.save() R:session.get()? session.load() D:session.delete() U:session.update() 2.读取数据 ...
- windows下apache配置ssl(https)服务器
SSl是为Http传输提供安全的协议,通过证书认证来确保客户端和网站服务器之间的数据是安全, 可以通过apache自带的openssl进行配置: 步骤如下: 1.安装有openssl模板的apache ...
- copy(source,destination)拷贝文件
source 必须 规定要复制的文件 destination 复制文件的目的地 说明 :将文件从 source 拷贝到 destination.如果成功则返回 TRUE,否则返回 FALSE. 例如: ...
- C语言基础文件读写操作
整理了一份C语言的文件读写件操作代码,测试时打开相应的注释即可. #include <stdio.h> #include <stdlib.h> #include <uni ...
- Oracle 游标使用全解(转)
转自:http://www.cnblogs.com/sc-xx/archive/2011/12/03/2275084.html 这个文档几乎包含了oracle游标使用的方方面面,全部通过了测试 -- ...
- PHP之路——MySql查询语句
1,select查询的基本结构 select 字段 from 表 where 过滤条件 group by 分组条件 having 过滤的第二条件 order by 排序条件 limit 限定结果条件; ...
- angular2 学习笔记 ( Component 组件)
refer : https://angular.cn/docs/ts/latest/guide/template-syntax.html https://angular.cn/docs/ts/late ...
- cf C. Divisible by Seven
http://codeforces.com/contest/376/problem/C 题意:给你一个大数最多含有10^6个数字,这里面必须含有1,6,8,9,然后重新排列找出一个能被6整除的数. 思 ...
- poj Building a Space Station
http://poj.org/problem?id=2031 #include<cstdio> #include<cstring> #include<cmath> ...