Измените вывод HTML с Java - PullRequest
0 голосов
/ 18 марта 2020

У меня есть следующий код:

@Controller
public class GatesController {

    @RequestMapping ("/gates")

    public static String qualityGates(String x) throws IOException {
        try {
            System.out.println("\n------QualityGates------");
            URL toConnect = new URL(x);
            HttpURLConnection con = (HttpURLConnection) toConnect.openConnection();
            System.out.println("Sending 'GET' request to URL : " + x);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }

            in.close();

            //Cast the JSON-File to a JSONObject
            JSONObject res = new JSONObject(response.toString());
            JSONArray gates = new JSONArray(res.getJSONObject("projectStatus").getJSONArray("conditions").toString());
            JSONObject test = new JSONObject(res.getJSONObject("projectStatus").toString());

            String a = ("\nThe current Project-Status is: " + test.get("status") + "\n");
            String b = "";
            for (int i = 0; i < gates.length(); i++) {
                String status = gates.getJSONObject(i).getString("status");
                String metric = gates.getJSONObject(i).getString("metricKey");
                b = b + ("<\b>Status: " + status + " | Metric: " + metric);

            }

            System.out.println(a+b);
            return a + b;
        } catch (Exception e) {
            System.out.println(e);
            return String.format("Error");
        }
    }

@SpringBootApplication
@RestController
public class SonarQualityGatesApplication {

    public static void main(String[] args) throws IOException {
        ConfigurableApplicationContext context=SpringApplication.run(SonarQualityGatesApplication.class, args);
        TestController b = context.getBean(TestController.class);


    }

    @GetMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
        return String.format("Hello %s!", name);
    }

    @GetMapping("/gates")
    public String gates() throws IOException {
        String temp = qualityGates("http://localhost:9000/api/qualitygates/project_status?projectKey={PROJECT_KEY}");
        return temp;
    }

}

Проблема в настоящее время веб-сайт выглядит следующим образом:

Website_Curr

Но я хочу новую строку для каждого показателя c, а не в одном ряду. Как видите, я попытался добавить <\ b> в коннотации строки. У вас есть идея, как это исправить? Это мое первое веб-приложение, которое я немного застрял.

Я ценю любую помощь!

1 Ответ

0 голосов
/ 18 марта 2020

Ваш "<\ b>" ломает его. Если вы удалите его и добавите новую строку "\ n", она должна работать. Вот так:

String a = ("\nThe current Project-Status is: " + test.get("status") + "\n");
String b = "";
for (int i = 0; i < gates.length(); i++) {
   status = gates.getJSONObject(i).getString("status");
   String metric = gates.getJSONObject(i).getString("metricKey");
   b = b + ("Status: " + status + " | Metric: " + metric + "\n");
}

Также вы возвращаете простой текст. Таким образом, чтобы отобразить его правильно, добавьте «yield =" text / plain "для возврата отформатированной строки.

@GetMapping(value = "/gates", produces = "text/plain")

Тогда ваш вывод будет отображаться с переносами строк. Таким образом, вы можете применить дальнейшее форматирование.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...