springboot controll 跳转页面的代码
时间: 2023-12-14 09:03:32 浏览: 30
以下是一个简单的Spring Boot控制器(Controller)代码示例,演示了如何跳转到一个页面:
```java
@Controller
public class MyController {
@GetMapping("/hello")
public String hello() {
return "hello"; // 返回视图名
}
}
```
上面的示例中,我们定义了一个控制器(使用注解`@Controller`),其中包含了一个处理GET请求的方法`hello`。该方法返回一个字符串`hello`,这个字符串是视图(页面)的名称。
在这个例子中,我们期望Spring Boot能够自动解析视图名称,并跳转到名为`hello.html`的Thymeleaf模板文件(如果存在的话)。
我们也可以使用`Model`对象向视图传递数据:
```java
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("name", "world");
return "hello";
}
```
在这个示例中,我们向模型(Model)对象添加了一个名为`name`的属性,其值为`"world"`。在视图中,我们可以使用Thymeleaf模板引擎将这个属性值显示出来:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<h1>Hello, <span th:text="${name}"></span>!</h1>
</body>
</html>
```
在这个示例中,我们使用了Thymeleaf的表达式语言(Expression Language,EL)来显示`name`属性的值。该表达式使用了Thymeleaf的`th:text`属性,它会将属性值设置到HTML元素的文本内容中。
总之,Spring Boot的控制器可以使用不同的方式来跳转页面,如返回视图名称、使用模型传递数据等。这些方式都可以根据具体的业务需求进行灵活的配置和使用。