Home > Mobile >  How to communicate with spring boot without creating a webpage?
How to communicate with spring boot without creating a webpage?

Time:08-21

I might be asking a really dumb question here. I am trying to learn Spring boot and I have created a rest controller, and with a simple HTML I am able to do post and get.

As I am mainly coding in Java, I do not have much knowledge on frontend development like php/html/javascript etc. Is it possible to test and develop codes using JFrames and JButtons etc?

The sample code below shows that when I run a JFrame, when clicking on the JButton, I wish to send the inputs in the textfield to my "PersonController".

Person Class:

@Entity
public class Person {
    String lastName;
    String firstName;

    public Person(String lastName, String firstName) {
        super();
        this.lastName = lastName;
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

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

    public String getFirstName() {
        return firstName;
    }

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

Rest Controller:

@RestController
public class PersonController {

    private final PersonService personService;

    @Autowired
    public PersonController(PersonService service) {
        this.personService = service;
    }

    // ------- THIS IS THE METHOD I WANT TO CALL WHEN THE BUTTON IS CLICKED
    @PostMapping("/add")
    public void addPerson(@RequestBody Person person) {
        this.personService.handleNewPerson(person);
    }
}

UI Using Java:

public class MainClass {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Test Frame");
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));

        JLabel lastNameLabel = new JLabel("Last name: ");
        JTextField lastNameTextfield = new JTextField(50);

        JLabel firstNameLabel = new JLabel("First name: ");
        JTextField firstNameTextfield = new JTextField(50);

        JPanel firstNamePanel = getInputPanel(firstNameLabel, firstNameTextfield);
        JPanel lastNamePanel = getInputPanel(lastNameLabel, lastNameTextfield);

        JButton button = new JButton("Click me");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // ------ Pack and send firstname/lastname to my rest controller
            }
        });

        p.add(lastNamePanel);
        p.add(firstNamePanel);
        p.add(button);

        frame.add(p);

        frame.pack();
        frame.setVisible(true);
    }

    private static JPanel getInputPanel(JLabel label, JTextField tf) {
        JPanel panel = new JPanel(new FlowLayout());
        label.setPreferredSize(new Dimension(100, label.getPreferredSize().height));

        panel.add(label);
        panel.add(tf);
        return panel;
    }
}

Is this even possible? Or in order for me to properly learn how to code using Spring boot, or to develop my own simple project, I'd also have to learn how to create webpages etc?

------------------------------------------ Edit: ----------------------------------------------

To further explain why I am doing this, one example is when I have a simple HTML(index.html), and do a post with user's first/last name input, I am unable to parse first/last name into "Person" json without the use of javascript(which I currently do not have knowledge on). Example below:

index.html

    <form action="add" method="POST">
        <div><label>Last Name:</label> <input name="lastName" type="text" value="" /></div>
        <div><label>First Name:</label> <input name="firstName" type="text" value="" /></div>
        <button>Add Manga</button>
    </form>

If my method takes in params as first and last name it would work:

@PostMapping("/add")
public void addManga(@RequestParam(name = "lastName") String lastName, @RequestParam(name = "firstName") String firstName) {
    Student student = new Student(lastName, firstName);
    this.personService.handleNewPerson(person);
}

But if my method takes in the Person object, the form post wouldn't work unless I parse it into a json?

@PostMapping("/add")
public void addPerson(@RequestBody Person person) {
    this.personService.handleNewPerson(person);
}

CodePudding user response:

It is really not obvious to me from the way the question is stated, but it kind of looks like you are thinking of including Swing (desktop UI) classes as a frontend to the Spring Boot server within the same application. Which is possible, but entirely backwards way of approaching the problem given gains vs effort put into the solution. Plus it makes for a really weird choice - why even use Spring Boot REST controllers if your input is controlled by Swing GUI?

More reasonable way of understanding your intention is that besides writing a Spring Boot server you are thinking of writing a separate client application, that is supposed to execute REST requests mapped to buttons, etc. This is OK, if your main focus is this client application, but if it is for testing, and your goal is to learn Spring Boot, it still seems a bit too much effort versus the expected gains. After all, it would effectively create your own REST client app, when there are already existing solutions like Postman and for many usecases, even regular browser is sufficient.

I would suggest an alternative solution that creates an easy to use HTML frontend automatically, with no additional maintenance requirement: include springdoc in your project.

Since this is a Spring Boot project, there is a lot of autoconfiguration alredy happening behind your back, and you only need to include the single maven/gradle dependency.

<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-ui</artifactId>
  <version>1.6.10</version>
</dependency>

Then after starting the application, visit the auto-generated frontend on (if using Spring defaults) http://localhost:8080/swagger-ui/index.html#/

CodePudding user response:

I assume you want to make a rest call from the action listener. You would have create an instance of a Rest-template and then call make a request to you controller . details of how to use a Rest-template can be found here

https://www.baeldung.com/rest-template

Official documentation from spring : https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#rest-client-access.

You are also welcome to use any http client available out there. An example is https://github.com/OpenFeign/feign

  • Related