今天,开启新的学习之路,学习spring。需要用到的开发环境,myEclipse2016,jdk1.8、Tomcat8.0,今天第一篇主要介绍如何在项目中添加spring的支持。总体流程为,导jar包,修改配置文件。下面依次说明。
首先,新建一个web项目,在web-info下面的lib添加spring需要的jar包,然后添加到项目中即可,具体如图所示
其次,添加配置文件,添加spring-mvc.xml,具体文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 自动扫描的包路径 -->
<context:component-scan base-package="my" />
<mvc:annotation-driven />
</beans>
修改web.xml,spring框架是基于servlet实现的,所以我们需要修改web.xml,内容如下:
<!-- Spring Framework -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- spring-mvc.xml的路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</context-param>
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 拦截的路径 -->
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
将上面的内容天添加到web.xml中。
到此,spring的添加已经完成,下面写代码来验证一下,我们新建一个类如下:
package my;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController
{
@RequestMapping("getStudent")
public Student getStudent()
{
Student stu = new Student();
stu.setId(20190001);
stu.setName("小韦");
stu.setCellphone("13810012345");
return stu;
}
}
然后,将项目跑起来,在浏览器输入:http://127.0.0.1:8080/springDemo01/app/getStudent
如果浏览器返回如下:
到此,项目中添加spring支持已经成功,下面开始学习之旅。