SpringMVC Controller返回值技巧:ModelAndView vs String的实战对比

server/2024/10/18 2:43:23/

前言

SpringMVC的相关小细节较多,这个博客主要针对控制层(Controller)中控制器方法的返回值为ModelAndView类型和返回值为String类型区别做出比较和案例实现

 第一步:创建web项目,添加依赖,配置web.xml

添加依赖

pom.xml:

<dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.1</version><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>4.3.2.RELEASE</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><build><finalName>springmvc1008</finalName><plugins><plugin><groupId>org.eclipse.jetty</groupId><artifactId>jetty-maven-plugin</artifactId><version>9.3.14.v20161028</version></plugin><plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven-plugin</artifactId><version>2.1</version><configuration><port>8080</port><path>/</path><uriEncoding>UTF-8</uriEncoding><server>tomcat7</server></configuration></plugin></plugins></build>
</project>

添加依赖包括:juint单元测试,springmvc依赖,servlet依赖 

添加两个插件:jetty服务器插件,tomcat服务器插件

注意:两个插件的目的是为了我们可以在maven项目中模拟本地服务器(tomcat或jetty)启动web项目

 配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-appversion="4.0"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:javaee="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xml="http://www.w3.org/XML/1998/namespace"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"><display-name>Archetype Created Web Application</display-name><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring.xml</param-value></init-param></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>*.cx</url-pattern></servlet-mapping>
</web-app>
  • 注意,如果不配置 <init-param>的话,那么springmvc会去WEB-INF/路径下去查找”你的servletname”-servlet.xml的配置文件,所以一般都会配置局部初始化参数,告诉spring配置文件的路径和名称.
  • 基于代码可读性的要求,尽量将请求url定义为*.do 或者*.action,以便区分前台请求和静态资源.(我这里设置为cx,这意味着访问请求时,需要带上后缀.cx,例如访问/login,需要在地址栏书写/login.cx)

 spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xmlns:util="http://www.springframework.org/schema/util"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.1.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.1.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-4.1.xsdhttp://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-4.1.xsd"><!-- 默认扫描的包路径 --><context:component-scan base-package="com.csx"/><!-- 添加注解驱动 --><mvc:annotation-driven/><!--处理器映射器-->
<!--    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>--><!--处理器适配器-->
<!--    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>--><!--视图解析器--><!-- 定义跳转的文件的前后缀 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp"/><!--    <bean name="/hello" class="com.csx.HelloController" />--></beans>	

基于注解开发的SpringMVC只需要配置默认扫描的包路径添加注解驱动以及配置视图解析器即可

 第二步:配置controller

在相应的控制器类中要添加@Controller注解,它本意和@Component 一致, 只不过带有特殊含义.

接下来进行案例分析:

登录页面

login.jsp

<%--Created by IntelliJ IDEA.User: AdministratorDate: 2024/10/8Time: 15:49To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<form action="/login.cx" method="post">用户名: <input type="text" name="user_name"> <br/>密码: <input type="password" name="password"> <br/><input type="submit" value="登录">
</form>
</body>
</html>

因为在web.xml中配置了后缀,所以这里的form表单中的action属性的url值,需要带上.cx后缀

登录案例(ModelAndView

java">@Controller
public class UserController {@RequestMapping("/login")public ModelAndView login(String user_name,String password){ModelAndView mv =new ModelAndView();if ("root".equals(user_name) && "123".equals(password)){mv.addObject("username",user_name);mv.setViewName("main");}else {mv.setViewName("login");}return mv;}
}
  • 将表单项的name属性值和控制器方法的形参名保持一致,就可以接受页面传递过来的参数。
  • @RequestMapping注解可以接受get和post的请求,如果想要设置接收指定类型,有两种方式
    • @GetMapping 和@PostMapping
    • @RequestMapping(value = "/login",method = RequestMethod.POST)

    • @RequestMapping(value = "/login",method = RequestMethod.GET)

  • @Controller注解,它本意和@Component 一致, 只不过带有特殊含义.

  • addObject方法可以向request域中存取数据,并且return  ModelAndView对象默认转发请求(forward)

  • setViewName方法可以设置要跳转的视图名

登录案例(String)

java">    @RequestMapping(value = "/login",method = RequestMethod.POST)public String login(User user , HttpSession session){if ("admin".equals(user.getUser_name()) &&"123".equals(user.getPassword())){session.setAttribute("user",user);return "main";}else {return "login";}}
  • controller控制器的参数可以是任意类型,包括了对象和HttpSession类型。
  • 如果是对象类型接收前端传入的参数,需要参数名与对象的属性名一一对应。

 比较分析

返回值为ModelAndView

其中,addObject用来存值,setViewName用来指定页面视图名称,视图解析器会添加上前缀和后缀,最后返回ModelAndView对象即可.

返回值为String

  • 只需将跳转的页面当做返回值即可.如果需要传递数据,可以在参数中使用Model的addAttribute方法.
  • 无论返回值时ModelAndView还是String,参数绑定机制都一样,即:
  • 只要表单或请求中的参数与方法参数一致,或者与参数对象的属性一致,即可自动绑定.

http://www.ppmy.cn/server/131731.html

相关文章

Ubuntu 22.04上安装Docker环境

前言 在当今快速发展的技术世界中&#xff0c;容器化技术已经成为软件开发和部署的核心工具之一。Docker作为容器化技术的领军者&#xff0c;因其轻量级、可移植性和高效性而备受开发者青睐。本文将详细介绍如何在Ubuntu 22.04上安装和配置Docker环境&#xff0c;为您的开发工作…

【TVM】——ubuntu18.04源码编译TVM

tvm, ubuntu18.04 1.创建conda环境 # make sure to start with a fresh environment conda env remove -n tvm-build-venv # create the conda environment with build dependency conda create -n tvm-build-venv -c conda-forge \"llvmdev>15" \"cmake>…

鸿蒙NEXT开发-知乎评论小案例(基于最新api12稳定版)

注意&#xff1a;博主有个鸿蒙专栏&#xff0c;里面从上到下有关于鸿蒙next的教学文档&#xff0c;大家感兴趣可以学习下 如果大家觉得博主文章写的好的话&#xff0c;可以点下关注&#xff0c;博主会一直更新鸿蒙next相关知识 专栏地址: https://blog.csdn.net/qq_56760790/…

【零散技术】MAC 安装多版本node

时间是我们最宝贵的财富,珍惜手上的每个时分 不同前端项目运行的node版本不一致&#xff0c;会导致无法运行&#xff0c;就像Odoo也需要依据版本使用对应的python环境。python 可以用 conda随时切换版本&#xff0c;那么Node可以吗&#xff1f;答案是肯定的。 1、安装 n&#x…

llvm开发心得

llvm使用心得 常用llvm命令 # 将.c编译为bitcode clang -emit-llvm -c test.c# 将bitcode反汇编为ir llvm-dis test.bc# 将ir转成bitcode llvm-as test.ll# 用lli执行bitcode或ir lli test.bc lli test.ll# llc将bitcode或ir转成目标汇编 llc test.bc llc test.ll# as将汇编转…

鸿蒙--下拉刷新+上拉加载

概述 Refresh组件支持下拉刷新,包裹list组件,下拉事件中更新列表 这里我们需要提前了解一下 @Builder装饰器 的基本用法 ArkUI提供了一种轻量的UI元素复用机制@Builder,该自定义组件内部UI结构固定,仅与使用方进行数据传递,开发者可以将重复使用的UI元素抽象成一个方法…

Android SELinux——安全策略(三)

SELinux 通过严格的访问控制机制增强了 Linux 系统的安全性。它通过标签和安全策略来控制进程和文件的访问权限,从而保护系统免受未经授权的访问和攻击。 一、策略介绍 1、主要组件 安全标签(Security Labels):每个文件、目录、进程等都有一个安全标签。标签包含类型(Ty…

使用激光跟踪仪提升码垛机器人精度

标题1.背景 码垛机器人是一种用于工业自动化的机器人&#xff0c;专门设计用来将物品按照一定的顺序和结构堆叠起来&#xff0c;通常用于仓库、物流中心和生产线上&#xff0c;它们可以自动执行重复的、高强度的搬运和堆垛任务。 图1 码垛机器人 传统调整码垛机器人的方法&a…