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

news/2024/10/18 23:27:30/

前言

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/news/1538906.html

相关文章

ubuntu 开放 8080 端口快捷命令

文章目录 查看防火墙状态开放 80 端口开放 8080 端口开放 22端口开启防火墙重启防火墙**使用 xhell登录**&#xff1a; 查看防火墙状态 sudo ufw status [sudo] password for crf: Status: inactivesudo ufw enable Firewall is active and enabled on system startup sudo…

LINUX---shell变量(或bash变量)和环境变量的区别

Shell 变量是特定于当前 shell 会话的变量。 作用范围&#xff1a;仅在当前 shell 会话中有效。如果你打开了多个终端窗口&#xff0c;每个窗口都有自己的一组 shell 变量&#xff0c;彼此独立。 生命周期&#xff1a;随着 shell 会话的结束而消失&#xff0c;不会传递给其他 …

Nodejs和C#使用ECDH算法交换秘钥

转载于&#xff1a;https://bkssl.com/document/nodejs-csharp-ecdh.html nodejs的ECDH算法在进行computeSecret的时候不会自动进行HASH运算&#xff0c;但C#的ECDH算法必须指定HASH算法。 两边算法必须使用相同的椭圆曲线和Hash算法&#xff0c;例如下面用例都是用的SHA256。…

刷题小计六:矩阵

73.矩阵置零 mid 矩阵置零 ①先使用两个变量&#xff08;row_0 & col_0&#xff09;&#xff0c;记录「首行 & 首列」是否该被置零 ②在「非首行首列」的位置&#xff0c;存储置零信息到首行首列 // 把第一行第一列作为标志位for (int i 1; i < row; i) {for (…

【工具使用】VCS仿真暂停dump波形_保存session,restore session

在仿真运行的过程中我们知道使用ctrlc可以进入ucli的交互界面&#xff0c;然后使用fsdbDumpflush将波形dump下来&#xff0c;此时查看完波形之后再输入run&#xff0c;仿真继续进行。这指出如果不使用fsdbDumpflush仿真路径下会产生较多关于fsdb的相关文件&#xff0c;输入指令…

RFID技术在汽车焊接生产线的智能应用与优化

RFID技术在汽车焊接生产线的智能应用与优化 随着科技的不断发展&#xff0c;智能化生产已经成为制造业的必然趋势&#xff0c;这就要求着生产方式也要随着发生改变。在汽车制造领域&#xff0c;RFID技术的应用&#xff0c;提升了汽车制造业的工作效率与管理水平。 在传统的在…

C语言刷题 LeetCode 30天挑战 (十)Stack 栈 (MinStack)

这个题目要求你设计一个特殊的栈&#xff08;MinStack&#xff09;&#xff0c;不仅要具备普通栈的基本功能&#xff08;push、pop 和 top&#xff09;&#xff0c;还要能够在常数时间内&#xff08;O(1) 时间复杂度&#xff09;获取栈中的最小元素&#xff08;getMin&#xff…

算法题总结(十五)——贪心算法(下)

1005、K 次取反后最大化的数组和 给你一个整数数组 nums 和一个整数 k &#xff0c;按以下方法修改该数组&#xff1a; 选择某个下标 i 并将 nums[i] 替换为 -nums[i] 。 重复这个过程恰好 k 次。可以多次选择同一个下标 i 。 以这种方式修改数组后&#xff0c;返回数组 可…