JavaEE学习日志(九十五): RestFul风格,控制器的返回值,重定向和转发,@SessionAttributes注解

JavaEE学习日志持续更新----> 必看!JavaEE学习路线(文章总汇)

SpringMVC

@SessionAttributes注解

作用:在session范围内存储对象

一、在类上标记该注解,表示在session范围内可以存储这两个变量名

@SessionAttributes({"username","password"})

二、把用户名和密码存入到session范围中,需要使用一个model对象,也可以使用modelMap对象

@RequestMapping("/testPut")
    public void testPut(Model model){
        model.addAttribute("username","zhangsan");
        model.addAttribute("password","123456");

    }

三、获取session范围内的对象,需要使用modelMap对象

@RequestMapping("/testGet")
    public void testGet(ModelMap modelMap){
        Object username = modelMap.get("username");
        System.out.println(username);
        Object password = modelMap.get("password");
        System.out.println(password);

    }

四、清空session,使用sessionStatus对象

@RequestMapping("/testClear")
    public void testClear(SessionStatus sessionStatus){
        sessionStatus.setComplete();
    }

RestFul风格

  • rest是一种编程风格
  • 满足了rest风格的网站,就是restful风格
  • 只是一种规范,不是规则

之前的写法,如:

  • 根据id获取一个用户
/user/findById?id=1
  • 根据id删除一个用户
/user/delById?id=1
  • 更新一个用户
/user/update?id=1
  • 添加一个用户
/user/save?id=1

若使用RestFul风格,则

  • 根据id获取一个用户,使用get方式提交
/user/operate/1
  • 根据id删除一个用户,使用delete方式提交
/user/operate/1
  • 更新一个用户,使用put方式提交
/user/operate/1
  • 添加一个用户,使用post方式提交
/user/operate/1

一、根据id获取用户和添加用户

  1. 将访问路径改成value = "/operate/{id}"
  2. 添加method属性,获取为get,添加为post
  3. 在形参前面添加注解@PathVariable("id")注意需要于访问路径中的名称一致,这样就可以获取到页面中传递的值了
@Controller
@RequestMapping("/user")
@SessionAttributes({"username","password"})
public class UserController {

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @RequestMapping(value = "/operate/{id}",method = RequestMethod.GET)
    public String findById(@PathVariable("id") Integer id){
        System.out.println("findById:"+id);
        return "show";
    }

    /**
     * 保存用户
     * @param id
     * @return
     */
    @RequestMapping(value = "/operate/{id}", method = RequestMethod.POST)
    public String save(@PathVariable("id") Integer id){
        System.out.println("save:"+id);
        return "show";
    }

}

jsp访问

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%--请求保存用户--%>
    <form action="/user/operate/1" method="POST">
        <input type="submit" value="提交">
    </form>
</body>
</html>

二、更新用户和删除用户

要使用put和delete提交方式

  1. 在web.xml中开启put和delete提交方式,添加过滤器HiddenHttpMethodFilter
<!--开启另外两种提交方式:put,delete-->
  <filter>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  1. 表单的提交方式必须是post
  2. 表单中必须设置一个隐藏域
    name=_method value=PUT
  3. 请求的方法返回值必须以流的形式返回(因为浏览器只能识别get和post请求),在方法上标记注解@ResponseBody
    相当于:response.getWriter().print()
/**
     * 更新用户
     * @param id
     * @return
     */
    @RequestMapping(value = "/operate/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public String update(@PathVariable("id") Integer id){
        System.out.println("update:"+id);
        return "show";
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @RequestMapping(value = "/operate/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public String delById(@PathVariable("id") Integer id){
        System.out.println("del:"+id);
        return "show";
    }
<%--更新用户--%>
    <form action="/user/operate/1" method="POST">
        <%--要使用put和delete提交方式
            1.在web.xml中开启put和delete提交方式
            2.表单的提交方式必须是post
            3.表单中必须设置一个隐藏域 name=_method value=PUT
            4.请求的方法返回值必须以流的形式返回,在方法上标记注解@ResponseBody
                相当于:response.getWriter().print()


        --%>
        <input type="hidden" name="_method" value="PUT">
        <input type="submit" value="更新">
    </form>

    <%--删除用户--%>
    <form action="/user/operate/1" method="POST">
        <input type="hidden" name="_method" value="DELETE">
        <input type="submit" value="删除">
    </form>

以上四种的浏览器访问路径都是同一个

http://localhost/user/operate/1

控制器方法的返回值

三种返回值类型:void、String、ModelAndView

返回值类型为void

因为没有指定返回值页面,会自动截取请求路径,进入视图解析器,拼接完整的路径。

方式一

package com.itheima.controller;

import com.itheima.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import java.lang.reflect.Member;
import java.util.Map;

@Controller
@RequestMapping("/user")
@SessionAttributes({"username","password"})
public class UserController {

    @RequestMapping("/testVoid")
    public void testVoid(){
        System.out.println("测试没有返回值");
        //因为没有指定返回值页面,会自动截取请求路径,进入视图解析器,拼接完整的路径
        //可以在对应的路径下创建对应的jsp页面
    }

}

此时根据路径访问时,会出现404页面,并在控制台打印
在这里插入图片描述

若在WEB-INF目录下创建 user文件夹,在user文件夹下创建testVoid.jsp
在这里插入图片描述
再次访问该路径,则会跳转到testVoid.jsp页面中
在这里插入图片描述
方式二: 使用重定向或转发

重定向:要注意,重定向不能进入WEB-INF目录

@RequestMapping("/testVoid2")
    public void testVoid2(HttpServletResponse response){
        System.out.println("测试没有返回值2");
        try {
            //重定向不能进入WEB-INF路径
            response.sendRedirect("/index.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

转发:可以进入WEB-INF目录

@RequestMapping("/testVoid3")
    public void testVoid3(HttpServletResponse response, HttpServletRequest request){
        System.out.println("测试没有返回值2");
        try {
            request.getRequestDispatcher("/WEB-INF/show.jsp").forward(request,response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

返回值类型为String

返回值进入视图解析器,拼接前缀和后缀后形成完整的路径。

/**
     * 方法的返回值为String
     * 返回值进入视图解析器,拼接前缀和后缀,完整的路径
     *
     */
    @RequestMapping("/testString")
    public String testString(){
        return "show";
    }

返回值类型为ModelAndView

ModelAndView:翻译为模型和视图

Model 模型:封装数据
View 视图:指定页面

/**
     * 返回值类型为ModelAndView,包含数据和视图页面
     * @return
     */
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView(){
        //准备数据
        List<User> userList = new ArrayList<>();
        User user = new User();
        user.setUsername("张三");
        user.setPassword("123");
        user.setId(2);

        User user2 = new User();
        user2.setUsername("张三2");
        user2.setPassword("123");
        user2.setId(3);

        userList.add(user);
        userList.add(user2);
        ModelAndView modelAndView = new ModelAndView();
        //添加数据
        modelAndView.addObject("userList",userList);
        //指定页面
        modelAndView.setViewName("show");
        return modelAndView;

    }

show.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
展示页面
${userList}
</body>
</html>

重定向和转发

当使用String类型为返回值时,默认为转发,会进入视图解析器拼接前缀后缀。

@RequestMapping("/testString")
    public String testString(){
        return "show";
    }

如果想要实现重定向,则需要加上redirect:,此时,就不会进入视图解析器。
注意:重定向不能进入WEB-INF目录下

/**
     * 添加了redirect后,不会进入视图解析器,需要配置完整的路径
     * 但重定向不能进入WEB-INF目录
     * @return
     */
    @RequestMapping("/testString2")
    public String testString2(){
        return "redirect:/index.jsp";
    }

如果想要实现转发,则需要加上forward:,此时,不会进入视图解析器,不会拼接前缀后缀

@RequestMapping("/testString3")
    public String testString3(){
        return "forward:/index.jsp";
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值