一、工程目录
二、步骤
- 先创建一个Maven工程。
- 创建好后,在pom.xml中添加
<packaging>war</packaging>
,表示最终要将整个工程打包成war包。 - 将整个WEB-INF放到webapp目录下。
- 在pom.xml中添加依赖。
<!--spring容器是用来扫描除了controller之外的东西,spring容器和spring-mvc容器是两个容器,
spring-mvc是spring的子容器,从子容器里面可以访问父容器的东西,反过来则不行;spring-mvc
容器用来扫描controller就行了。-->
<dependencies>
<!--添加spring-mvc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
</dependencies>
添加完依赖后,就会多出Spring Config这个选项。
5. 创建两个配置文件applicationContext.xml、spring-servlet.xml(Spring Config文件)和controller、service层。6. 配置applicationContext.xml、spring-servlet.xml。
applicationContext.xml
<!--use-default-filters设置为true,使用默认过滤,这样就会扫描org.kaneki下面所有的东西-->
<context:component-scan base-package="org.kaneki" use-default-filters="true">
<!--除去某个东西,不让spring容器扫描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
spring-servlet.xml
<context:component-scan base-package="org.kaneki" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--开启driven-->
<mvc:annotation-driven/>
7 配置web.xml。
<!--和spring相关的配置-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--和springmvc相关的配置-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
8 创建HelloController类和HelloService类。
HelloController.java
@RestController
public class HelloController {
@Autowired
HelloService helloService;
/**
* produces 防止乱码
* @GetMapping 实际上就是 @RequestMapping(method = {RequestMethod.GET})
*/
@GetMapping(value = "/hello", produces = "text/html;charset=utf-8")
public String hello(){
return helloService.sayHello();
}
}
HelloService.java
@Service
public class HelloService {
public String sayHello() {
return "hello Java !";
}
}
9 配置Tomcat,右上角"启动按钮"左边Add Configurations。
10 启动,打开浏览器,输入 http://localhost:8080/hello
。