我正在使用JSP开发谷歌应用引擎。我需要通过String类中的startsWith()方法比较两个字符串。
以下是我正在处理的代码。
<%
String artist = "Surendra Perera";
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key songKey = KeyFactory.createKey("songs", 123454);
// Run an ancestor query to ensure we see the most up-to-date
// view of the songs.
Query query = new Query("Song", songKey).addSort("Artist");
//query.addFilter("Artist", Query.FilterOperator.IN, "Milton Mallawarachchi");
List<Entity> songsList = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(30));
if(songsList.isEmpty()){
%>
<p>There are no songs</p>
<%
}else{
%>
<ul class="playlist">
<%
for(Entity song : songsList){
if(artist.startsWith(song.getProperty("Artist"))){
%>
<li><a href="<%= song.getProperty("Link") %>"><%= song.getProperty("Title") %>  <span class="comment"><%= song.getProperty("Artist") %></span></a></li>
<% }}} %>
这是我得到的错误......
HTTP ERROR 500
Problem accessing /search.jsp. Reason:
Unable to compile class for JSP:
An error occurred at line: -1 in the generated java file
[javac] C:\DOCUME~1\SILICO~1\LOCALS~1\Temp\Jetty_127_0_0_1_8888_war____.g0qk00\jsp\org\apache\jsp\search_jsp.java:178: cannot find symbol
[javac] symbol : method startsWith(java.lang.Object)
[javac] location: class java.lang.String
[javac] if(artist.startsWith(song.getProperty("Artist"))){
[javac] ^
[javac] 1 error
Stacktrace:
Caused by:
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: -1 in the generated java file
[javac] C:\DOCUME~1\SILICO~1\LOCALS~1\Temp\Jetty_127_0_0_1_8888_war____.g0qk00\jsp\org\apache\jsp\search_jsp.java:178: cannot find symbol
[javac] symbol : method startsWith(java.lang.Object)
[javac] location: class java.lang.String
[javac] if(artist.startsWith(song.getProperty("Artist"))){
[javac] ^
[javac] 1 error
提前致谢!
答案 0 :(得分:4)
错误告诉它无法在method startsWith(java.lang.Object)
类中找到给定的方法String
。请注意,错误显示java.lang.Object
作为方法参数。这确实是错的。它必须是java.lang.String
,另请参阅javadoc。
您必须将song.getProperty()
的返回类型从Object
更改为String
:
public String getProperty(String name) {
// ...
}
或在(String)
上添加强制转型,如果它是{em>实际的String
类型:
if (artist.startsWith((String) song.getProperty("Artist"))) {
// ...
}
或使用值得信赖的Javabean:
public String getArtist() {
return artist;
}
与
if (artist.startsWith(song.getArtist())) {
// ...
}
最后但同样重要的是,此问题与JSP 无关。在普通的Java类中执行此操作时,您会遇到完全相同的问题。在JSP文件中编写Java代码是not the best way,以使基本概念正确。