SpringMVC的第一个程序——helloworld
步骤:
(一)导包
(二)配置
(三)测试
准备工作:
- 切换至“Java EE”模式(如果没有这个模式,可在搜索框中搜索)。
(一)导包
(二)配置
功能说明:index界面中有一个超链接,点击超链接后会发送“hello”请求,点击超链接后会跳转至“success” 界面。
- 新建index.jsp页面(在WebContent文件夹下新建“jsp file”):
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="hello">helloworld</a>
</body>
</html>
- 在WEB-INF文件夹下创建“pages”文件夹,用于存放jsp页面,在该文件夹下创建“success。jsp”页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>成功!<h1>
</body>
</html>
- 创建控制器组件(类)“MyFirstController.java”
package com.atguigu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
//@Controller:说明该组件(类)为控制器类,并将其加入容器中(此时需要在容器配置文件中添加扫描,才能将该组件添加至容器中)。
@Controller
public class MyFirstController {
// @RequestMapping("/hello"):请求映射。前端index页面中点击超链接后会像控制器发送一个“hello”请求,此时控制器会接受该请求,并做出如下方法中的反应。
@RequestMapping("/hello")
public String hello(){
System.out.println("控制器接收到请求。。。正在处理中。。。");
// 控制器接到“hello”请求后先打印以上语句,然后返回“success”界面给前端展示。
return "/WEB-INF/pages/success.jsp";
}
}
- 在类路径下(src文件夹)创建容器配置文件“springMVC.xml”
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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.0.xsd">
<context:component-scan base-package="com.atguigu"></context:component-scan>
</beans>
- 配置web.xml文件
(三)测试
运行“index.jsp”页面即可