0

I am brand new to Java so please keep that in mind if this is a stupid or repeated question.

I have created a very simple jsp page(index.jsp) that has several text input fields where a user will input first and last names, a servlet that creates class instances(called Person) based on the input, saves them to an Array List and redirects to a second jsp page where the inputs are displayed.

Currently I have the "name" attribute in the input fields set to "nameN" on all input fields where N is the respective number:

<label for="name1">Name 1:</label><br>
      <input type="text" required placeholder="Firstname Lastname" name="name1" id="name1">
      <br> 
      <label for="name2">Name 2:</label><br>
      <input type="text" required placeholder="Firstname Lastname" name="name2" id="name2">
      <br> 
      <label for="name3">Name 3:</label><br>
      <input type="text" required placeholder="Firstname Lastname" name="name3" id="name3">
      <br>
...etc

and I'm able to iterate over them and create new class instances for each input field.

However, If I change the order of the inputs to something more 'random':

<label for="name5">Name 5:</label><br>
      <input type="text" required placeholder="Firstname Lastname" name="name5" id="name5">
      <br> 
      <label for="name3">Name 3:</label><br>
      <input type="text" required placeholder="Firstname Lastname" name="name3" id="name3">
      <br>
      <label for="name1">Name 1:</label><br>
      <input type="text" required placeholder="Firstname Lastname" name="name1" id="name1">
      <br>
      ...

The objects are saved in the same order: name5, name3, name1 etc.

I'd like to have them sorted in order based on the name attribute. So it will always display "name1, name2, name3" regardless of the input order.

I figure a loop is my best bet but I can't figure out how to loop through user input fields and check if the info has been saved. Another option would be to do a comparison in the class itself but I can't seem to get that to work either.

Any help would be greatly appreciated.

Here is the relevant code:

index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
    <head>
      <title>Sample Application JSP Page</title>
    </head>
  
    <body bgcolor=white>
  
    <table border="0" cellpadding="10">
      <tr>
        <td align=center>
          <img src="images/thumbs.jpg">
        </td>
        <td>
           <h1>Sample Application JSP Page</h1>
        </td>
      </tr>
    </table>
  
    <br />
  
    <form action="ReverseServlet" method="POST">
      <!-- <h3>Please enter any text:</h3>
      <input type="text" name="testText" id="testText">
      <br>
      <br>  -->
      <h3>Please enter names:</h3>
      <label for="name5">Name 5:</label><br>
      <input type="text" required placeholder="Firstname Lastname" name="name5" id="name5">
      <br> 
      <label for="name3">Name 3:</label><br>
      <input type="text" required placeholder="Firstname Lastname" name="name3" id="name3">
      <br> 
      <label for="name4">Name 4:</label><br>
      <input type="text" required placeholder="Firstname Lastname" name="name4" id="name4">
      <br>  
      <label for="name6">Name 6:</label><br>
      <input type="text" required placeholder="Firstname Lastname" name="name6" id="name6">
      <br>
      <label for="name1">Name 1:</label><br>
      <input type="text" required placeholder="Firstname Lastname" name="name1" id="name1">
      <br> 
      <label for="name8">Name 8:</label><br>
      <input type="text" required placeholder="Firstname Lastname" name="name8" id="name8">
      <br>
      <label for="name2">Name 2:</label><br>
      <input type="text" required placeholder="Firstname Lastname" name="name2" id="name2">
      <br>
      <label for="name7">Name 7:</label><br>
      <input type="text" required placeholder="Firstname Lastname" name="name7" id="name7">
      <br>
      
      <input type="submit" value="Submit"> 
    </form>
    </body>
  </html> 

Person.java:

//Java Person class file

package examples;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.*;
import java.lang.*;
import static java.lang.System.*;
import java.io.*;
import java.util.*;
import java.util.Comparator;
import java.nio.charset.StandardCharsets;

public class Person implements Comparable{
    private String firstName = null;
    private String lastName = null;
    //private static int nextIndex = 1;
    private String index;

    public Person(){
        // index = nextIndex;
        // nextIndex++;
    }
    public String getFirstName() {
        return firstName;
    }

    public String getIndex() {
        return index;
    }

    public String getLastName() {
        return lastName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public void setIndex(String Index) {
        this.index = index;
    }

    // public static Comparator<Person> PersonComparator = new Comparator<Person> {

    //     public int compare(Person p1, Person p2) {
    //         String PersonIndex1 = p1.getIndex().toUpperCase();
    //         String PersonIndex2 = p2.getIndex().toUpperCase();

    //         return PersonIndex1.compareTo(PersonIndex2);
    //     }
    // }

    @Override
    public int compareTo(Person other){
        String compareiId = ((Person)other).getIndex();
        return this.Index - compareiId;
    }



} 

ReverseServlet.jsp

package examples;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.*;
import java.lang.*;
import static java.lang.System.*;
import java.io.*;
import java.util.*;
import java.nio.charset.StandardCharsets;
 
public class ReverseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        
        String randText = request.getParameter("testText");

        HttpSession session = request.getSession();

         ArrayList<Person> names = new ArrayList<Person>();


        /**
         * ///////////////////////////////
         * Code below goes through all input fields and 
         * creates a new class instance each time.
         * Better than the for-loop because now the 'name'
         * of the jsp element doesn't have to be "name",
         *  it can be numbered and it won't effect anything
         * ///////////////////////////////
         */   
        int id = 1;
        int something = id;
        String strID = Integer.toString(something);
        String el = "name".concat(strID);

        Enumeration e = request.getParameterNames();

 
        while(e.hasMoreElements()) {
            Object obj = e.nextElement();
            String fieldName = (String) obj;
            String fieldValue = request.getParameter(fieldName);

            String[] result = fieldValue.split(" ");
            person.setFirstName(result[0]);
            person.setLastName(result[1]);
            names.add(person);
            //++id;


            // COME BACK TO THIS IF SORT DOESN'T WORK

            // if(fieldName.equals("name" + strID)){

            //     Person person = new Person();

            //     String[] result = fieldValue.split(" ");
            //     person.setFirstName(result[0]);
            //     person.setLastName(result[1]);
            //     names.add(person);
            //     //names.add(person);
            //     ++id;
            // }



        }

        

        Collections.sort(names, Person.PersonComparator);

        session.setAttribute("testPerson", names);



        response.sendRedirect ("hello.jsp");
    }
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
P. Izzo
  • 25
  • 7
  • I found the abovelinked duplicate via https://google.com/search?q=how+to+sort+arraylist+java+site:stackoverflow.com Try the same the next time :) – BalusC Dec 10 '20 at 15:34
  • My apologies, was googling and kept getting deeper in the weeds without finding a solution. Thank you for your help @BalusC ! – P. Izzo Dec 10 '20 at 15:39

0 Answers0