controller配置總結(jié)
使用注解
1.web.xml配置
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc.xml</param-value>
</init-param>
2.Controller修改
類(lèi)聲明前加@Controller
相應(yīng)方法前加@RequestMapping("/請(qǐng)求名")
3.spring配置文件修改
<!-- 掃描該包下的注解-->
<context:component-scan base-package="包名"/>
使用nameurlhandlermapping和handleradapter
1.配置好handleradapter時(shí)勃教,bean的name可以加.do也可以不加厨诸,沒(méi)有配置時(shí)必須加上.do才能使用昏滴。
使用simpleurlhandlermapping
<bean class="simpleurlhandlermapping">
<property name="mappings">
<props>
<prop key="/hello.do">hello</prop>
</props>
</property>
</bean>
跳轉(zhuǎn)結(jié)果方式
1.設(shè)置ModelAndView對(duì)象,根據(jù)View名稱(chēng)和視圖解析器跳轉(zhuǎn)到指定頁(yè)面:視圖解析器前綴+viewname+視圖解析器后綴
2.通過(guò)servletAPI對(duì)象來(lái)實(shí)現(xiàn)橙垢,不需要視圖解析器的配置。
a.response.getwriter().println
b.response.sendredirect
c.request.setattribute;request.getrequestdispatcher.forward;
3.通過(guò)springmvc實(shí)現(xiàn)轉(zhuǎn)發(fā)和重定向(沒(méi)有視圖解析器)
a.public String hello(){
return "index.jsp";
}
b.public String hello(){
return "forward:index.jsp";
}
c.public String hello(){
return "redirect:index.jsp";
}
4.通過(guò)springmvc實(shí)現(xiàn)轉(zhuǎn)發(fā)和重定向(有視圖解析器)
a.轉(zhuǎn)發(fā)
return"hello";會(huì)用到視圖解析器
b.重定向
return“redirect:hello.do";不會(huì)用到視圖解析器
將數(shù)據(jù)顯示到UI層
1.通過(guò)ModelAndView--需要視圖解析器
ModelAndView mv=new ModelAndView();
mv.addObject("msg","hello springmvc");
mv.setViewName("hello");
return mv;
2.通過(guò)ModelMap來(lái)實(shí)現(xiàn)--不需要視圖解析器
ModelMap需要作為處理方法的參數(shù)
public String hello(String name,ModelMap model){
model.addAttribute("name",name);
return "index.jsp";
}