基于SpringMVC注解 写一个Helloworld的程序
时间: 2024-03-16 17:46:15 浏览: 120
好的,下面是基于SpringMVC注解的Helloworld程序的示例代码:
1. 首先,在pom.xml文件中添加以下依赖:
```xml
<dependencies>
<!--SpringMVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<!--JSP-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
```
2. 在web.xml文件中配置DispatcherServlet:
```xml
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
```
3. 创建dispatcher-servlet.xml文件,在其中配置SpringMVC:
```xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns: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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<context:component-scan base-package="com.example.controller"/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
```
4. 创建Controller类,实现Helloworld功能:
```java
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloWorldController {
@RequestMapping("/hello")
public String sayHello(Model model) {
model.addAttribute("message", "Hello World!");
return "hello";
}
}
```
5. 创建JSP页面,展示Helloworld信息:
```jsp
<!DOCTYPE html>
<html>
<head>
<title>HelloWorld</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>
```
6. 最后,在Tomcat中部署并启动该项目,在浏览器中输入http://localhost:8080/项目名/hello,即可看到Helloworld信息展示在页面上。
希望这个示例程序能帮助你理解SpringMVC注解的使用方式。
阅读全文