IDEA: spring+mybatis+springMVC SSM框架(二) spring 整合 springMVC

在上一篇文章的基础上 我们在pom文件中添加springMVC 的依赖



  org.springframework
  spring-webmvc
  4.3.20.RELEASE

注销掉spring-web包的依赖 spring-webmvc 会冲突
IDEA: spring+mybatis+springMVC SSM框架(二) spring 整合 springMVC_第1张图片

然后创建一个配置文件 ApplicationContext-mvc.xml 对springMVC进行配置




    
    
    
    
    
    
    
    

    
    
        
        
        
    


此配置文件中同样配置了context:component-scan,将ApplicationContext.xml 中的context:component-scan 注释掉,后续在ApplicationContext.xml 配置整合mybatis

编辑web.xml 添加 配置SpringMVC核心控制器的代码


    
        springMvc
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath*:ApplicationContext-mvc.xml
        
        
        1
    
    
    
        springMvc
        
        /
    

    
    
        encodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
        
            forceEncoding
            true
        
    

    
        encodingFilter
        /*
    

注:如果web.xml报错 修改web-app属性保证兼容


下面来验证一下

创建一个视图(View) 我们视图前缀是配置的是/WEB-INF/jsp/ 在前缀目录下创建一个hello.jsp

IDEA: spring+mybatis+springMVC SSM框架(二) spring 整合 springMVC_第2张图片

然后创建一个控制器(Controller) 去跳转到这个视图

package com.ssm.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping(value = "test")
public class TestController {

    private Logger logger = Logger.getLogger(TestController.class);

//    @Autowired
//    private TestService testService;

    @RequestMapping(params = "firstMethod")
    public String firstMothed() {
//        testService.firstService();
        return "hello";
    }
}

IDEA: spring+mybatis+springMVC SSM框架(二) spring 整合 springMVC_第3张图片

启动项目 输入请求地址 test.do?firstMethod

我们看到了 hello.jsp中的内容

IDEA: spring+mybatis+springMVC SSM框架(二) spring 整合 springMVC_第4张图片

但是我们Controller中返回的是个String的hello, 为什么会跳转到jsp呢?
Controller 将我们返回的String当作了View的名称 去/WEB-INF/jsp/ 找对应的jsp文件了
我们可以通过@ResponseBody 告诉springMVC我需要响应的是数据 而不是视图

我们在TestController 新建一个方法来测试下

@RequestMapping(params = "secondMethod")
@ResponseBody
public String secondMethod() {
    return "hello";
}

重新启动服务 访问 test.do?secondMethod

IDEA: spring+mybatis+springMVC SSM框架(二) spring 整合 springMVC_第5张图片

这次好了 我们的hello没有被当作视图去解析

简单的spring整合SpringMVC就完成了

进度包下载地址,希望大家可以一起进步~

https://download.csdn.net/download/qq_33668603/10870040

你可能感兴趣的:(spring)