资讯专栏INFORMATION COLUMN

基于注解方式配置springMVC 并整合mybatis(一)

岳光 / 890人阅读

摘要:在实战一书中前面两部分分别介绍了和的高级特性,并且基于类配置有一套层的,但是没有将层整合层,于是我试着整合了下,也方便以后写测试。

在《springBoot实战》 一书中前面两部分分别介绍了spring 和 springMVC的高级特性,并且基于java类配置有一套web层的demo,但是没有将web层整合dao层,于是我试着整合了下,也方便以后写测试demo。下面是我的整理

pom.xml(一些基础的jar包,可能有些在这个demo中不会用到)



    4.0.0

    com.tao
    springmvc_demo_simple
    1.0-SNAPSHOT
    war

    
        
        1.7
        UTF-8
        UTF-8
        
        2.2
        1.2
        3.1.0
        
        4.1.5.RELEASE
        
        1.0.13
        1.7.5
    

    
        
            javax
            javaee-web-api
            7.0
            provided
        

        
        
            org.springframework
            spring-webmvc
            ${spring-framework.version}
        

        
        
            javax.servlet
            jstl
            ${jstl.version}
        

        
            javax.servlet
            javax.servlet-api
            ${servlet.version}
            provided
        

        
            javax.servlet.jsp
            jsp-api
            ${jsp.version}
            provided
        

        
        
            org.springframework
            spring-tx
            ${spring-framework.version}
        

        
        
            org.slf4j
            slf4j-api
            ${slf4j.version}
        
        
            log4j
            log4j
            1.2.16
        
        
            org.slf4j
            jcl-over-slf4j
            ${slf4j.version}
        
        
            ch.qos.logback
            logback-classic
            ${logback.version}
        
        
            ch.qos.logback
            logback-core
            ${logback.version}
        
        
            ch.qos.logback
            logback-access
            ${logback.version}
        

        
        
            com.fasterxml.jackson.dataformat
            jackson-dataformat-xml
            2.5.3
        

        
        
            com.alibaba
            fastjson
            1.1.41
        

        
        
            commons-fileupload
            commons-fileupload
            1.3.1
        
        
        
            commons-io
            commons-io
            2.3
        

        
            org.springframework
            spring-test
            ${spring-framework.version}
            test 
        

        
            junit
            junit
            4.11
            test
        

        
        
            org.mybatis
            mybatis
            3.2.6
        
        
        
            org.mybatis
            mybatis-spring
            1.2.2
        
        
        
            mysql
            mysql-connector-java
            5.1.6
        
        
        
            commons-dbcp
            commons-dbcp
            1.2.2
        
        
            org.springframework
            spring-jdbc
            ${spring-framework.version}
        
        
            org.springframework
            spring-context-support
            ${spring-framework.version}
        
        
        
            aspectj
            aspectjweaver
            1.5.3
        

    

    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                2.3.2
                
                    ${java.version}
                    ${java.version}
                
            
            
                org.apache.maven.plugins
                maven-war-plugin
                2.3
                
                    false
                
            
        
    

配置类(类似于springMVC.xml)

@Configuration
@EnableWebMvc
@EnableScheduling
@ComponentScan(basePackages = { "com.tao.demo.web" })
public class MyMvcConfig extends WebMvcConfigurerAdapter{
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/classes/views/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);
        return viewResolver;
    }

    @Bean
    public MultipartResolver multipartResolver(){
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        commonsMultipartResolver.setMaxUploadSize(1000000);
        return commonsMultipartResolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //静态资源
        registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/");
    }

    @Bean
    public DemoInterceptor demoInterceptor(){
        return new DemoInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(demoInterceptor());
    }


    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("/index");
    }

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUseSuffixPatternMatch(false);
    }

    @Override
    public void extendMessageConverters(List> converters) {
        converters.add( new MyMessageConverter());
    }

}

拦截器

public class DemoInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime",startTime);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long startTime = (Long)request.getAttribute("startTime");
        request.removeAttribute("startTime");
        long endTime = System.currentTimeMillis();
        System.out.println("本次请求处理时间"+new Long(endTime-startTime)+"ms");
        request.setAttribute("handingTime",endTime-startTime);
    }
}

自定义消息转换器

public class MyMessageConverter extends AbstractHttpMessageConverter{

    public MyMessageConverter() {
        super(new MediaType("application","x-tao", Charset.forName("UTF-8")));
    }

    @Override
    protected boolean supports(Class aClass) {
        return DemoObj.class.isAssignableFrom(aClass);
    }

    @Override
    protected DemoObj readInternal(Class aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        String s = StreamUtils.copyToString(httpInputMessage.getBody(), Charset.forName("UTF-8"));
        String[] split = s.split("-");
        return new DemoObj(Long.valueOf(split[0]),split[1]);
    }

    @Override
    protected void writeInternal(DemoObj obj, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        String s = "hello:" + obj.getId() + "-" + obj.getName();
        httpOutputMessage.getBody().write(s.getBytes());
    }
}

初始化(相当于web.xml)

public class WebInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(MyMvcConfig.class);
        context.setServletContext(servletContext);
        ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher",new DispatcherServlet(context));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
        servlet.setAsyncSupported(true);
//  整合dao层的时候需要
//        servletContext.setInitParameter("contextConfigLocation","classpath:spring-mybatis.xml");
//        servletContext.addListener(ContextLoaderListener.class);
    }
}

控制层

@Controller
public class HelloController {

    @RequestMapping("index")
    public String hello(){
        System.out.println("hello world");
        return "index";
    }

}

view

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>



    
    Insert title here


        Welcome to Spring MVC world!
    

整体目录结构

运行结果

基于注解方式配置springMVC 并整合mybatis(二)

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/67877.html

相关文章

  • 基于注解方式配置springMVC 整合mybatis(二)

    摘要:基于注解方式配置并整合一接上篇文章,如下是整合数据层。整合时,如果不加上就无法启动容器。 基于注解方式配置springMVC 并整合mybatis(一) 接上篇文章,如下是整合数据层。 spring-mybatis.xml ...

    peixn 评论0 收藏0
  • Java后端

    摘要:,面向切面编程,中最主要的是用于事务方面的使用。目标达成后还会有去构建微服务,希望大家多多支持。原文地址手把手教程优雅的应用四手把手实现后端搭建第四期 SpringMVC 干货系列:从零搭建 SpringMVC+mybatis(四):Spring 两大核心之 AOP 学习 | 掘金技术征文 原本地址:SpringMVC 干货系列:从零搭建 SpringMVC+mybatis(四):Sp...

    joyvw 评论0 收藏0
  • 手撕面试官系列(二):开源框架面试题Spring+SpringMVC+MyBatis

    摘要:跳槽时时刻刻都在发生,但是我建议大家跳槽之前,先想清楚为什么要跳槽。切不可跟风,看到同事一个个都走了,自己也盲目的开始面试起来期间也没有准备充分,到底是因为技术原因影响自己的发展,偏移自己规划的轨迹,还是钱给少了,不受重视。 跳槽时时刻刻都在发生,但是我建议大家跳槽之前,先想清楚为什么要跳槽。切不可跟风,看到同事一个个都走了,自己也盲目的开始面试起来(期间也没有准备充分),到底是因为技...

    Flink_China 评论0 收藏0
  • ssm框架整合

    ssm整合 开发环境ide,mysql数据库,Spring+SpringMVC+Mybatis,tomcat8.5,jdk使用的是1.7版本。 第一步:导入jar包 Spring+ SpringMVC + MyBatis + Mybatis-spring整合包 AOP联盟+织入 + c3p0 数据库连接池 + MySQL连接驱动 + jstl 链接:https://pan.baidu.com/...

    Simon_Zhou 评论0 收藏0

发表评论

0条评论

岳光

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<