SpringMVC前后端交互

参数绑定

Controller层请求

在请求过程中使用@RequestMapping注解,将URL映射到controller的类或方法上。

@RequestMapping注解特点

  1. 窄化请求
    添加在类上,对URL请求进行分类管理,在类上添加该注解的URL(称为根路径),URL访问的完整路径变为 -> 根路径 + 子路径。
    这时候访问页面就应该在/test前加上/user:http://localhost:8080/user/test
@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/test")
    public @ResponseBody String test(){
        return "hello houoyi";
    }
}
  1. 限制HTTP请求方法
    限制HTTP请求特定的方法可以起到保护URL的目的(保证服务端的安全访问)。如果指定为get方法请求,则除了get方法请求可以通过外,其他的请求都不能通过。
@RequestMapping(value = "/list" ,method = RequestMethod.POST)

springMVC参数绑定

  • 参数绑定即客户端发送请求,而请求中包含一些数据,这些数据传递到 controller 层对应的方法的参数上,这个过程就涉及到参数绑定的问题。

参数绑定过程

在这里插入图片描述

  • 参数绑定器:将请求的数据转化为需要的数据。
  • SpringMVC,在客户端提交数据的过程中,客户端将数据以key-value形式进行提交,在SpringMVC中通过参数绑定器将参数绑定到方法的形参上。
具体步骤

这里还是用school数据库中student表为例进行操作。

  1. 在用户列表页面(studentlist.jsp)添加修改操作:
    在这里插入图片描述
  2. 添加修改页面 jsp文件(editStudent.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>修改页面</title>
    </head>
    <body>
    <form action="${pageContext.request.contextPath }/student/submit" method="post">
    <table width="60%" border="1"align="center">
    <h1 align="center">修改学生信息</h1>
    <tr>
    <td>学生ID</td>
    <td> <input type="text" name="SID" value="${student.SID }" readonly ></td> </td>
    </tr>
    <tr>
    <td>用户名</td>
    <td> <input id="Sname" type="text" name="Sname" value="${student.sname }"></td> </td>
    </tr>
    <tr>
    <td>性别</td>
    <td> <input id="Ssex" type="text" name="Ssex" value="${student.ssex }"></td> </td>
    </tr>
    <tr>
    <td>年龄</td>
    <td> <input id="Sage" type="text" name="Sage" value="${student.sage }"></td> </td>
    </tr>
    <tr ><td colspan="2" align="center"><input   type="submit" value="提交"/></td></tr>
    </table>
    </form>
    </body>
    </html>
  1. Handler实现
    dao层添加:
    在这里插入图片描述
    Mapper文件添加:
    在这里插入图片描述
    Service层添加:
    在这里插入图片描述
    主要操作:在Controller层添加修改函数
    在这里插入图片描述

SpringMVC支持的参数类型

默认参数类型

SpringMVC中支持的默认的参数类型,可以直接在形参上给出默认的参数类型,可直接使用。

  • HttpServletRequest request, 通过request对象进行参数获取。
  • HttpServletResponse response, 通过response对象处理响应信息。
  • HttpSession session, 通过Session对象来获取Session中的对象。
  • Model model,Model是一个接口,modelMap是接口实现,将 model数据封装到 request中

使用示例:

public ModelAndView list(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model) throws IOException {
        request.getParameter("id");//前端页面传递的 id属性通过 request.getParameter进行接收
        response.getWriter().write("");//响应结果

        session.setAttribute("name","张三");//写缓存信息
        session.getAttribute("name");//获取缓存
        model.addAttribute("name","key");//写数据
}
基本参数类型
  • 基本的类型, byte\ short\ int\ long\ float\ double\ char\ boolean 都能够进行支持。
  • 以int类型为例介绍,以form表单(前端向后端提交数据的一种格式)提交数据给后台。

jsp页面:

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
        <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
        <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
        <html>
        <head>
        <title>数据提交</title>
        </head>
        <body>
          <form action="/student/test" method="post">
             <input name="num" value="7"  type="text"/>
              <input type="submit" value="提交"> </input>
          </form>
        </tbody>
        </table>
        </form>
        </body>
        </html>

controller层实现
在这里插入图片描述

  • 注意
    表单中Inputname值和controller层上方法的形参保持一致,就能完成参数绑定。
    如果不一致 -> 通过注解@RequestParam完成参数的绑定:
    在这里插入图片描述
自定义参数类型
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>修改页面</title>
    </head>
    <body>
    <form action="${pageContext.request.contextPath }/student/submit" method="post">
    <table width="60%" border="1"align="center">
    <h1 align="center">修改学生信息</h1>
    <tr>
    <td>学生ID</td>
    <td> <input type="text" name="SID" value="${student.SID }" readonly ></td> </td>
    </tr>
    <tr>
    <td>用户名</td>
    <td> <input id="Sname" type="text" name="Sname" value="${student.sname }"></td> </td>
    </tr>
    <tr>
    <td>性别</td>
    <td> <input id="Ssex" type="text" name="Ssex" value="${student.ssex }"></td> </td>
    </tr>
    <tr>
    <td>年龄</td>
    <td> <input id="Sage" type="text" name="Sage" value="${student.sage }"></td> </td>
    </tr>
    <tr ><td colspan="2" align="center"><input   type="submit" value="提交"/></td></tr>
    </table>
    </form>
    </body>
    </html>

controller层的实现

    @RequestMapping("/submit")
    public void submit(Student211 student){
        System.out.println("submit:"+student);
    }
  • 注意:在进行自定义参数绑定时,Input中name值需要和自定义类型的类中属性名保持一致,才能完成自定义对象的映射,否则无法完成映射。
    在这里插入图片描述

字符集编码问题(中文乱码问题)

  <!--字符集编码配置-->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

返回值

Controller请求返回值的类型

ModelAndView

modelAndView对象返回包含数据和逻辑视图名,或者仅视图

@RequestMapping(value = "/student")                                   
public ModelAndView list() throws IOException {                       
    List<Student211> student211s = studentService.selectAllStudents();
                                                                      
    ModelAndView modelAndView = new ModelAndView();                   
    modelAndView.addObject("students",student211s);                   
    modelAndView.setViewName("studentlist");                          
    return modelAndView;                                              
}                                                                     

String

返回逻辑视图名

逻辑视图名=前缀+视图名称+后缀(注意要将springmvc.xml文件中视图解析器的前后缀设置屏蔽掉)

@RequestMapping(value = "/student1")    
public String list1(Model model) throws IOException {
        List <Student211> student211s = userService.selectAllStudents();
        model.addAttribute("students",student211s);
        return "/WEB-INF/jsp/studentlist.jsp";
}                               
redirect(重定向)

重定向:浏览器上地址会改变,修改后的数据无法传递到重定向页面(request数据不能共享)

@RequestMapping("/submit")
    public String submit(Student211 student){
        System.out.println("id"+student.getSID());
        return "redirect:/student/student";//重定向
}

在这里插入图片描述

forward(页面转发)

浏览器地址不会发生改变request数据可以共享

    @RequestMapping("/submit")
    public String submit(Student211 student){
        System.out.println("id:"+student.getSID());
        return "forward:/student/list";
    }

在这里插入图片描述

void

通过request转向页面
@RequestMapping("/submit")
public void submit(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
	//forward
 	request.getRequestDispatcher("/student/student").forward(request,response);
}
通过response页面重定向
@RequestMapping("/submit")
public void submit(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
	//redirect
	response.sendRedirect("/student/student");
}
通过response进行页面响应
  @RequestMapping("/submit")
public void submit(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
	response.setContentType("application/json;charset=utf-8");
    response.getWriter().write("hello world");
}

在这里插入图片描述

  • 19
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值