What is `@Controller` does?

26 篇文章 0 订阅
11 篇文章 0 订阅

@ControllerSpringMVC注解,标记一个类作为Web控制器(Controller),负责处理HTTP请求并返回响应结果

SpringMVC中,控制器类的主要职责是:
1、接收来自客户端的HTTP请求
2、调用服务层或其他业务逻辑组件
3、根据操作结果准备视图模型数据(Model),将控制权转移给视图解析器(View Resolver)渲染视图
4、操作结果直接返回HTTP响应(例如JSON、XML等)。

使用样例

简单页面渲染

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class SimplePageController {

    @GetMapping("/hello")
    public String displayHelloPage() {
        // ...
        return "hello"; // 假设有一个名为"hello.html"的模板文件在视图解析器配置的路径下
    }
}

结合ModelAndView对象使用

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class UserViewController {

    @GetMapping("/users/{id}")
    public ModelAndView showUser(@PathVariable Long id, Model model) {
        // 假设userService.find(id)获取用户信息
        User user = userService.find(id);

        // 将用户信息添加到模型中供视图模板使用
        model.addAttribute("user", user);

        // 返回包含视图名称和模型数据的ModelAndView对象
        return new ModelAndView("user-profile", model.asMap());
    }
}

处理POST请求并返回重定向

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/login")
public class LoginController {

    @GetMapping
    public String showLoginForm() {
        // 显示登录表单页面
        return "login";
    }

    @PostMapping
    public String processLogin(@RequestParam("username") String username,
                              @RequestParam("password") String password,
                              RedirectAttributes redirectAttrs) {

        // 假设userService.authenticate(username, password)进行身份验证
        if (userService.authenticate(username, password)) {
            // 登录成功,重定向到主页
            redirectAttrs.addFlashAttribute("successMessage", "Welcome, you have successfully logged in!");
            return "redirect:/home";
        } else {
            // 登录失败,将错误信息添加到模型中以便在重定向后的页面显示
            redirectAttrs.addFlashAttribute("errorMessage", "Invalid credentials. Please try again.");
            return "redirect:/login";
        }
    }
}

结合@RequestBody处理JSON数据

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @PostMapping("/users")
    public ResponseEntity<User> createUser(@RequestBody CreateUserRequest request) {
        User user = userService.createUser(request.getName(), request.getEmail());
        return ResponseEntity.ok(user);
    }

    static class CreateUserRequest {
        private String name;
        private String email;

        // getters and setters
    }
}

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值