springMVC的基础知识及入门程序

来源:互联网 发布:陈奕迅不要说话知乎 编辑:程序博客网 时间:2024/06/03 12:23

什么是springMVC?

springmvc是spring框架的一个模块,springmvc和spring无需通过中间整合层进行整合。springmvc是一个基于mvc的web框架。

springMVC架构

架构原理:前端控制器 处理器映射器 处理器适配器 视图解析器


这里写图片描述
第一步:发起请求到前端控制器(DispatcherServlet);
第二步:前端控制器请求HandlerMapping查找 Handler可以根据xml配置、注解进行查找;
第三步:处理器映射器HandlerMapping向前端控制器返回执行链(包含拦截器、Handler);
第四步:前端控制器调用处理器适配器去执行Handler
第五步:处理器适配器去执行Handler
第六步:Handler执行完成给适配器返回ModelAndView;
第七步:处理器适配器向前端控制器返回ModelAndView( 注:ModelAndView是springmvc框架的一个底层对象,包括 Model和view);
第八步:前端控制器请求视图解析器去进行视图解析,根据逻辑视图名解析成真正的视图(jsp);
第九步:视图解析器向前端控制器返回View;
第十步:前端控制器进行视图渲染,视图渲染将模型数据(在ModelAndView对象中)填充到request域;
第十一步:前端控制器向用户响应结果 。

组件:
1、前端控制器DispatcherServlet(不需要程序员开发)
作用接收请求,响应结果,相当于转发器,中央处理器。
有了DispatcherServlet减少了其它组件之间的耦合度。

2、处理器映射器HandlerMapping(不需要程序员开发)
作用:根据请求的url查找Handler

3、处理器适配器HandlerAdapter
作用:按照特定规则(HandlerAdapter要求的规则)去执行Handler

4、处理器Handler(需要程序员开发)
相当于controller层
注意:编写Handler时按照HandlerAdapter的要求去做,这样适配器才可以去正确执行Handler

5、视图解析器View resolver(不需要程序员开发)
作用:进行视图解析,根据逻辑视图名解析成真正的视图(view)

6、视图View(需要程序员开发jsp)
View是一个接口,实现类支持不同的View类型(jsp、freemarker、pdf…)

入门程序

web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns="http://xmlns.jcp.org/xml/ns/javaee"    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"    id="WebApp_ID" version="3.1">    <display-name>aisino0711</display-name>    <!-- springMVC 前端控制器 -->    <servlet>        <servlet-name>springMVC</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <init-param>            <!--contextConfigLocation配置springMVC加载的配置文件(配置处理器映射器、适配器等等) -->            <param-name>contextConfigLocation</param-name>            <param-value>/WEB-INF/springMVC.xml </param-value>        </init-param>    </servlet>    <servlet-mapping>        <servlet-name>springMVC</servlet-name>        <!-- 第一种:*.action 访问以*.action结尾的由DispatcherServlet进行解析                     第二种:/, 所有访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析                使用此种方法可以 实现RESTful风格的url -->        <url-pattern>*.action</url-pattern>    </servlet-mapping>    <welcome-file-list>        <welcome-file>index.html</welcome-file>        <welcome-file>index.htm</welcome-file>        <welcome-file>index.jsp</welcome-file>        <welcome-file>default.html</welcome-file>        <welcome-file>default.htm</welcome-file>        <welcome-file>default.jsp</welcome-file>    </welcome-file-list></web-app>

springMVC.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.1.xsd                 http://www.springframework.org/schema/context                 http://www.springframework.org/schema/context/spring-context-3.1.xsd                 http://www.springframework.org/schema/mvc                 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">    <!-- 配置Handler <bean id="showGoods1" name="/queryaction.action" class="com.aisino.controller.GoodsController"></bean> -->    <!-- 1.处理器映射器 将bean的name作为url查找,需要在配置handler时指定beanname <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean> -->    <!-- 2.处理器映射器 简单的url映射, 需要需要在配置handler时指定beanid     <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">     <property name="mappings"> <props> <prop key="/queryaction1.action">showGoods1</prop>     </props> </property> </bean> -->    <!-- 使用 mvc:annotation-driven代替上边注解映射器和注解适配器配置 mvc:annotation-driven默认加载很多的参数绑定方法,         比如json转换解析器就默认加载了,如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequestMappingHandlerAdapter         实际开发时使用mvc:annotation-driven -->    <mvc:annotation-driven></mvc:annotation-driven>    <!-- 可以扫描controller、service、... 这里让扫描controller,指定controller的包  配置Handler -->    <context:component-scan base-package="com.aisino.controller"></context:component-scan>    <!-- 1.处理器适配器 controller层需要实现 controller接口 -->    <bean        class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter">    </bean>    <!-- 2.处理器适配器 controller层需要实现 httprequestHandler接口 -->    <bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter">    </bean>    <!-- 视图解析器 解析jsp标签 -->    <bean        class="org.springframework.web.servlet.view.InternalResourceViewResolver">    </bean></beans>  

该配置文件中使用了两种方式:非注解方式和注解方式
非注解处理器映射器

<!-- 1.处理器映射器 将bean的name作为url查找,需要在配置handler时指定beanname <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean> -->    <!-- 2.处理器映射器 简单的url映射, 需要需要在配置handler时指定beanid     <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">     <property name="mappings"> <props> <prop key="/queryaction1.action">showGoods1</prop>     </props> </property> </bean> -->

非注解处理器适配器

    <!-- 1.处理器适配器 controller层需要实现 controller接口 -->    <bean        class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter">    </bean>    <!-- 2.处理器适配器 controller层需要实现 httprequestHandler接口 -->    <bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter">    </bean>

注解处理器适配器和处理器

<!-- 使用 mvc:annotation-driven代替上边注解映射器和注解适配器配置 mvc:annotation-driven默认加载很多的参数绑定方法,         比如json转换解析器就默认加载了,如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequestMappingHandlerAdapter         实际开发时使用mvc:annotation-driven -->    <mvc:annotation-driven></mvc:annotation-driven>

使用注解的映射器和注解的适配器。(注解的映射器和注解的适配器必须配对使用)

controller层(该处实现了注解的方式)

package com.aisino.controller;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import com.aisino.entity.Goods;import com.aisino.until.HibernateUtil;/** * 实现controller接口的处理器 * @author suny *  * *///使用Controller标识 它是一个控制器@org.springframework.stereotype.Controllerpublic class GoodsController1{    //@RequestMapping实现 对queryItems方法和url进行映射,一个方法对应一个url        //一般建议将url和方法写成一样    @RequestMapping("/showGoods")    public ModelAndView handleRequest(HttpServletRequest request,            HttpServletResponse response) throws Exception {        // TODO Auto-generated method stub        //调用service查找数据库        SessionFactory factory = HibernateUtil.getSessionFactory();        // 获取session对象        Session session = factory.openSession();        // 获取事务对象        Transaction tran = session.getTransaction();        // 开启事务        tran.begin();        //调用session对象的load方法实现查询。        Goods goods = (Goods) session.get(Goods.class, 2);        //返回modelAndView        ModelAndView modelAndView  = new ModelAndView();        //相当与request中的setAttribut ,在jsp页面中通过goods取数据        modelAndView.addObject("goods", goods);        //指定视图        modelAndView.setViewName("/showGoods.jsp");        // 关闭事务,提交或回滚        tran.commit();        // 关闭session        session.close();        // 关闭sessionFactroy        HibernateUtil.shutdown();        return modelAndView;    }}

jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>查询商品列表</title></head><body>    <form        action="${pageContext.request.contextPath }/item/queryItem.action"        method="post">        查询条件:        <table width="100%" border=1>            <tr>                <td><input type="submit" value="查询" /></td>            </tr>        </table>        商品列表:        <table width="100%" border=1>            <tr>                <td>商品名称</td>                <td>商品价格</td>                <td>商品数量</td>                <td>操作</td>            </tr>            <tr>                <td>${goods.name }</td>                <td>${goods.price }</td>                <td>${goods.num }</td>                <td><a                    href="${pageContext.request.contextPath }/item/editItem.action?id=${item.id}">修改</a></td>            </tr>        </table>    </form></body></html>

通过入门程序理解springmvc前端控制器、处理器映射器、处理器适配器、视图解析器用法。

原创粉丝点击