上篇文章,我们围绕什么是Spring MVC进行讲述了,这篇,我们将在IDEA创建我们的第一个Spring MVC项目。
创建我们的第一个Spring MVC项目
创建项目模块
如果你出现上面小图这样的,代表你就成功创建成功了一个Web项目,当然方式有好几种。我偏向喜欢这种罢了。我就使用这种方式进行讲解啦。
配置依赖
接下来我们需要配置依赖了,在配置依赖之前,由于我们是通过上述自动创建的方式创建war项目,故而我们需要将<build>
删除。:
注意依赖这步骤很重要,请各位亲们仔细一点,如果是复制粘贴的可以,就使用我的,如果是自己敲的,请各位注意一下,千万别敲错了。
注:由于 Maven 的传递性,我们不必将所有需要的包全部配置依赖,而是配置最顶端的依赖,其他靠传递性导入。
还有不是按照我的方式创建的亲们,这里是war.不是jar。
配置web.xml
注意,在配置这一步的时候,你需要注意的事情是,我们默认创建的web.xml是有问题的,这个时候你需要改成我这样的。
可通过init-param标签设置SpringMVC配置文件的位置和名称,通过load-on-startup标签设置
我们先将默认的index.jsp删除,我们将主要使用html进行,我们在WEB-INF目录下,创建一个Templates文件夹,用来存放我们的html文件。
创建一个index.html
创建java包和类
看上图,我们发现我们没法写代码,你发现我们现在缺了一个java文件夹来撰写我们的Java项目,现在我们来看看如何创建。
选择main,然后右键选择上述图片中框红的位置,然后idea会显示Java,resources,点击一下Java就可以创建Java项目了。然后我们在Java文件夹下创建我们想要的包。
创建一个SpringMVC.xml文件
在上面创建了一个resources,接下来创建一个springMVC.xml文件
配置Tomcat启动
接下来我们需要再Idea配置一个Tomcat,然后将项目部署到Tomcat中。
注意,为了避免8080冲突,我将端口号改成了8008。亲,你的可以使用默认的。
启动项目
浏览器发送请求,若请求地址符合前端控制器的url-pattern,该请求就会被前端控制器DispatcherServlet
处理。前端控制器会读取SpringMVC
的核心配置文件,通过扫描组件找到控制器,将请求地址和控制器中@RequestMapping
注解的value
属性值进行匹配,若匹配成功,该注解所标识的控制器方法就是处理请求的方法。处理请求的方法需要返回一个字符串类型的视图名称,该视图名称会被视图解析器解析,加上前缀和后缀组成视图的路径,通过Thymeleaf
对视图进行渲染,最终转发到视图所对应页面