java if语句不一致性
在bean中有一个java if语句不一致性,java,jsp,jstl,javabeans,Java,Jsp,Jstl,Javabeans,在bean中有一个if语句,在创建测试java类时,该语句似乎处理得很好,但在jsp调用该bean时却不能正常工作 我的代码,让我向您展示: 首先,测试类: package com.serco.inquire; import java.util.*; import java.text.*; public class TestCollection { public static void main(String[] args) { IrCollection myColle
if
语句,在创建测试java类时,该语句似乎处理得很好,但在jsp调用该bean时却不能正常工作
我的代码,让我向您展示:
首先,测试类:
package com.serco.inquire;
import java.util.*;
import java.text.*;
public class TestCollection {
public static void main(String[] args) {
IrCollection myCollection = new IrCollection();
myCollection.setSort("none");
myCollection.setMgrid("none");
int endpoint = myCollection.getSize();
for (int i=0;i<endpoint;i++) {
InquireRecord curRec = myCollection.getCurRecords(i);
Long milis = new Long(curRec.getSubmitDate());
Date theDate = new Date(milis);
Format formatter = new SimpleDateFormat("dd MMM yyyy");
String s = formatter.format(theDate);
System.out.println("ID: " + curRec.getID() + " | Subject: " + curRec.getSubject());
}
}
}
另一个方法中有更多的代码使用以下方法调用此特定方法:
this.processSort(this.sort);
但问题是第二个代码示例中的if(datum==“none”)
部分。假定第一个类的第10行将成员变量sort设置为“none”
,则processSort()
方法应将成员变量fullSort
设置为“ORDER BY lastUpdated DESC”
如果我在第一个示例中使用这个类,它就会这样做
然而
我有这个自定义标签:
<%@ tag body-content="scriptless" import="com.serco.inquire.*" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ attribute name="mgr" required="true" %>
<%@ attribute name="mkind" required="false" %>
<%@ attribute name="sort" required="false" %>
<c:if test="${empty mkind}">
<c:set var="mkind" value="manager" />
</c:if>
<c:if test="${empty sort}">
<c:set var="sort" value="none" />
</c:if>
<jsp:useBean id="irc" scope="page" class="com.serco.inquire.IrCollection">
<jsp:setProperty name="irc" property="mgrtype" value="${mkind}" />
<jsp:setProperty name="irc" property="sort" value="${sort}" />
<jsp:setProperty name="irc" property="mgrid" value="${mgr}" />
</jsp:useBean>
${irc.fullsort}
${irc.fullsort}
.jsp文件通过以下方式调用:
<c:set var="user" value="none" />
<c:set var="sort" value="none" />
<inq:displayCollection>
<jsp:attribute name="mgr">${user}</jsp:attribute>
<jsp:attribute name="mkind">cotr</jsp:attribute>
<jsp:attribute name="sort">${sort}</jsp:attribute>
</inq:displayCollection>
${user}
cotr
${sort}
换句话说,完全相同的数据被馈送到IrCollection bean。所以我应该得到同样的数据,对吗
除了我得到这个:
其中cotr=非DES的“无”订单
所以当Java调用它时,它认为“none”==“none”
,但当jsp调用它时,它认为“none”!=“无”
基准==“无”是错误的。你想要
datum.equals("none");
string==运算符仅比较指针位置,而不是字符串的实际值。因此,它在某些情况下(如果数据是用常量字符串设置的)有效,但在动态创建时无效。您必须使用
等于而不是=
:
datum.equals(“无”)
请参阅使用equals进行字符串比较我更喜欢使用,equals()
方法,而不是比较引用变量,它可能会在相同的情况下给出正确的结果,但是应该检查字符串在逻辑上是否相等。我认为您的问题是Java中的对象相等。正如其他人提到的,您应该使用equals()
。类的编译器可能会为文本的每个实例创建一个共享字符串(如“none”)。这将导致==
,它检查两个变量是否指向同一个对象,如果字符串是从类中分配的。然后,当您使用JSP页面时,“none”字符串由外部类提供,从而使其成为不同的对象
这个故事的寓意是使用“equals()”来比较字符串。还有。。。为什么这个论坛忽略了我的代码缩进?--nm,修复了它。在java中不要将==与字符串一起使用。使用。相等是的。。。刚刚注意到。那个回来答谢。谢谢大家的回答。
datum.equals("none");