Spring全家桶之springMVC(四)
路径变量PathVariable
PathVariable
Controller除了可以接收表单提交的数据之外,还可以获取url中携带的变量,即路径变量,此时需要使用@PathVariable注解来设置,其中包含下面几个属性。
- value:指定请求参数的名称,即url中的值,当url中的名称和方法参数名称不一致时,可以使用该属性解决。
- name:同value,两者只能使用一个
- required:指定该参数是否是必须传入的,boolean类型。若为 true,则表示请求中所携带的参数中必须包含当前参数。若为 false,则表示有没有均可。
 
创建Controller,注意@RequestMapping注解中的写法
package controller; import bean.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; @Controller
public class RegistController03 { @RequestMapping("/{username}/{age}/regist.do")
public ModelAndView regist(@PathVariable("username") String name,@PathVariable int age) throws Exception{ ModelAndView mv = new ModelAndView();
mv.addObject("name", name);
mv.addObject("age", age);
mv.setViewName("result");
return mv;
}
}
之后,在浏览器的地址栏里面直接输入:
localhost:/jack//regist.do
此时可以直接获取url中的jack和19的值。
这种方式在restful风格的url中使用较多。
Controller中方法的返回值(上)
Controller中方法的返回值类型
在我们之前写的Controller的方法中,返回值都写的是ModelAndView,其实还可以返回其他类型的对象,在实际应用中需要根据不同的情况来使用不同的返回值:
- ModelAndView
- String
- void
- 自定义类型
 
返回ModelAndView(跳转页面以及传递参数)
    先来看下ModelAndView,这个是我们之前一直使用的返回值,如果Controller的方法执行完毕后,需要跳转到jsp或其他资源,且又要传递数据, 此时方法返回ModelAndView比较方便。
如果只传递数据,或者只跳转jsp或其他资源的话,使用ModelAndView就显得有些多余了   
返回String类型(跳转页面)
如果controller中的方法在执行完毕后,需要跳转到jsp或者其他资源上,此时就可以让该方法返回String类型,返回String类型多用于只跳转页面而不传递参数的情况下(restful风格也使用String类型)。
String类型返回内部资源
1、创建一个Controller,方法返回String类型:
package controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; /**
* 方法返回String类型
*/
@Controller
public class ReturnStringController01 { @RequestMapping("/welcome.do")
public String welcome() throws Exception{
//直接填写要跳转的jsp的名称
return "welcome";
}
}
springmvc.xml中设置的视图解析器为jsp,所以这里跳转的全路径为/jsp/welcome.jsp
2、编写welcome.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body> 欢迎你学习java!
</body>
</html>
3、在浏览器的地址栏中输入:
localhost:/welcome.do
String类型返回外部资源
如果你需要在controller的方法中跳转到外部资源,比如跳转到www.baidu.com:
此时需要在springmvc.xml文件中配置一个BeanNameViewResolver类,这个类被称作是视图解析器。在springmvc.xml文件中添加下面内容:
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<!--定义外部资源view对象-->
<bean id="returnString" class="org.springframework.web.servlet.view.RedirectView">
<property name="url" value="http://www.baidu.com/"/>
</bean>
其中id是controller中的方法返回值,value是要跳转的外部资源的地址。
之后修改controller中的方法返回值:
@RequestMapping("/welcome.do")
public String welcome() throws Exception{
    //直接填写要跳转的jsp的名称
    return "returnString";
}
此时在浏览器中输入:
localhost:/welcome.do
然后页面就会跳转到你指定的外部资源了。
Model对象
之前简单说过这个Model,它是一个接口,写在controller的方法中的时候,spring mvc会为其进行赋值。我们可以使用Model对象来传递数据,也就是说我们可以使用Model传递数据并且将方法返回值设置为String类型,通过这种方式实现与方法返回ModelAndView一样的功能。
@RequestMapping("/welcome1.do")
public String welcome1(String name,Model model) throws Exception{
    //这种写法spring mvc会自动为传入的参数取名
    //model.addAttribute(name);
    model.addAttribute("username", name);
    //直接填写要跳转的jsp的名称
    return "welcome";
}
在welcome.jsp中添加下面内容:
${username}<br>
${string}<br>
从浏览器的url中输入:
http://localhost:8080/welcome1.do?name=jack
可以看到页面中会显示两个jack
上面controller中使用了下面的写法:
model.addAttribute(name);
这种写法spring mvc会根据传入的参数对其进行取名,此时传入的参数name是一个String类型,因此会给他取名为string,即类似如下写法:
model.addAttribute("string", name);
这里面spring mvc的取名方式就是根据传入参数的类型来取名的,例如:
传入Product类型,会将其命名为"product"
MyProduct 命名为 "myProduct"
UKProduct 命名为 "UKProduct"
另外在Model接口中还有两个方法:
- addAllAttributes(Collection<?> attributeValues);
 会将传入的list中的数据对其进行命名,例如:
 
- addAllAttributes(Collection<?> attributeValues);
List<Integer> integerList = new ArrayList<>();
integerList.add();
integerList.add();
integerList.add();
model.addAllAttributes(integerList);
上面代码相当于:
model.addAttribute("", );
model.addAttribute("", );
model.addAttribute("", );
- addAllAttributes(Map<string, ?=""> attributes);
会将map中的key作为名字,value作为值放入到model对象中,例如:
Map<String, Integer> integerMap = new HashMap<>();
integerMap.put("first", );
integerMap.put("second", );
integerMap.put("third", );
model.addAllAttributes(integerMap);
上面代码相当于:
model.addAttribute("first", );
model.addAttribute("second", );
model.addAttribute("third", );
Controller中方法的返回值(下)
返回void
如果你不用spring mvc帮你完成资源的跳转,此时可以将controller中的方法返回值设置为void。一般情况下有下面两个应用场景:
- 通过原始的servlet来实现跳转
- ajax响应
 
先来看第一个,使用servlet来实现跳转,spring mvc底层就是servlet,因此我们可以在controller中使用servlet中的方法来实现页面的跳转,参数的传递。\
package controller; import bean.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; @Controller
public class controllerTest {
@RequestMapping("/welcome2.do")
public void welcome2(HttpServletRequest request, HttpServletResponse response, Student student) throws ServletException, IOException {
request.setAttribute("student", student);
//因为使用servlet中的api,所以视图解析就不能使用了
request.getRequestDispatcher("/jsp/welcome.jsp").forward(request,response);
}
}
上面的写法跟之前在servlet中是一样的。
再来看下ajax响应,这块来使用下jQuery,先下载jQuery:
http://jquery.com/download/
拷贝到项目中webapp/js目录中,然后编写ajaxRequest.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Title</title>
<script src="/js/jquery-3.3.1.js"></script>
</head>
<body>
<button id="ajaxRequest">提交</button>
</body>
<script>
$(function () {
$("#ajaxRequest").click(function () {
$.ajax({
method:"post",
url:"/ajaxRequest.do",
data:{name:"monkey",age:18},
dataType:"json",
success:function (result) {
alert(result.name + "," + result.age);
}
});
});
}); </script>
</html>
创建Controller,这里使用了fastjson,所以需要将fastjson的jar包导入到项目中:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
在Controller中添加下面方法
@RequestMapping("/ajaxRequest.do")
public void ajaxRequest(HttpServletRequest request, HttpServletResponse response, Student student) throws Exception{
    PrintWriter out = response.getWriter();
    String jsonString = JSON.toJSONString(student);
    out.write(jsonString);
}
返回Object类型
倘若需要controller中的方法返回Object类型,需要先配置下面内容:
1、添加jackson的jar包,在Spring mvc中使用了jackson来进行json数据格式的转换。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.4</version>
</dependency>
2、在springmvc.xml文件中添加注解驱动。
<mvc:annotation-driven/>
上面两个配置缺一不可。
    Object类型返回String字符串
    3、之前在controller方法中返回字符串,spring mvc会根据那个字符串跳转到相应的jsp中。这里返回的字符串会添加到响应体中传递到jsp页面中,此时需要在方法上添加一个注解@ResponseBody即可。运行程序可能会出现乱码,所以在RequestMapping中使用@produces注解
package controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; /**
* 方法返回Object类型
*/
@Controller
public class ReturnObjectController01 {
@RequestMapping(value = "/returnObject.do", produces = "text/html;charset=utf-8")
@ResponseBody
public Object welcome4(){
return "This is Object!";
}
}
4、在jsp中发送ajax请求:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="/js/jquery-3.3.1.js"></script>
</head>
<body>
<button id="ajaxRequest">提交</button>
</body>
<script>
$(function () {
$("#ajaxRequest").click(function () {
$.ajax({
method:"post",
url:"/returnObject.do",
success:function (result) {
alert(result);
}
});
});
});
</script>
</html>
Object返回map类型
创建controller:
@Controller
public class ReturnObjectController01 { @RequestMapping(value = "/returnString.do")
@ResponseBody
public Object returnString() throws Exception{ Map<String, String> map = new HashMap<>();
map.put("hello", "你好");
map.put("world", "世界");
return map;
}
}
jsp中添加ajax:
$(function () {
       $("#ajaxRequest").click(function () {
           $.ajax({
               method:"post",
               url:"/returnString.do",
               success:function (result) {
                   alert(result.hello);
               }
           });
       });
    });
除了这些之外还可以返回其他类型:List,基本数据类型的包装类,自定义类型等,这里就不演示了。
Spring全家桶之springMVC(四)的更多相关文章
- Spring全家桶之springMVC(一)
		Spring MVC简介和第一个spring MVC程序 Spring MVC是目前企业中使用较多的一个MVC框架,被很多业内人士认为是一个教科书级别的MVC表现层框架,Spring MVC是大名鼎鼎 ... 
- Spring全家桶之SpringMVC(三)
		Spring MVC单个接收表单提交的数据 单个接收表单提交的参数 在实际开发中通过会在spring MVC的Controller里面接收表单提交过来的参数,这块代码该怎么去编写呢? 示例: 编写 ... 
- Spring全家桶之springMVC(二)
		spring mvc中url-pattern的写法 1.设置url-pattern为*.do 之前我们在web.xml文件中配置DispatcherServlet的时候,将url-pattern配置为 ... 
- 10分钟详解Spring全家桶7大知识点
		Spring框架自2002年诞生以来一直备受开发者青睐,它包括SpringMVC.SpringBoot.Spring Cloud.Spring Cloud Dataflow等解决方案.有人亲切的称之为 ... 
- 一文解读Spring全家桶 (转)
		Spring框架自2002年诞生以来一直备受开发者青睐,它包括SpringMVC.SpringBoot.Spring Cloud.Spring Cloud Dataflow等解决方案.有人亲切的称之为 ... 
- 【转】Spring全家桶
		Spring框架自诞生以来一直备受开发者青睐,有人亲切的称之为:Spring 全家桶.它包括SpringMVC.SpringBoot.Spring Cloud.Spring Cloud Dataflo ... 
- Spring全家桶–SpringBoot Rest API
		Spring Boot通过提供开箱即用的默认依赖或者转换来补充Spring REST支持.在Spring Boot中编写RESTful服务与SpringMVC没有什么不同.总而言之,基于Spring ... 
- Java秋招面试复习大纲(二):Spring全家桶+MyBatis+MongDB+微服务
		前言 对于那些想面试高级 Java 岗位的同学来说,除了算法属于比较「天方夜谭」的题目外,剩下针对实际工作的题目就属于真正的本事了,热门技术的细节和难点成为了面试时主要考察的内容. 这里说「天方夜谭」 ... 
- Spring全家桶系列–SpringBoot之AOP详解
		//本文作者:cuifuan //本文将收录到菜单栏:<Spring全家桶>专栏中 面向方面编程(AOP)通过提供另一种思考程序结构的方式来补充面向对象编程(OOP). OOP中模块化的关 ... 
随机推荐
- Python 如何移除旧的版本特性,如何迎接新的特性?
			2020 年 4 月 20 日,Python 2 的最后一个版本 2.7.18 发布了,这意味着 Python 2 是真正的 EOL(end of life)了,一个时代终于落幕了. Python 2 ... 
- 开发者福利!百问I.MX6ULL裸机文档发布
			终于等到你,百问科技近600页的100ask_imx6ull裸机文档发布,已经合并到“嵌入式Linux应用开发完全手册第2版_韦东山全系列视频文档全集.pdf(1222页)”,所有人免费下载学习. 本 ... 
- TensorFlow keras dropout层
			# 建立神经网络模型 model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), # 将输入数据的形状进行修改成神经网 ... 
- synchronized 的实现原理
			加不加 synchronized 有什么区别? synchronized 作为悲观锁,锁住了什么? synchronized 代码块怎么用 前面 3 篇文章讲了 synchronized 的同步方法和 ... 
- 2019-2020-1 20199328《Linux内核原理与分析》第四周作业
			<Linux内核原理与分析>第四周作业 步骤一 首先我们指定一个内核并指定内存根文件系统,这里的bzImage是vmLinux经过gzip压缩的内核,"b"表示&quo ... 
- Visual Studio Code mac OS 安装 中文简体语言包
			先下载中文简体语言包 官网 https://marketplace.visualstudio.com/search?target=VSCode&category=Language%20Pack ... 
- JS面向对象编程之对象
			在AJAX兴起以前,很多人写JS可以说都是毫无章法可言的,基本上是想到什么就写什么,就是一个接一个的函数function,遇到重复的还得copy,如果一不小心函数重名了,还真不知道从何开始查找错误,因 ... 
- mac OS 安装 Homebrew软件包管理器
			Homebrew macOS 缺失的软件包的管理器 中文官网 https://brew.sh/index_zh-cn 获取安装命令 /usr/bin/ruby -e "$(curl -fsS ... 
- webpack打包多入口配置
			在它的entry入口设置多文件入口即可,例: entry: { core: './src/core.js', design: './src/design.js' }, 单一出口输出: output: ... 
- RMI原理揭秘之远程对象
			讨论开始之前,我们先看看网上的一个例子,这个例子我腾抄了一分,没有用链接的方式,只是为了让大家看得方便,如有侵权,我立马***. 定义远程接口: 1 2 3 4 5 6 package com.guo ... 
