So my servlet is reading a url link from another servlet and then publishing the article associated with it. All the articles are in a single .txt file with each article on its own separate line. So I have made the first URL link work properly but I can't get the 2nd to work properly. The problem is if I use a loop like while( br.readline() != null)
then it will display all 3 articles instead of just the article whos URL I clicked on. When I don't loop it and just use br.readline()
it stops at the first line and doesn't move to the second line like I need it to if I'm asking for URL 2 or URL 3. Here is my code:
s = br.readLine();
out.println("<tr>");
StringTokenizer s2 = new StringTokenizer(s, "|");
if (request.getParameter("article1") != null){
while (s2.hasMoreElements()){
if (index == 0){
out.println("<td class='first'>"+s2.nextElement()+"</td>");
}
else if (index == 1){
out.println("<td>"+s2.nextElement()+"</td>");
}
else if (index == 2){
out.println("<td>"+s2.nextElement()+"</td>");
}
else if (index == 3){
out.println("<td>"+s2.nextElement()+"</td>");
}
index++;
out.println("</tr>");
}
}
else if (request.getParameter("article2") != null){
s = br.readLine();
while (s2.hasMoreElements()){
if (index == 4{
out.println("<td class='first'>"+s2.nextElement()+"</td>");
}
else if (index == 5){
out.println("<td>"+s2.nextElement()+"</td>");
}
else if (index == 6){
out.println("<td>"+s2.nextElement()+"</td>");
}
else if (index == 7){
out.println("<td>"+s2.nextElement()+"</td>");
}
index ++;
out.println("</tr>");
}
I know this is probably just a stupid coding error that I can't see because I've been looking at it for so long, but I can't seem to get it to do what I want it to. Also I didn't show the article 3 code because it is essentially the same, and if I can fix article 2's code, then article 3's will basically be the same.
I would strongly advise you to separate out the "reading the data" from the "outputting HTML" sections of your code.
It looks like you should create a data structure for an article, with properties for whatever the different bits in each line are. You can then:
List<Article>
Article
(e.g. via splitting as per your code)Article
to the listYou now have a List<Article>
which you can use in any way you like in the part of your code which needs to output HTML. You don't need to worry about mixing the line-reading and parsing with the output code. This should make it all much simpler to handle.
See more on this question at Stackoverflow