用两种形式搭建springmvc开发环境,并编写controll用两种形式搭建springmvc开发环境,并编写controller做简单访问测试。分别采用返回字符串和返回视图页面两种形式。er做简单访问测试。分别采用返回字符串和返回视图页面两种形式。
时间: 2024-10-23 20:08:04 浏览: 14
AngularJS整合Springmvc、Spring、Mybatis搭建开发环境
在Spring MVC中,有两种常见的方式来搭建开发环境并编写Controller,分别是基于XML配置和基于注解配置。
**1. XML配置:**
首先,你需要添加Spring MVC依赖到你的Maven或Gradle项目中。然后,创建以下文件:
- **web.xml**: 配置Servlet和DispatcherServlet。
```xml
<web-app>
<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/spring-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>
</web-app>
```
- **spring-servlet.xml**: 配置Controller、视图解析器等。
```xml
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
```
创建Controller:
```java
@Controller
public class SimpleController {
@RequestMapping(value = "/hello")
public String hello() {
return "welcome"; // 返回字符串视图名
}
@RequestMapping(value = "/greeting", method = RequestMethod.GET)
public String greeting(Model model) { // 返回视图页面
model.addAttribute("message", "Hello Spring MVC!");
return "index"; // 返回具体的JSP视图名称
}
}
```
**2. 注解配置:**
去除XML配置文件,改为使用Java配置类。在pom.xml中引入Spring Boot或Spring Web MVC依赖。创建一个`Application.java`作为启动类:
```java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
创建Controller:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class SimpleController {
private final ViewResolver viewResolver;
@Autowired
public SimpleController(ViewResolver viewResolver) {
this.viewResolver = viewResolver;
}
@GetMapping("/hello")
public String hello() {
return "welcome";
}
@GetMapping("/greeting")
public String greeting(Model model) {
model.addAttribute("message", "Hello Spring MVC!");
return "index";
}
}
```
访问测试:
- 访问`http://localhost:8080/hello` (返回字符串): 你会看到浏览器加载指定的静态HTML内容(如welcome.html)
- 访问`http://localhost:8080/greeting` (返回视图页面): 显示名为`index.jsp`或类似后缀的视图页面,包含消息"Hello Spring MVC!"。
阅读全文