例1:springmvc实现Controller接口
package com.pac.springmvc.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class HelloAction implements Controller{
public HelloAction() {
System.out.println("helloAction");
}
public ModelAndView handleRequest(HttpServletRequest
arg0,HttpServletResponse arg1) throws Exception {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message","SpringMVC测试");
modelAndView.setViewName("/WEB-INF/jsp/success.jsp");
return modelAndView;
}
}
必须在web.xml中配置DispatcherServlet,可以配置springmvc的配置文件的存储位置,否则默认就是WEB-INF目录下;另外要想让jsp以及程序的编码为UTF-8,还必须配置Filter.
@SuppressWarnings("deprecation")
public class EmpAction extends AbstractCommandController{
//调用AbstractCommandController的setCommandClass方法将jsp的数据收集并封装到指定的类中
publicEmpAction(){
setCommandClass(Emp.class);
}
protected void initBinder(HttpServletRequest request,ServletRequestDataBinder
binder) throws Exception {
//向springmvc内部注入一个自定义的类型转换器
//参数一:将String转成什么类型的字节码
//参数二:自定义转换规则
//true表示该日期字段可以为空
binder.registerCustomEditor(Date.class,new CustomDateEditor(
newSimpleDateFormat("yyyy-MM-dd"),true));
}
@Override
protected ModelAndView handle(HttpServletRequest request,
HttpServletResponse response, Object obj,BindException error)throws Exception {
ModelAndView modelAndView = newModelAndView();
System.out.println(request.getParameter("date").toString());
Emp emp = (Emp) obj;
System.out.println(emp.getName()+"\n"+emp.getGender()+"\n"
+emp.getDate().toLocaleString().substring(0,10));
modelAndView.addObject("message","员工信息更新完成");
//将Emp封装到ModeAndView对象中
modelAndView.addObject("emp",emp);
modelAndView.setViewName("success");
return modelAndView;
}
}