使用@Controller
注解的处理器的处理器方法,其返回值常用的有四种类型:
1. ModelAndView
2. String
3. 返回自定义类型对象
4. 无返回值 void
1.返回值是ModelAndView
使用此返回值的情况
1.前后端不分的开发,大部分情况下,我们返回 ModelAndView
2.既有数据的携带还有资源的跳转,可以选择该种方式
使用此返回类型要配置视图解析器 在springMVC的配置文件中配置
<!--视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
@RequestMapping("test01")
public ModelAndView test01(){
ModelAndView mv=new ModelAndView();//模型与视图
//携带数据
//相当于request.setAttribute("teamName","湖人队“);
mv.addObject("teamName","湖人队");
// 经过视图解析器InternalResourceViewResolver的处
理,将逻辑视图名称加上前后缀变为物理资源路径 /jsp/result.jsp
mv.setViewName("result");
return mv;
}
前端页面 使用EL表达式获取存储的teamName
<h1> test01----${teamName} </h1>
2.返回String
使用此返回值的情况
同样使用此返回类型要配置视图解析器 在springMVC的配置文件中配置
1.只需要返回跳转的页面不需要数据的存储
2.同时返回跳转的页面和存储在作用域的值供前端获取
此情况返回值需要配合 HttpServletRequest对象使用
@RequestMapping("test02")
public String test02(HttpServletRequest request){
Team team=new Team();
team.setLocation("迈阿密");
team.setTeamId(1002);
team.setTeamName("热火");
//携带数据
request.setAttribute("team",team);
request.getSession().setAttribute("team",team);
//资源的跳转
return "result";// 经过视图解析器InternalResourceViewResolver的处理,将逻辑视
图名称加上前后缀变为物理资源路径 /jsp/result.jsp
}
前端页面
<h1>test02---request作用域获取:---${requestScope.team.teamName}--
-${requestScope.team.teamId}---${requestScope.team.location}</h1>
<h1>test02---session作用域获取:---${sessionScope.team.teamName}--
-${sessionScope.team.teamId}---${sessionScope.team.location}</h1>
3.返回对象类型
使用此返回值的情况
当处理器方法返回Object对象类型的时候,可以是Integer、String、Map、List,也可以是自定义的对 象类型。但是无论是什么类型,都不是作为逻辑视图出现,而是直接作为数据返回然后展示的。
一般前 端发起Ajax请求的时候都会使用直接返回对象的形式。 返回对象的时候,需要使用@ResponseBody 注解,将转换后的 JSON 数据放入到响应体中。
pom.xml文件中添加两个依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
1.返回基础类型
使用情况:前端需要获取信息是的基础类型
需要配合@ResponseBody 注解使用 作用就是 不再走视图解析器 而且将返回的数据类型转换成json格式,以便于前端接收数据。
1.Integer类型
@ResponseBody
@RequestMapping("test03-1")
public Integer test031(){
return 666;
}
2.String类型
@ResponseBody
@RequestMapping("test03-2")
public String test032(){
return "test";
}
3.返回List数组
@ResponseBody
@RequestMapping("test03-3")
public List<String> test033(){
List<String> list =new ArrayList<>();
list.add("热火");
list.add("篮网");
list.add("勇士");
return list;
}
4.返回map集合
@ResponseBody
@RequestMapping("test03-4")
public Map<String,String> test034(){
Map<String,String> map = new HashMap<>();
map.put("1","迈阿密");
map.put("2","纽约");
map.put("3","金州");
return map;
}
2.返回自定义对象类型
1.返回单个对象类型
先创建一个自定义的Team 属性 有 location teamId teamName
@ResponseBody
@RequestMapping("test03-5")
public Team test035(){
Team team=new Team();
team.setLocation("迈阿密");
team.setTeamId(1002);
team.setTeamName("热火");
return team;
}
前端ajax进行数据获取
<div>
<button type="button" id="btn1">ajax请求自定义对象</button>
<h3>ajax请求自定义对象的结果展示</h3>
<p id="res1"></p>
</div>
<script>
$(function(){
$("#btn1").click(function () {
$.ajax({
type: "POST",
url: "/result/test03-5",
data: "",
success: function(msg){
alert( "Data Saved: " + msg );
var name=msg.teamName;
var id=msg.teamId;
var loc=msg.location;
$("#res1").html("name:"+name+",id:"+id+",location:"+loc);
}
});
});
</script>
2.返回集合List LIst<Team>
@ResponseBody
@RequestMapping("test03-6")
public List<Team> test036(){
List<Team> list=new ArrayList<>(5);
for(int i=1;i<=5;i++) {
Team team = new Team();
team.setLocation("迈阿密"+i);
team.setTeamId(1002+i);
team.setTeamName("热火"+i);
list.add(team);
}
return list;
}
前端页面获取
<div>
<button type="button" id="btn2">ajax请求自定义对象</button>
<h3>ajax请求自定义对象的结果展示</h3>
<p id="res2"></p>
</div>
<script>
$(function(){
$("#btn2").click(function () {
$.ajax({
type: "POST",
url: "/result/test03-6",
data: "",
success: function(list){
alert( "Data Saved: " + list );
var str="";
for(var i=0;i<list.length;i++){
var obj=list[i];
str+="name:"+obj.teamName+",id:"+obj.teamId+",location:"+obj.location+"<br/>";
}
$("#res2").html(str);
}
});
});
});
</script>
结果展示
3.返回集合Map
@ResponseBody
@RequestMapping("test03-7")
public Map<String,Team> test037(){
Map<String,Team> map=new HashMap();
for(int i=1;i<=5;i++) {
Team team = new Team();
team.setLocation("金州"+i);
team.setTeamId(1000+i);
team.setTeamName("勇士"+i);
//日期类型,在返回的时候是个数字,如果想要按日期格式展示需要在实体类对应属性添加注解
//@JsonFormat(pattern = "yyyy-MM-dd")
team.setCreateTime(new Date());
map.put(team.getTeamId()+"",team);
}
return map;
}
前端页面获取
<div>
<button type="button" id="btn3">ajax请求Map</button>
<h3>ajax请求Map的结果展示</h3>
<p id="res3"></p>
</div>
<script>
$(function(){
$("#btn3").click(function () {
$.ajax({
type: "POST",
url: "/result/test03-7",
data: "",
success: function(map){
alert( "Data Saved: " + map );
var str="";
$.each(map,function (i,obj) {
str+="name:"+obj.teamName+",id:"+obj.teamId+",location:"+obj.location+"<br/>";
});
$("#res3").html(str);
}
});
});
</script>
结果展示
4.无返回值 void-了解
使用情况:直接进行页面的跳转,或者存储对象在作用域中方便前端获取。
方法的返回值为 void,并不一定真的没有返回值,我们可以通过其他方式给前端返回。实际上,这种方 式也可以理解为 Servlet 中的的处理方案,简单讲就是页面跳转。
转发:request.getRequestDispatcher("页面路径").forward(request,response);
重定向:response.sendRedirect("页面路径");
使用servlet方式的转发和重定向是不会走路径视图解析器的
转发和重定向的区别:
1.转发url里面的地址栏是不会改变的,重定向会改变 展示结果页面的路径。
2.转发需要 一次请求一次响应 ,重定向需要两次请求两次响应 ,重定向后request作用域的值会丢失,session作用域和application不会丢失。
也就是重定向两次请求不共享数据,转发一次请求共享数据(requset作用域)
3.调用两个方法的对象不同,转发使用HttpServletRequest,重定向使用HttpServletResponse
//通过 HttpServletRequest 做服务端跳转
@RequestMapping("test04-1")
public void test041(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
System.out.println("直接使用HttpServletRequest进行服务器端的转发");
request.getRequestDispatcher("/jsp/ok.jsp").forward(request,response);
}
//通过 HttpServletResponse 做重定向
@RequestMapping("test04-2")
public void test042(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
System.out.println("直接使用HttpServletResponse重定向跳转");
response.sendRedirect("/jsp/ok.jsp");
}
//通过 HttpServletResponse 给出响应
@RequestMapping("test04-3")
public void test043(HttpServletResponse response) throws ServletException,
IOException {
response.setCharacterEncoding("UTF-8");
//浏览器解析方式
response.setContentType("text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();
//会直接在页面中显示 请求路径requert/test04-3
writer.write("返回void类型测试---直接返回字符串");
writer.flush();
writer.close();
}
//也可以自己手动指定响应头去实现重定向:
@RequestMapping("test04-4")
public void test044(HttpServletResponse response) throws ServletException,
IOException {
response.setStatus(302);//设置响应码,302表示重定向
response.setHeader("Location","/jsp/ok.jsp");
}
5.日期类型的转换
前端传来的数据格式字符串类型,后端接受为日期Date需要转换
@DateTimeFormat(pattern = "yyyy-MM-dd hh-mm-ss")
放在接受的属性类的日期参数上
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
在返回的时候是个数字(1970年到现在的时间单位为秒),如果想要按日期格式展示需要在实体类对应属性添加注解
@JsonFormat(pattern = "yyyy-MM-dd")
需要引入依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
如果是java内部的日期格式的转换,使date类型的日期输出标准化
//下面的格式最为常用的
SimpleDateFormat sdf = newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str1 = sdf.format(date);
System.out.println(str1);