微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java之SpringMVC学习二使用注解、跳转、重定向、参数接收

代码

package com.jay.controller;

import com.jay.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

//使用注解自动装配
@Controller
//一级目录,这个Controller下的所有视图访问的时候都要拼接/home
public class HelloController {
    //访问路径
    //@RequestMapping("/hello")
    @GetMapping("/hello/{a}/{b}")//get请求,restful风格的url
    //@PostMapping("/hello/{a}/{b}")//post请求
    //restful风格的路径,简洁、高效(支持缓存)、安全(隐藏参数名)
    public String hello(@PathVariable int a, @PathVariable int b, Model model) {
        int c = a + b;
        model.addAttribute("c", c);
        //Model用来存储视图数据,jsp页面可以直接取出
        model.addAttribute("msg", "Hello SpringMVCAnnotation!");
//        return "hello";//视图名
        //没有视图解析器时,用下面三种方法跳转
//        return "/WEB-INF/view/hello.jsp";//视图路径
//        return "forward:/WEB-INF/view/hello.jsp";//转发
        return "redirect:/test";//重定向到指定的url
//        return "redirect:/index.jsp";//重定向到指定的jsp页面
        //注意路径,斜杠/直接到webapp目录下
    }

    //http://localhost:9091/hello/1/2
    @RequestMapping("/test")
    public String test(Model model) {
        model.addAttribute("msg", "test xxxxxx");
//        return "/WEB-INF/view/test.jsp";//没有视图解析器的方式
        return "test";
    }

    //如果多个视图,写多个hello这样的方法就可以了,不用每个都写一个servlet。
    @RequestMapping("/test1")
    public String test1(@RequestParam("username") String username, Model model) {
        //@RequestParam配置前端参数只能传username,否则报错
        model.addAttribute("msg", username);
        return "test1";
    }
    //http://localhost:9091/test2?age=19&id=1&username=jay
    @RequestMapping("/test2")
    public String test2(User user, Model model) {
        //使用对象接收前端参数,会自动绑定到user对应的属性中
        model.addAttribute("msg", user.toString());
        return "test2";
    }
}

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐