学习笔记-SpringMVC(三)
1. 接收表单数据
- 准备实体类
public class Student {
private int id;
private String name;
private String address;
}
- 新建addStudent.jsp(webContext目录下)
<form action="addStudent">
姓名:<input type="text" name="name" value="">
住址:<input type="text" name="address" value="">
<input type="submit" value="增加学生信息">
</form>
- 新建控制器StudentController
控制器StudentController,准备一个add方法映射/addStudent路径
为add方法准备一个Student参数,用于接收注入
最后跳转到showStudent页面显示用户提交的数据
@Controller
public class StudentController {
@RequestMapping("/addStudent")
public ModelAndView add(Student student) throws Exception {
ModelAndView mav = new ModelAndView("showStudent");
return mav;
}
}
- 创建 showProduct.jsp(WEB-INF/page)
姓名: ${student.name}<br>
住址: ${student.address}
测试,完成。
2. 客户端跳转
修改IndexController
映射/jump到jump()方法
@RequestMapping("/jump")
public ModelAndView jump() {
ModelAndView mav=new ModelAndView("redirect:/index");
//表示客户端跳转
return mav;
}
Session
在用户登录,一些特殊场合在页面间传递数据的时候会经常用到
修改IndexController
映射 /check 到方法check()
@RequestMapping("/check")
public ModelAndView check(HttpSession session) {
Integer i = (Integer) session.getAttribute("count");
if (i == null)
i = 0;
i++;
session.setAttribute("count", i);
ModelAndView mav = new ModelAndView("check");
return mav;
}
check.jsp文件
session中记录的访问次数:${count}
中文处理:
修改web.xml
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
修改addStudent.jsp为form 设置method=”post”