因为以前没怎么使用过,springmvc。所以对比着struts2以前的使用经验来使用springmvc。
一。用户访问controller
仿struts2的访问,页面action或.do访问配置文件,根据struts2配置文件的name找到具体执行哪个类的哪个方法。
然后进入对应类的方法,执行相关逻辑,return。返回之后,根据返回值在配置文件中找到具体的内部跳转页面,或者具体的下一个action方法。或者页面重定向的位置。
如下流程1页面action------->2.struts2配置文件name------------->3.找到某某类的某某方法------------>4.执行某某类的某某方法-----------------------》5.回跳到struts2配置文件,并找到具体的返回位置--------》6回到页面,或者继续执行第2步,回到页面可以有内部跳转和外部跳转两种,继续第2步则是链式执行。
对于spring mvc如下代码
@Controller
@RequestMapping("/student.do")
public class StudentController {
protected final transient Log log = LogFactory
.getLog(StudentController.class);
@Autowired
private StudentService studentService;
public StudentController(){
}
@RequestMapping
public String load(ModelMap modelMap){
List<Object> list = studentService.getStudentList();
modelMap.put("list", list);
return "student";
}
@RequestMapping(params = "method=add")
public String add(HttpServletRequest request, ModelMap modelMap) throws Exception{
return "student_add";
}
@RequestMapping(params = "method=save")
public String save(HttpServletRequest request, ModelMap modelMap){
String user = request.getParameter("user");
String psw = request.getParameter("psw");
Student st = new Student();
st.setUser(user);
st.setPsw(psw);
try{
studentService.save(st);
modelMap.put("addstate", "添加成功");
}
catch(Exception e){
log.error(e.getMessage());
modelMap.put("addstate", "添加失败");
}
return "student_add";
}
}
例如我们执行 项目/student.do。会执行默认的方法,即load(ModelMap modelMap);
会根据return的值来确认,具体return到的页面
如return "student".就会跑到student.jsp
执行/student.do?method=add就会执行add方法。
所以spring根据@RequestMapping(params = "method=add")来确定具体访问的方法。
重点:public String save(HttpServletRequest request, ModelMap modelMap)
里面的参数是干嘛的呢?当然啦,一个是用户传过来的数据,一个是用户返回的数据,和系统设计一致,输入,输出。
request作为用户输入,modelmap作为输出。
二.springmvc如何做到像struts2那样链式跳转呢?
在spring mvc的controller中,从一个controller请求跳转到另一个请求有以下若干方式.
1 "redirect:/test"
2 "forward:/test"
3 ModelAndView(new RedirectView("test"))
4 直接调用bean:1)注解拿到其他controller;2)实现ApplicationContextAware接口,从context拿到其他controller
其中以上方式各有优缺点,可以根据情况酌情处理。
需要考虑的因素有
1 性能
2 耦合:1)url耦合;2)对象和方法耦合
3 规范及可维护性