前言:
本文属于上篇文章的补充。
正文:
一、传递参数不再是简单String字符串,而是一个对象,例如一个课程的详细资料为一个对象Course。
写一个对象Course。
package model;
public class Course {
/**
* 课程名称:<input type="text" name="title"/><br>
课程时长:<input type="text" name="duration"/><br>
课程难度:<input type="text" name="level"/><br>
课程介绍:<input type="text" name="descr"/><br>
* */
private String title;
private String duration;
private String level;
private String descr;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getDescr() {
return descr;
}
public void setDescr(String descr) {
this.descr = descr;
}
@Override
public String toString() {
return "Course [title=" + title + ", duration=" + duration + ", level=" + level + ", descr=" + descr + "]";
}
}
二、Model,ModelAndView,ModelMap,Map随便使用,都差不多。
1、写一个Controller(/loginp)直接跳转到详情页。
@RequestMapping(value="/loginp",method=RequestMethod.GET)
public String getCourse() {
return "login";
}
2、通过login.jsp提交表单。action请求为请求的上下文路径+/save
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="<%=request.getContextPath()%>/save" method="post">
课程名称:<input type="text" name="title"/><br>
课程时长:<input type="text" name="duration"/><br>
课程难度:<input type="text" name="level"/><br>
课程介绍:<input type="text" name="descr"/><br>
<input type="submit" value="提交">
</form>
</body>
</html>
3、写一个Controller,此处通过Model,(也可以通过Map<String,Object> model替代或者ModelMap替代)添加到属性course。这个course在后面jsp页面中会用到。
//重定向:"redirect:/loginp"回到上面的loginp请求
//不用重定向:直接成功jsp页面
@RequestMapping(value="/save",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
public String saveCourse(Course course,Model model) {
log.error(ReflectionToStringBuilder.toString(course));
// model.put("course",ReflectionToStringBuilder.toString(course));
model.addAttribute("course", ReflectionToStringBuilder.toString(course));
return "success";
}
PS:如果像下面这样子的完整Course对象展示,可以通过@ModelAttribute也可:
@RequestMapping(value="/save2",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
public String saveCourse2(@ModelAttribute Course course) {
log.error("-----"+ReflectionToStringBuilder.toString(course));
return "success";
}
4、成功展示页面很简单。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>${course}</h1>
</body>
</html>