# 实现 springmvc 简单案例
# 实现 maven 的基本配置
1 2 3 4 5
| <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties>
|
# 坐标导入
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <dependencies>
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.10.RELEASE</version> </dependency> </dependencies>
|
# tomcat 的配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <build> <plugins> <plugin>
<groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.1</version> <configuration> <port>80</port> <path>/</path> </configuration> </plugin> </plugins> </build>
|
# 创建软件包实现 controller 层
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package com.ljc.controller;
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; //使用@Controller定义bean @Controller public class Usercontroller { //设置当前操作的访问路径 @RequestMapping("/save") //设置当前操作返回值类型 @ResponseBody public String save() { System.out.println("user模块正在执行。。。。。"); return "{'module':'springmvc'}";
} }
|
在创建配置类 config (ServletContaininitConfig 和 SpringMvcConfig)
# ServletContaininitConfig 类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| package com.ljc.config;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer; //定义一个servlet容器自动的配置类,在里面加载spring的配置 public class ServletContaininitConfig extends AbstractDispatcherServletInitializer { //加载SpringMvc容器配置 @Override protected WebApplicationContext createServletApplicationContext() { AnnotationConfigWebApplicationContext ctx=new AnnotationConfigWebApplicationContext(); ctx.register(SpringMvcConfig.class); return ctx; } //设置哪些请求归属SpringMvc处理 @Override protected String[] getServletMappings() { return new String[]{"/"}; } //加载spring容器配置 @Override protected WebApplicationContext createRootApplicationContext() { return null; } }
|
# SpringMvcConfig
1 2 3 4 5 6 7 8 9 10 11
| package com.ljc.config;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; //创建springmvc的配置文件,加载controller对应的bean @Configuration @ComponentScan("com.ljc.controller") public class SpringMvcConfig {
}
|
在黑马上面做的一个简单的案例!!!