一、组件解析分析
- DispatcherServlet:前端控制器,整个流程的控制中心,调用其他组件处理客户端请求,它降低了代码的耦合性。
- HandlerMapping:处理器映射器,根据用户的请求找到一个合适的处理器(Handler)。
- HandlerAdaptor:处理器适配器,通过HanderAdaptor对处理器进行执行适配并应用。
- viewResolver:视图解析器,负责处理生成视图。
二、视图映射
- 默认转发是一次请求;重定向是两次请求。
- 方法返回的视图时转发(forward)。
@Controller
@RequestMapping(value = "index")
public class IndexController {
@RequestMapping(value = "toIndex")
public String toIndex(){
return "redirct:/index.jsp";
}
}
三、组件扫描
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.cxsw.controller"/>
</beans>
四、视图解析
- prefix:前缀。
- suffix:后缀。
- WEB-INF下的目录和文件是受保护的。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.cxsw.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/index/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
五、页面跳转
@Controller
@RequestMapping(value = "index")
public class IndexController {
@RequestMapping(value = "toIndex")
public String toIndex(){
return "index";
}
@RequestMapping(value = "redirectIndex")
public String toRedirect(){
return "redirect:/index/toIndex";
}
@RequestMapping("toModelAndView")
public ModelAndView toModelAndView(){
ModelAndView view = new ModelAndView();
view.setViewName("index");
view.addObject("username", "张三");
return view;
}
}