美文网首页SSM架构程序员技术干货
SpringMvc使用以及ssm整合

SpringMvc使用以及ssm整合

作者: 越长越圆 | 来源:发表于2017-07-14 15:47 被阅读176次

    SpringMvc框架使用

    • 导包
    • 配置web.xml文件
    <?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:p="http://www.springframework.org/schema/p"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    
         <!--扫描@Controler @Service-->
        <context:component-scan base-package="com.fmt.springmvc"></context:component-scan>
    
    
        <!--<!–处理器映射器–>-->
        <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>-->
    
        <!--<!–处理器引射器–>-->
        <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>-->
    
        <!--视图解析器-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
        <!--注解驱动-->
        <mvc:annotation-driven/>
    </beans>
    

    配置springmvc.xml

    <?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:p="http://www.springframework.org/schema/p"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    
         <!--扫描@Controler @Service-->
        <context:component-scan base-package="com.fmt.springmvc"></context:component-scan>
    
    
        <!--<!–处理器映射器–>-->
        <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>-->
    
        <!--<!–处理器引射器–>-->
        <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>-->
        
        
        <!--注解驱动-->
        <mvc:annotation-driven/>
    </beans>
    

    实现一个Controller

    @Controller
    public class ItemController {
    
    
            @RequestMapping(value = "/item/itemlist.action",method = {RequestMethod.POST,RequestMethod.GET})
        public ModelAndView itemList(){
            ModelAndView mav=new ModelAndView();
            //mav.setViewName("/WEB-INF/jsp/itemList.jsp");
            //配置了视图解析器后
            mav.setViewName("itemList");
            return mav;
        }
    }
    

    访问http://localhost:8080/item/itemlist.action

    参数绑定

    //直接方法上写提交上来的参数名字可以直接获得
      @RequestMapping(value = "/item/paramer.action")
        public ModelAndView getParamer(@RequestParam(value = "age",required = false,defaultValue = "1") int age,Integer id, String name){
            System.out.println(id);
            System.out.println(name);
            List<Items> itemselect = itemService.getItemselect();
            ModelAndView mav=new ModelAndView();
            mav.setViewName("itemList");
            return mav;
        }
    

    对象绑定

    @RequestMapping(value = "/item/user.action")
        public ModelAndView getUser(User user){
            System.out.println(user);
            ModelAndView mav=new ModelAndView();
            mav.setViewName("itemList");
            return mav;
        }
    

    //http://localhost:8080/item/user.action?age=12&name=xiaohon(自动封装一个User)

    在类上处理映射

    @RequestMapping(value = "/item")
    public class ItemController {
    //多个url映射到同一个方法上
    @RequestMapping(value ={ "/paramer.action"," "/paramexxxr.action""})
        public ModelAndView getParamer(){
            
        }
    }
    

    自定义参数绑定

    如果提交了一个date为2017:12-02 15_22-22,springmvc没办法把字符串转换成日期类型。所以需要自定义参数绑定。

       @RequestMapping(value = "/item/user.action")
        public ModelAndView getUser(User user,Date date){
            System.out.println(user);
            ModelAndView mav=new ModelAndView();
            mav.setViewName("itemList");
            return mav;
        }
    
    public class DateConver implements Converter<String,Date>{
    
        @Override
        public Date convert(String s) {
            try {
                if (null!=s){
                    DateFormat format=new SimpleDateFormat("yyyy:MM-dd HH_mm-ss");
                    return format.parse(s);
                }
            }catch (Exception e){
    
            }
            return null;
        }
    }
    
    
    <!--注解驱动-->
        <mvc:annotation-driven conversion-service="formattingConversionService"/>
         <!--配置Conveter转换器 转换日期-->
        <bean id="formattingConversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
            <!--配置多个转换器-->
            <property name="converters">
                <set>
                    <bean class="com.fmt.springmvc.conver.DateConver"></bean>
                </set>
            </property>
        </bean>
    
    

    PathVariable

    @RequestMapping(value ="/itemEdit/{id}.action")
        public void test(@PathVariable Integer id){
    }
    

    Controller的返回

    • ModelAndView
    • String
    public String testController(Model model){
    
    //return "forward:path";//path代表转发的地址
    return "redirect:path";//path代表重定向的地址
    
    }
    
    • Void(返回这种结果的时候可以在Controller方法的形参中定义HTTPServletRequest和HTTPServletResponse对象进行请求的接收和响应)

    异常处理器

    当发生异常了,捕获到异常信息

    public class CustomExceptionResolver implements HandlerExceptionResolver {
        @Override
        public ModelAndView resolveException(javax.servlet.http.HttpServletRequest httpServletRequest,
                                             javax.servlet.http.HttpServletResponse httpServletResponse,
                                             Object o,
                                             Exception e) {
    //        发生异常的地方sevice 方法
            //可以记录到日志
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("error","发生错误");
            modelAndView.setViewName("error");
    
            return modelAndView;
        }
    }
    
    

    在springmvc.xml中注册

       <!--SpringMvc的异常处理器-->
        <bean class="com.fmt.springmvc.exception.CustomExceptionResolver"/>
    

    访问进入异常界面,在上方能捕获到

    @RequestMapping(value = "/item/itemlist.action",method = {RequestMethod.POST,RequestMethod.GET})
        public ModelAndView itemList(){
            List<Items> itemselect = itemService.getItemselect();
            ModelAndView mav=new ModelAndView();
            mav.setViewName("itemList");
            int i=1/0;
            return mav;
        }
    

    图片上传

      @RequestMapping(value = "update.action")
        public void file(MultipartFile file) throws IOException {
            file.transferTo(new File("D:\\"));
        }
    

    在springmvc中配置

     <!--上传图片的实现类-->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!--上传图片的大小 单位是B-->
            <property name="maxUploadSize" value="500000"/>
        </bean>
    

    json交互

    客户端提交json数据,服务器返回json数据

     @RequestMapping(value = "/json.action")
        @ResponseBody
        //客户端提交json数据,自动解析成User
        public User json(@RequestBody  User user){
             return user;
        }
    

    如果提示415错误的话参考下面文章
    http://blog.csdn.net/tiantiandjava/article/details/46125141

    拦截器

    springmvc.xml配置

       <!--SpringMvc的拦截器-->
        <mvc:interceptors>
            <!--多个拦截器-->
            <mvc:interceptor>
                <!--/aaa/bbb-->
                <mvc:mapping path="/**"/>
                <!--自定义拦截器类-->
                <bean class="com.fmt.springmvc.interceptor.interceptor1"></bean>
            </mvc:interceptor>
            <mvc:interceptor>
                <!--/aaa/bbb-->
                <mvc:mapping path="/**"/>
                <!--自定义拦截器类-->
                <bean class="com.fmt.springmvc.interceptor.interceptor2"></bean>
            </mvc:interceptor>
        </mvc:interceptors>
    
    public class interceptor1 implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
            System.out.println("方法前1");
            //是否拦截
            return false;
        }
    
        @Override
        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
            System.out.println("方法后1");
        }
    
        @Override
        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
            System.out.println("页面渲染后1");
        }
    }
    

    SpringMvc 流程

    这里写图片描述

    架构流程

    ⦁ 用户发送请求至前端控制器DispatcherServlet
    ⦁ DispatcherServlet收到请求调用HandlerMapping处理器映射器。
    ⦁ 处理器映射器根据请求url找到具体的处理器,生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。
    ⦁ DispatcherServlet通过HandlerAdapter处理器适配器调用处理器
    ⦁ 执行处理器(Controller,也叫后端控制器)。
    ⦁ Controller执行完成返回ModelAndView
    ⦁ HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet
    ⦁ DispatcherServlet将ModelAndView传给ViewReslover视图解析器
    ⦁ ViewReslover解析后返回具体View
    ⦁ DispatcherServlet对View进行渲染视图(即将模型数据填充至视图中)。
    ⦁ DispatcherServlet响应用户

    处理器映射器、处理器适配器、视图解析器称为springmvc的三大组件。

    整合mybatis

    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
    
    
        <!-- Spring监听器 -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </context-param>
    
      <!-- 处理POST提交乱码问题 -->
      <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
      </filter>
      
      <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>*.action</url-pattern>
      </filter-mapping>
      
    
        <!--前端控制器-->
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
          <!--默认找/WEB-INF/[servlet的名称]-servlet.xml-->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc.xml</param-value>
            </init-param>
        </servlet>
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <!--
              1./*拦截所有jsp js png .css全拦截 建议不适用
              2.*.action *.do 以do action结尾的请求 肯定能使用
              3./ 拦截所有(不包括jsp)(包含 .js .png .css)强烈建议使用
            -->
            <url-pattern>*.action</url-pattern>
        </servlet-mapping>
    
    </web-app>
    

    springmvc与struts2不同

    ⦁ springmvc的入口是一个servlet即前端控制器,而struts2入口是一个filter过滤器。
    ⦁ springmvc是基于方法开发(一个url对应一个方法),请求参数传递到方法的形参,可以设计为单例或多例(建议单例),struts2是基于类开发,传递参数是通过类的属性,只能设计为多例。
    ⦁ Struts采用值栈存储请求和响应的数据,通过OGNL存取数据, springmvc通过参数解析器是将request请求内容解析,并给方法形参赋值,将数据和视图封装成ModelAndView对象,最后又将ModelAndView中的模型数据通过request域传输到页面。Jsp视图解析器默认使用jstl。

    SSM整合

    配置sqlMapConfig.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    
        <!--别名-->
        <typeAliases>
            <package name="com.fmt.ssm.pojo"/>
        </typeAliases>
    
    </configuration>
    

    配置applicationContext-dao.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
           xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    
        <!-- 配置 读取properties文件 jdbc.properties -->
        <context:property-placeholder location="classpath:jdbc.properties" />
    
    
    
        <!-- 配置 数据源 -->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${jdbc.driver}" />
            <property name="url" value="${jdbc.url}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
        </bean>
    
        <!-- 配置SqlSessionFactory -->
        <bean class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 设置MyBatis核心配置文件 -->
            <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
            <!-- 设置数据源 -->
            <property name="dataSource" ref="dataSource" />
        </bean>
    
        <!-- 配置Mapper扫描 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- 设置Mapper扫描包 -->
            <property name="basePackage" value="com.fmt.ssm.map" />
        </bean>
    
    
    
    
    </beans>
    

    配置applicationContext-service.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
           xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    
        <!-- 配置Service扫描 -->
        <context:component-scan base-package="com.fmt.ssm.service" />
    </beans>
    
    

    配置SpringMvc.xml

    <?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:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
        <!-- 配置Controller扫描 -->
        <context:component-scan base-package="com.fmt.ssm.controller" />
        
            <context:property-placeholder location="classpath:resource.properties" />
        
        <!-- 配置注解驱动 -->
        <mvc:annotation-driven />
        
        <!-- 对静态资源放行  -->
        <mvc:resources location="/css/" mapping="/css/**"/>
        <mvc:resources location="/js/" mapping="/js/**"/>
        <mvc:resources location="/fonts/" mapping="/fonts/**"/>
        <!-- 配置视图解析器 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- 前缀 -->
            <property name="prefix" value="/WEB-INF/jsp/" />
            <!-- 后缀 -->
            <property name="suffix" value=".jsp" />
        </bean>
    </beans>
        
    
    

    配置web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
        <display-name>ssm</display-name>
        <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>
    
    
        <!-- 配置spring -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/applicationContext-*.xml</param-value>
        </context-param>
    
        <!-- 配置监听器加载spring -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
    
        <!-- 配置过滤器,解决post的乱码问题 -->
        <filter>
            <filter-name>encoding</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>encoding</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        <!-- 配置SpringMVC -->
        <servlet>
            <servlet-name>ssm</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:spring/springmvc.xml</param-value>
            </init-param>
            <!-- 配置springmvc什么时候启动,参数必须为整数 -->
            <!-- 如果为0或者大于0,则springMVC随着容器启动而启动 -->
            <!-- 如果小于0,则在第一次请求进来的时候启动 -->
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>ssm</servlet-name>
            <!-- 所有的请求都进入springMVC -->
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
    
    </web-app>
    

    原文链接:http://blog.csdn.net/qq_22329521/article/details/75116264

    相关文章

      网友评论

        本文标题:SpringMvc使用以及ssm整合

        本文链接:https://www.haomeiwen.com/subject/mpfohxtx.html