0

This is the Controller page:

@Controller public class AppController {

@Autowired
private UserRepository userRepo;

@GetMapping("")
public String viewHomePage() {
    return "index";
}

@GetMapping("/index")
public String logoutPage() {return "index";}

@GetMapping("/menu")
public String menuPage() {return "menu";}

@GetMapping("/register")
public String showRegistrationForm(Model model) {
    model.addAttribute("user", new User());

    return "signup_form";
}

@PostMapping("/process_register")
public String processRegister(User user) {
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    String encodedPassword = passwordEncoder.encode(user.getPassword());
    user.setPassword(encodedPassword);

    userRepo.save(user);

    return "menu";
}

@GetMapping("/users")
public String listUsers(Model model) {
    List<User> listUsers = userRepo.findAll();
    model.addAttribute("listUsers", listUsers);

    return "users";
}

public  List<Troops> getTroops() {
    List<Troops> TroopList = new LinkedList<>();
    try {
        // File path to the XML file.
        Path filePath = Paths.get("C:\\Users\\amani\\OneDrive\\WYWM\\Java\\Capstone 1\\dataset.xml");
        File file = new File(String.valueOf(filePath.toAbsolutePath()));

        if (file.exists()) {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse(String.valueOf(filePath.toAbsolutePath()));
            // Reads the XML tagName of full_name and id.
            NodeList[] user = { document.getElementsByTagName("full_name"), document.getElementsByTagName("id") };

            for (int i = 0; i < user[0].getLength(); i++) {

                String fullName = user[0].item(i).getTextContent();
                int id = Integer.parseInt(user[1].item(i).getTextContent());
                Troops newTroop = new Troops(fullName, id);
                TroopList.add(newTroop);
            }
        } else {
            System.out.println("File not found");
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    // Returns the TroopList with data from the XML file.
    return TroopList;

}




@RequestMapping(value = "/numasc", method = RequestMethod.GET)
@ResponseBody
public List<Troops> getNumAsc( ) {
    List<Troops> ascList = new LinkedList<Troops>();
    ascList.addAll(getTroops());
    ascList.sort((u1, u2) -> u1.getId() - u2.getId());
    return ascList;
}

When run the above - I get the following:

[{"fullName":"Maridel MacCostye","id":1},{"fullName":"Phineas Bonnet","id":2},{"fullName":"Oates McGillivray","id":3},{"fullName":"Curtice Comelli","id":4},{"fullName":"Phillis Wontner","id":5},{"fullName":"Bradley Hasell","id":6},{"fullName":"Carling Cokely","id":7},{"fullName":"Bertrand Samms","id":8},{"fullName":"Chiarra Trill","id":9},{"fullName":"Willie Balmadier","id":10},

but my html page for "/numasc" looks like this:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
  <meta charset="ISO-8859-1">
  <title>Soldiers Deployed</title>
  <link rel="stylesheet" type="text/css" href="/webjars/bootstrap/css/bootstrap.min.css" />
  <script type="text/javascript" src="/webjars/jquery/jquery.min.js"></script>
  <script type="text/javascript" src="/webjars/bootstrap/js/bootstrap.min.js"></script>
</head>

<body>
<div class="container text-center">
  <div>
    <form th:action="@{/logout}" method="post">
      <p>
        Welcome <b>[[${#request.userPrincipal.principal.fullName}]]</b>
      </p>
      <input type="submit" value="Sign Out" />
    </form>
  </div>
  <div>
    <h1>Soldiers Deployed</h1>
  </div>

  <div>

    <table class="table table-striped table-bordered">
      <thead class="thead-dark">
      <tr>
        <th>ID</th>
        <th>Full Name</th>

      </tr>
      </thead>
      <tbody>

      <a th:href="@{/menu}" class="button primary">Back to Menu</a>

      <tr th:each=" ${ascList}">
        <td th:text=${ascList.id}>ID</td>>
        <td th:text=${ascList.fullName}>Full name</td>>
      </tr>
      </tbody>
    </table>
  </div>
</div>
</body>

</html>

Apart from having a table, my html pages are similiars and they are all working fine. I don't understand why the html page isn't being picked up.

1

2 Answers 2

1

Try removing the @ResponseBody tag.

@RequestMapping(value = "/numasc", method = RequestMethod.GET)
@ResponseBody
public List<Troops> getNumAsc( ) {
    List<Troops> ascList = new LinkedList<Troops>();
    ascList.addAll(getTroops());
    ascList.sort((u1, u2) -> u1.getId() - u2.getId());
    return ascList;
}

Instead use:

@RequestMapping(value = "/numasc", method = RequestMethod.GET)
public String getNumAsc(Model m) {
    List<Troops> ascList = new LinkedList<Troops>();
    ascList.addAll(getTroops());
    ascList.sort((u1, u2) -> u1.getId() - u2.getId());
    m.addAttribute("ascList", ascList);
    return "numsac";
}
Sign up to request clarification or add additional context in comments.

7 Comments

If I remove it I then get this error: Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. And then about 100 lines which stack over isn't allowing me to post
change the return type to String for the getNumAsc() method and in the return statement specify the name of the html file you want to be loaded when you call /numasc. When you use @ResponseBody, it returns the HTML file as a response body not a HTML file.
it then gives this error: Error resolving template [ascList], template might not exist or might not be accessible by any of the configured Template Resolvers org.thymeleaf.exceptions.TemplateInputException: Error resolving template [ascList], template might not exist or might not be accessible by any of the configured Template Resolvers
what is the name of the html file you want to be returned?
@RequestMapping(value = "/numasc", method = RequestMethod.GET) public String getNumAsc( ) { List<Troops> ascList = new LinkedList<Troops>(); ascList.addAll(getTroops()); ascList.sort((u1, u2) -> u1.getId() - u2.getId()); return "{name_of_your_html_file}"; }
|
0

modified according to your working html routes...

@RequestMapping(value = "/numasc", method = RequestMethod.GET)
public String getNumAsc(Model model) {
    List<Troops> ascList = new LinkedList<Troops>();
    ascList.addAll(getTroops());
    ascList.sort((u1, u2) -> u1.getId() - u2.getId());

    model.addAttribute("ascList", ascList);

    return "numask";
}

4 Comments

is the return "numask" a type - did you mean to put numasc which is the same as the html file?
There is no more error and now I can see a table but the table is empty. I have put this in the html file: <tr th:each="ascList:${ascList}">
I figured it out - your answers really helped me understand it a lot better - thank you so much
numask ist the template name (html file)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.