gpt4 book ai didi

java - 使用 getOrDefault() 时,我没有获得默认值

转载 作者:太空宇宙 更新时间:2023-11-04 12:25:41 26 4
gpt4 key购买 nike

如果我在文本框页面中提供一些值,那么我会得到正确的输出,但如果我没有在文本框中提供任何值,我希望它将打印默认值。

为此,我使用 Map 类的 getOrDefault() 方法,但仍然没有获得默认值。

StudentAdmissionController.java

package com.diwakar;

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class StudentAdmissionController {

@RequestMapping(value="/admission.html", method = RequestMethod.GET)
public ModelAndView getAdmissionForm() {

ModelAndView model = new ModelAndView("AdmissionForm");
return model;
}

@RequestMapping(value="/submitForm", method = RequestMethod.POST)
public ModelAndView submitAdmissionForm(@RequestParam Map<String, String> reqParm) {

String name = reqParm. ("studentName", "Default Name");
String hobby = reqParm.getOrDefault("studentHobby", "Default Hobby");

ModelAndView model = new ModelAndView("AdmissionSuccess");
model.addObject("msg", "Details submitted by you, Name : " + name + " and hobby is : " + hobby);
return model;
}
}

spring-dispatcher-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">



<!-- <bean id="HandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<bean name="/welcome.html" class="com.diwakar.HelloController" /> -->

<context:component-scan base-package="com.diwakar" />
<mvc:annotation-driven />

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp"></property>
</bean>
</beans>

输出是

恭喜!详细信息已提交。

您提交的详细信息,姓名:和爱好:

而不是

最佳答案

getOrDefault仅当没有映射时才返回默认值,您可能有一个到空字符串的映射,您应该检查自定义代码,也许构建一个方法:

private static String getOrDefaultIfEmpty(Map<String,String> map, String key, String def)
{
String v = map.get(key);
return v==null || v.length()==0 ? def : v;
}

您需要执行此检查,因为空 HTML 文本框会发送一个创建映射的空字符串作为参数,因此您不会获得默认值,而是会获得一个空字符串。

关于java - 使用 getOrDefault() 时,我没有获得默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38420188/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com