基于Spring使用Idea搭建简化版Web应用

引言

本来打算到网上找一个Demo示例直接使用,发现很多各种版本,各种配置的都有,而不能精简,因此,为了能够快速搭建Spring的Web简版开发环境,并能够了解其中的配置,将整个过程记录下来,也为后续自己需要的时候可以直接使用。

前提条件

开发工具:Idea
使用框架:maven+spring

基于Maven搭建Web项目

1、使用Idea的Maven创建项目,选择maven-archetype-webapp
基于Spring使用Idea搭建简化版Web应用_第1张图片
2、填写groupId和artifactId
基于Spring使用Idea搭建简化版Web应用_第2张图片
3、点击next后,如图
基于Spring使用Idea搭建简化版Web应用_第3张图片
4、一直next到finish后就会生成一个web的项目,配置tomcat运行
基于Spring使用Idea搭建简化版Web应用_第4张图片
其中未对生成后的目录文件进行讲解,因为比较简单

5、启动完成后,就会弹出网页
基于Spring使用Idea搭建简化版Web应用_第5张图片
此时的Web项目就创建完成,我们继续添加Spring相关的组件来实现从前端到服务端的请求。

Spring+SpringMVC实现请求

借用idea的工具,直接在Project项目上右键,选择“Add Framework Support…”
基于Spring使用Idea搭建简化版Web应用_第6张图片
选择SpringMVC后点击“OK” 直接会生成需要的配置文件,如图:
基于Spring使用Idea搭建简化版Web应用_第7张图片

配置文件

现在开始对配置文件进行最简化的配置,将项目能够运行起来
1、web.xml




  Spring WebProject
  
    contextConfigLocation
    /WEB-INF/applicationContext.xml
  
  
    org.springframework.web.context.ContextLoaderListener
  

  
    dispatcher
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      /WEB-INF/dispatcher-servlet.xml
    
    1
  
  
    dispatcher
    /
  

2、applicationContext.xml





3、dispatcher-servlet.xml




    
        
    

其他代码

1、pom文件中需要添加的配置


      org.springframework
      spring-webmvc
      5.1.8.RELEASE
    
    
      javax.servlet
      javax.servlet-api
      4.0.1
      provided
    

2、对应的Controller类

/**
 * @Auther: chenyanwu
 * @Date: 2019/9/30 16:38
 * @Description:
 * @Version 1.0
 */
@Controller
@RequestMapping("/hello")
public class HelloController {

    @RequestMapping("/say")
    @ResponseBody
    public String sayHello(String name) {
        return "Hello, " + name;
    }
}

到此代码对应的配置和代码已经写完,启动服务后:
浏览器中输入:http://localhost:8080/hello/say?name=chenyanwu
结果:
基于Spring使用Idea搭建简化版Web应用_第8张图片
对于配置文件:web.xml、applicationContext.xml、dispatcher-servlet.xml的文件详细说明,后续在抽时间详细罗列讲解!

更多精彩,更多技术请关注:码蚁在线(coding_online)
基于Spring使用Idea搭建简化版Web应用_第9张图片

你可能感兴趣的:(SpringMVC)