Spring MVC随后笔记:
1. MVC原理图:
控制器:(Servlet)
模型:(JavaBean) <---> 数据库
视图:(JSP)
2. 核心点:
(1) 前端控制器(DispatcherServlet):
① 作用:接收web请求,响应结果(集中访问点);
② 实现:在web.xml文件中配置:
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>*.actionurl-pattern>
servlet-mapping>
(2) 配置Handler适配器:(配置JavaBean)
① 在springmvc下配置:(springmvc.xml)
”org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter”>
(3) 配置注解Handler映射器和适配器:
”org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping”>
”org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter”>
<-- 实际开发时使用mvc:annotation-driven -->
(4) 控制类:(可优化成注解的方式)
public class IndexController implements Controller {
Public ModelAndView handler(HttpServlet request, HttpServletResponse respomse) throws Exception{
ModelAndView mav = new ModelAndView(“index.jsp”);
mav.addObject(“message”, “Hello Spring MVC”);
return mav;
}
}
注:控制类实现Controller接口,提供handler方法请求
ModelAndView:视图(index.jsp)、模型(数据message,内容Hello Spring MVC)
(5) 视图:(index.jsp)
若要接收表单数据:
$
$
3. 采用注解方式:
控制类:
@Controller //表示是一个控制类
public class IndexController{
Public ModelAndView handler(HttpServlet request, HttpServletResponse respomse) throws Exception{
@RequestMapping(“/index”) //表示/index会映射到该方法上
ModelAndView mav = new ModelAndView(“index.jsp”);
mav.addObject(“message”, “Hello Spring MVC”);
return mav;
}
}
映射配置:
直接从包controller下扫描@Controller注解的类
class=”org.springframework.web.servlet.handler.simpleUrlHandlerMapping”>