一、工程准备
1、jar包准备,maven下载后提取jar ,或 直接maven官网下载(费劲)
2、项目创建
打开Eclipse,并点击菜单栏的 "File"(文件)-> "New"(新建)-> "Dynamic Web Project"(动态Web项目)。
在弹出的对话框中,输入项目名称并选择目标运行时环境为Tomcat。
点击 "Next"(下一步)并在 "Configuration"(配置)中选择 "Generate web.xml deployment descriptor"(生成web.xml部署描述符)。
点击 "Next"(下一步),在 "Content Directory"(内容目录)中选择 "src/main/webapp",这是存放项目资源和Web页面的目录。
点击 "Finish"(完成)来创建项目。此时,您将在项目资源树中看到一个新的项目。
右键单击项目,选择 "Properties"(属性),然后选择 "Project Facets"(项目面板)。
在 "Project Facets"(项目面板)中,勾选 "Java" 和 "Dynamic Web Module",确保选择的版本与您的项目需求匹配。
点击 "Apply and Close"(应用并关闭)保存更改。
3、目录结构
4、导包
接下来,您需要添加Spring框架的库文件。将所需的Spring框架JAR文件拷贝到项目的 "WEB-INF/lib" 目录中。
二、运行准备
1、改端口 servers/server.xml
2、配置同步路径
三、代码书写
一、/GoodTestSpringMVC/src/com/example/controller/UserController.java
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
//1.定义1个 Controller
@Controller
public class UserController {
//3.设置网页访问路径@RM
@RequestMapping("/me")
//4.设置响应页面的类型@RB
@ResponseBody
//2.定义控制器的
public String save(){
System.out.println("系统 执行……");
return "{'me':'handsome'}";
}
}
二、/GoodTestSpringMVC/src/com/example/config/SpringMvcConfig.java
package com.example.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//5.注解配置springMVC
@Configuration
//6.加载controller
@ComponentScan("com.example.controller")
public class SpringMvcConfig {
}
三、/GoodTestSpringMVC/src/com/example/config/ServletConfig.java
package com.example.config;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
//7.定义一个servlet容器启动的配置类,在里面加载spring的配置 !ADSI
public class ServletConfig extends AbstractDispatcherServletInitializer{
//加载springMVC容器配置
@Override
protected WebApplicationContext createServletApplicationContext() {
//!ACWAC
AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext();
annotationConfigWebApplicationContext.register(SpringMvcConfig.class);
return annotationConfigWebApplicationContext;
}
// 设置哪些请求归属springMVC处理
@Override
protected String[] getServletMappings() {
String[] a = new String[]{"/"};//字符串数组
return a;
}
//加载spring容器配置
@Override
protected WebApplicationContext createRootApplicationContext() {
// TODO Auto-generated method stub
return null;
}
}
四、运行到tomcat
右键单击项目,选择 "Run As"(运行为)-> "Run on Server"(在服务器上运行)。选择您的Tomcat服务器进行部署和运行。