SpringMVC业务层框架配置实现hello world
SpringMVC业务层框架配置实现hello world
一、创建javaEE项目
1、创建项目后添加maven框架支持,然后加入SpringMVC框架所需要的maven依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
二、配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 配置分发器 -->
<servlet>
<!-- 这里servlet名称随意
需要对应spring配置文件名称
名称格式为:
servlet名称 + "-servlet.xml"
此处对应名称为:dispatcher-servlet.xml
-->
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<!-- 该servlet对应的站点目录 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
三、配置Spring框架配置文件,配置文件名称对应步骤二分发器servlet名称
<?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:mvc="http://www.springframework.org/schema/mvc"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 配置扫描路径 -->
<context:component-scan base-package="top.it1002.springmvc.controller"/>
<!-- 使用注解驱动 -->
<mvc:annotation-driven />
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 视图解析器前缀 -->
<property name="prefix" value="/"/>
<!-- 视图解析器后缀 -->
<property name="suffix" value=".jsp"/>
<!-- 例如控制器返回的地址为:index
那么解析地址对应为:前缀 + "index" + 后缀
e.g. /index.jsp
-->
</bean>
</beans>
四、创建一个控制器处理请求
IndexController.java
package top.it1002.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("index")
public String index(){
return "index";
}
}
五、编辑index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1 style="text-align: center;color: red;font-weight: 800;">Hello World</h1>
</body>
</html>