之前一直是使用Eclipse创建Web项目,用IDEA和MyEclipse的创建SpringMVC项目的时候时不时会遇到一些问题,这里把这个过程记录一下,希望能帮助到那些有需要的朋友。我是用的是MyEclipse2017 CI 3,相近版本应该都差不多。至于其他版本找到类似操作即可。
1.新建web项目
然后点击finish完成web项目创建。
2.安装Spring框架
此时,项目结构如图:
3.创建xml文件
内容如下:
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
servlet>
servlet-name>dispatcherorg.springframework.web.servlet.DispatcherServletinit-param>
param-name>contextConfigLocationparam-value>classpath:dispatcher-servlet.xml>
>
>
servlet-mapping监听所有请求-->
url-pattern>/>
web-app>
然后在src目录下创建名为 dispatcher-servlet.xml (与上面指定的文件名要一致)的文件。
内容如下:
beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsixmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
定义要扫描 controller的包-->
context:component-scanbase-package="com.frank.springmvc.controller" />
mvc:default-servlet-handler/>
启动注解驱动 SpringMVC 功能mvc:annotation-driven配置视图解析器解析路径beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"id="internalResourceViewResolver">
定义视图存放路径-->
propertyname="prefix"value="/WEB-INF/jsp/" />
定义视图后缀="suffix"=".jsp" />
beanbeans>
然后在WEB-INF目录下创建一个名为jsp的文件夹。
4.定义控制器
新建一个包com.frank.springmvc.controller(跟dispatcher-servlet.xml中指定的包名要一致)
然后在包下创建一个controller类,取名为HelloSpringMVC
代码如下:
packagecom.frank.springmvc.controller;importorg.springframework.stereotype.Controller;org.springframework.web.bind.annotation.RequestMapping;
@Controllerpublic HelloSpringMVC {
@RequestMapping("/hello")publicString test() {
System.out.println("test");return "hello";
}
}
这样,就会将对/HelloSpringMVC/hello路径的请求转向/WEB-INF/jsp/hello.jsp文件
5.创建jsp文件
在jsp文件夹下创建hello.jsp文件
hello.jsp中会有一些代码,这里只是尽快建立SpringMVC运行项目,无需修改。
6.部署项目到Tomcat服务器
然后启动服务器。
在浏览器中输入:localhost:8080/SpringMVCDemo/hello
如果显示正常说明我们的项目部署成功。
总结
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。