1、乱码处理
在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>*.do</url-pattern>
</filter-mapping>
这样对任何*.do的请求都会过滤并将编码改为utf-8格式
2、RequestMapping分模块使用,放在类前面注解
@RequestParam(value="id",required=false) String id
@RequestParam("id") int id
这个可以把请求的参数传过来,required=false表示参数可以为空,默认是不可为空
@RequestParam("id") int id这个自动将String类型的id转化为int型
内部跳转的两种方式:
return "redirect:/student/list.do";
return "forward:/student/list.do";
form表单中提交的内容可以自动装配到这里
@Controller
//student模块
@RequestMapping("/student")
public class StudentController {
@RequestMapping("/list")
public ModelAndView list() {
ModelAndView mv=new ModelAndView();
mv.setViewName("list");
mv.addObject("students", students);
return mv;
}
@RequestMapping("/preSave")
//传递参数
public ModelAndView update(@RequestParam(value="id",required=false) String id) {
ModelAndView mv=new ModelAndView();
System.out.println("id 是:"+id);
if (id!=null) {
mv.setViewName("update");
mv.addObject("student", students.get(Integer.parseInt(id)));
}else {
mv.setViewName("add");
}
return mv;
}
@RequestMapping("/save")
//student为jsp页面提交的form表单传过来的,自动装配
public String save(Student student) {
if (student.getId()!=0) {
Student student2=students.get(student.getId());
student2.setName(student.getName());
student2.setAge(student.getAge());
}else {
students.put(student.getId(), student);
}
//内部跳转
return "redirect:/student/list.do";
// return "forward:/student/list.do";
}
@RequestMapping("/delete")
public String delete(@RequestParam("id") int id) {
students.remove(id);
return "redirect:/student/list.do";
// return "forward:/student/list.do";
}
}