SpringMVC响应传值、请求传参的实现

1、SpringMVC 响应传值方式

SpringMVC如何从服务器传数据到浏览器?共四种方式
在这里插入图片描述

1.1 Controller方法的返回值类型为void(了解)

在Controller方法形参上可以定义request和response,使用request或response指定响应结果:

  1. 使用request请求转发页面:
    request.getRequestDispatcher(“页面路径”).forward(request, response);
  2. 通过response重定向页面:
    response.sendRedirect(“url”)
  3. 通过response指定响应结果,例如响应json数据如下:
    通过request.setAttribute(“key”,“value”)共享数据
@Controller
public class TestContro03 {
  
    @RequestMapping("/test01")
    public void test01(HttpServletRequest req, HttpServletResponse res) throws Exception{
        //返回void类型和共享数据,不用此方式!!!
        req.setAttribute("info","test01");
        //页面跳转
        req.getRequestDispatcher("/index.jsp").forward(req,res);
    }

1.2 返回ModelAndView类型和共享数据(掌握)

@RequestMapping("/test02")
    public ModelAndView test02(){
        //返回modelandview类型数据,使用多
        ModelAndView mv = new ModelAndView();
        User user = new User(01,"张三","123");
        /*共享数据*/
        mv.addObject("info","test02");
        mv.addObject("info1",user);
        /*跳转页面*/
        /*当要跳转的页面路径过长时,可以在springmvc配置文件中配置视图解析器,指定前缀和后缀*/
        mv.setViewName("/index.jsp");

        return mv;
    }

在SpringMVC配置文件中,重新配置视图解析器:
Controller方法返回字符串表示逻辑视图名,通过视图解析器解析为物理视图地址。
此时默认的物理视图地址为:视图前缀+逻辑视图名称+视图后缀.

<!--配置视图解析器,页面路径过于复杂,配置前缀和后缀-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/******"/>
        <property name="suffix" value=".jsp"/>
    </bean>

1.3 返回String类型和共享数据(掌握)

(1)返回值为String类型,字符串返回值就是要跳转的页面(逻辑视图名),默认视图的地址:前缀+方法的返回值+后缀
(2)使用参数中的Model对象共享数据

@RequestMapping("/test03")
    public String test03(Model model){
   
    
        model.addAttribute("info","test03");

        return "/index.jsp";
    
    }

(3)redirect和forward:

redirect方式相当于“response.sendRedirect()”,转发后浏览器的地址栏变为重定向后的地址,不共享之前请求的数据。

forward方式相当于“request.getRequestDispatcher().forward(request,response)”,转发后浏览器地址栏还是原来的地址,共享之前请求中的数据。

redirect或者forward之后,配置的视图解析器中的前缀和后缀不再有效.

return  "redirect/index.jsp"   // (重定向);
return  "forward/index.jsp"  //(请求转发)

1.4 返回对象类型和共享数据(掌握)

注意点:

  1. 返回对象类型的方法通常用于返回JSON字符串时,这种方法一般结合json使用
  2. 把当前请求的url作为逻辑视图名称
  3. key默认为返回值类型名user(首字母小写),可用注解 ModelAttribute修改key值
  4. value为user对象
1.4.1 SpingMVC结合JSON

1.将对象转换为json的方法有很多,可以使用工具类处理
有两种,一种是springMVC底层使用的jackson(此处使用)
另外一个中为阿里出品,fastjson
(1)导入jackson依赖,导入databind,会自动下载其他依赖。


<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.6</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.6</version>
        </dependency>
	
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.6</version>
        </dependency>

(2)在controller类中定义方法
在这里插入图片描述

//响应浏览器json格式数据
   @RequestMapping("/test04")
    @ResponseBody  //可以把返回的对象,转换成json格式字符串,响应给浏览器
    public Employee test04(){
        Employee emp = new Employee(01,"王五",new Date(),"123",true);
        return emp;
    }
1.4.2 jackson注解的常规使用
@Setter@Getter@ToString
@AllArgsConstructor@NoArgsConstructor
public class Employee {

    private Integer id;

    private String name;

    //@JsonFormat(pattern = "yyyy-MM-dd") 按照指定格式格式化
    private Date birthday;

    //@JsonIgnore   不显示此字段
    private String password;


    //@JsonProperty("gender")  起别名
    private Boolean sex;
}

2、SpringMVC 请求传参方式

2.1 传统的方式(了解)

方法参数中带入request,通过request.getParameter(“参数名”),再封装到JavaBean中(鸡肋)
(1)Controller类:

@Controller
public class Controller01 {

    @RequestMapping("/test01")
    public ModelAndView test01(HttpServletRequest req){
        //传统的方式,方法参数中带入request,通过request.getParameter("参数名"),再封装到JavaBean中.

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username+" "+password);
        return null;
    }

}

(2)jsp页面

<fieldset>
    <legend>请求方式一</legend>
    <form action="/test01" method="post">
        用户名:<input type="text" name="username"/>
        密码:<input type="password" name="password"/>
        <input type="submit" value="提交">
    </form>
</fieldset>

2.2 简单类型参数和RequestParam注解(掌握)

  1. 如果请求参数和Controller方法的形参同名. 可以直接接收
  2. 如果请求参数和Controller方法的形参不同名. 使用@RequestParam注解贴在形参前,设置对应的请求参数名称.

(1)Controller类:

@RequestMapping("/test02")
    public ModelAndView test02(@RequestParam("username") String name, String password){
        //简单类型参数和RequestParam注解(使用此注解,则必须传值,可设置默认值)
        /*同名匹配原则,形参名字和表单name属性名一致;若不一致,可使用@RequestParam*/
        System.out.println(name+" "+password);
        return null;
    }

(2)jsp页面

<fieldset>
    <legend>请求方式二</legend>
    <form action="/test02" method="post">
        用户名:<input type="text" name="username"/>
        密码:<input type="password" name="password"/>
        <input type="submit" value="提交">
    </form>
</fieldset>

在这里插入图片描述

2.3 对象传参(掌握)

  1. 能够自动把请求参数封装到声明在形参上的对象中,此时请求参数必须和对象的属性同名。
  2. 此时,SpringMVC会将对象参数直接放入request的作用域中,key名为类型首字母小写
  3. 或用@ModelAttribute(“xxx”)注解指定key名
    (1)Controller类:
@RequestMapping("/test03")
    public ModelAndView test03(User user){
        //对象传参,能够自动把请求参数封装到声明在形参上的对象中,此时请求参数必须和对象的属性同名(使用比较多).
        /*此时,SpringMVC会将对象参数直接放入request的作用域中,
        名称为类型首字母小写,或用@ModelAttribute("xxx")注解指定key名*/
        
        System.out.println(user);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/login.jsp");
        return mv;
    }

(2)jsp页面

<fieldset>
    <legend>请求方式三</legend>
    <form action="/test03" method="post">
        id:<input type="text" name="id"/>
        用户名:<input type="text" name="name"/>
        日期:<input type="date" name="date"/>
        <input type="submit" value="提交">
    </form>
</fieldset>

2.4 数组和List集合类型参数(使用)

2.4.1 接收数组类型参数:

(1)Controller类:

@RequestMapping("/test04")
    public ModelAndView test04(String id[]){
        //数组和List集合类型参数
        /*
        接收数组类型参数:必须同名
        不能直接获取,只能通过对象封装List集合.
         */
        for(String i:id){
            System.out.println(i);
        }
        return null;
    }

(2)jsp页面

<fieldset>
    <legend>请求方式四</legend>
    <form action="/test04" method="post">
        <input type="checkbox" name="id" value="1"/>
        <input type="checkbox" name="id" value="2"/>
        <input type="checkbox" name="id" value="3"/>
        <input type="submit" value="提交">
    </form>
</fieldset>
2.4.2 接收List类型参数:

不能直接获取,只能通过对象封装List集合.

@Getter@Setter
public class User {
    private List<Long> ids= new ArrayList<Long>();
}
 @RequestMapping("/test6")
    public ModelAndView test6(User u){
        System.out.println(u);
        return null;
    }

2.5 RESTful(了解)

一种软件架构风格,严格上说是一种编码风格,其充分利用 HTTP 协议本身语义从而提供了一组设计原则和约束条件。

@RequestMapping("/delete/{id}")
    public ModelAndView test05(@PathVariable("id")Long id){
        //RESTful是一种软件架构风格,严格上说是一种编码风格,
        // 其充分利用 HTTP 协议本身语义从而提供了一组设计原则和约束条件。
        /*主要用于客户端和服务器交互类的软件,该风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。
        在后台,RequestMapping标签后,可以用{参数名}方式传参,同时需要在形参前加注解@PathVarible,前台的请求地址为localhost:8080/delete/3*/
        System.out.println("delete");
        System.out.println(id);
        return null;

    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值