坐标
<!--Spring坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!--SpringMVC坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!--Servlet坐标-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--Jsp坐标-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
Controller:该包负责请求转发,接受页面过来的参数,传给Service处理,接到返回值,再传给页面
UserController:控制器类
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
//Controler负责请求转发,接受页面过来的参数,传给Service处理,接到返回值,再传给页面。
@Controller//SpringMVC的Bean配置
public class UserController {
@RequestMapping("/save")//设置当前的访问路径
@ResponseBody//设置当前操作的返回值类型
public String save(){
System.out.println("use save...");
return "{'module':'springmvc'}";
}
}
配置类
SpringMVCconfigpackage com.example.demo.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration//定义配置类
@ComponentScan("com.example.demo.controller")
public class SpringMVCconfig {
}
ServletConfig
package com.example.demo.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 ServletConfig extends AbstractDispatcherServletInitializer {
// 加载mvc的配置
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext ctx=new AnnotationConfigWebApplicationContext();//初始化web容器
ctx.register(SpringMVCconfig.class);//加载配置
return ctx;
}
//设置哪些请求是mvc处理的
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
//加载spring的配置
@Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
}
标签:web,入门,SpringMVC,springframework,案例,context,org,import,servlet From: https://www.cnblogs.com/7ink/p/17602309.html