如何将数据从表单发送到后端? [Java]

时间:2019-05-21 12:35:57

标签: java json spring model-view-controller

如何将数据从表单视图发送到后端?我想使用收集的数据创建JSON请求。

@Controller
public class ControllerClass {

    Connect connect = new Connect();

    @RequestMapping(value = "/Search", method = RequestMethod.GET)
    public ModelAndView showForm() {
        return new ModelAndView("Forms", "FlightDTO", new FlightDTO());
    }

    @RequestMapping(value = "/connect", method = RequestMethod.POST)
    public String submit(@Valid @ModelAttribute("FlightDTO") FlightDTO flightDTO,
                         BindingResult result, ModelMap model) {
        if (result.hasErrors()) {
            return "error.jsp";
        }
        return connect.connect();
    }
}

查看收集数据的类。

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Handling Form Submission</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="@{/connect}" th:object="${FlightDTO}" method="post">
    <p>Orgin: <input type="text" th:field="*{Origin}" /></p>
    <p>Departure: <input type="text" th:field="*{Departure}" /></p>
    <p>DateFrom: <input type="text" th:field="*{DateFrom}" /></p>
    <p>DateTo: <input type="text" th:field="*{DateTo}" /></p>
    <p>Currency: <input type="text" th:field="*{Currency}" /></p>



    <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>

负责消费数据JSON的类。

public class Connect  {

    public String connect() {
        String output = null;

        try {
            UrlBuilder urlBuilder = new UrlBuilder();
            urlBuilder.ulr();

            System.out.println("URL String : " + urlBuilder.ulr());
            URL url = new URL(urlBuilder.ulr());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection() ;
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP Error code : " + conn.getResponseCode());
            }

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            output = response.toString();
        } catch (Exception e) {
            System.out.println("Exception Flight:- " + e);
        }


        return output;
    }
}

负责从视图中收集数据的类

public class FlightDTO {
    private String dateFrom;

private String dateTo;

@Size(min = 2, max = 10)
private String origin;
@Size(min = 2, max = 10)
private String departure;
@Size(min = 2, max = 4)
private String currency;

我的URL构建器类负责构建请求。

public class UrlBuilder extends FlightDTO {

    private String key = "47c5ebee552ce27c902e7521b6ef3858";


    public String ulr( ) {
        String connectUrlString =
                "http://api.travelpayouts.com/v1/prices/cheap?origin="
                        + getOrigin() + "&destination=" + getDeparture() +
                        "&depart_date=" + getDateFrom() +
                        "&currency=" + getCurrency() +
                        "&return_date=" + getDateTo() +
                        "&token=" + key;
        return connectUrlString ;
    }



}

我试图以多种方式解决我的问题。不幸的是,这无济于事,所以我决定创建一个线程。我找不到类似的问题。我可能正在寻找一个坏的。但是,我不知道如何谷歌

我得到空响应:

http://api.travelpayouts.com/v1/prices/cheap?origin=null&destination=null&depart_date=null&currency=null&return_date=null&token=47c5ebee552ce27c902e7521b6ef3858

1 个答案:

答案 0 :(得分:1)

上面的代码将不起作用,因为您正在创建新的UrlBuilder对象,该对象将没有任何值,而不是从控制器传递flightDTO对象。

  

控制器

@RequestMapping(value = "/connect", method = RequestMethod.POST)
    public String submit(@Valid @ModelAttribute("FlightDTO") FlightDTO flightDTO,
                         BindingResult result, ModelMap model) {
        if (result.hasErrors()) {
            return "error.jsp";
        }
        return connect.connect(flightDTO); //passing flightDTO object received from form
    }
  

连接

public String connect(FlightDTO flightDTO) { //Added new parameter to recevice flightDTO
        String output = null;

        try {
            UrlBuilder urlBuilder = new UrlBuilder();
            urlBuilder.setOrigin(flightDTO.getOrigin());
            urlBuilder.setDestination(flightDTO.getDestination());
            urlBuilder.setDateFrom(flightDTO.getDateFrom());
            urlBuilder.setDateTo(flightDTO.getDateTo());
            ......//Set other required values
            urlBuilder.ulr();

            System.out.println("URL String : " + urlBuilder.ulr());
            ......//other code    
        }
}