{"id":1561,"date":"2015-10-26T00:07:30","date_gmt":"2015-10-25T23:07:30","guid":{"rendered":"http:\/\/codingexplained.com\/?p=1561"},"modified":"2015-10-26T00:04:51","modified_gmt":"2015-10-25T23:04:51","slug":"replace-newline-characters-java-jstl","status":"publish","type":"post","link":"https:\/\/codingexplained.com\/coding\/java\/replace-newline-characters-java-jstl","title":{"rendered":"Replacing Newline Characters in Java and JSTL"},"content":{"rendered":"<p>In this article, we will take a look at how we can replace newline characters in Java. Additionally, we will implement a custom JSTL tag so that we can replace newline characters with corresponding <span class=\"code\">&lt;br \/&gt;<\/span> break lines within JSP files. Unlike PHP&#8217;s <span class=\"code\">nl2br<\/span> function, for instance, this is not as easy in JSTL.<\/p>\n<h2>Replacing or Removing Newlines in Java<\/h2>\n<p>First, let&#8217;s see how we can replace newline characters in plain Java. It is very important to <a href=\"http:\/\/stackoverflow.com\/questions\/3516957\/how-do-i-use-system-getpropertyline-separator-tostring#answer-3519883\" title=\"Newline separators for different platforms\" target=\"_blank\" rel=\"external nofollow\">account for different newline separators<\/a> for different platforms (and when moving data between platforms). Luckily, Java&#8217;s <span class=\"code\">java.util.Scanner<\/span> does just that for us, and this is very convenient, because it saves us some time dealing with this ourselves. With the <span class=\"code\">java.util.Scanner<\/span> utility, we simply make use of its <span class=\"code\">nextLine<\/span> method and iterate through each line.<\/p>\n<pre>\r\npublic final class GeneralUtils {\r\n    private GeneralUtils() { }\r\n\r\n    \/**\r\n     * Replaces all occurrences of newlines within a string with the HTML break line\r\n     *\r\n     * @param input The string to add HTML break lines to\r\n     * @return The input string with HTML break lines instead of newlines\r\n     *\/\r\n    public static String nl2br(String input) {\r\n        Scanner scanner = new Scanner(input);\r\n        List<String> lines = new ArrayList<>();\r\n\r\n        do {\r\n            lines.add(scanner.nextLine());\r\n        } while (scanner.hasNextLine());\r\n\r\n        return String.join(\"&lt;br \/&gt;\", lines);\r\n    }\r\n}\r\n<\/pre>\n<p>I have wrapped the above method within a utility class for convenience. What the method does is to simply iterate through the lines in the input and add it to an <span class=\"code\">ArrayList<\/span>. After iterating through all of the lines (thus having split the input), the list elements are joined together with the <span class=\"code\">&lt;br \/&gt;<\/span> break line tag, effectively replacing the newline characters.<\/p>\n<p>This method replaces the newlines with HTML break lines, but you can of course modify it to replace it with whatever you would like, such as an empty string, in case you simply want to remove the newline characters. To use the utility method, simply do as below.<\/p>\n<pre>\r\nString split = GeneralUtils.nl2br(\"Some input\");\r\n<\/pre>\n<h2>Replacing Newlines with HTML Line Breaks in JSTL<\/h2>\n<p>Now that we have a handy utility for replacing newline characters in plain Java, let&#8217;s move on to seeing how we can accomplish this with JSTL. It is a bit tricky, because we cannot simply write a JSTL function and output the results of that, because we don&#8217;t want to leave a cross-site scripting (XSS) vulnerability behind. Therefore we should escape any markup within our data, but doing that, we will also escape any HTML line breaks. The result is that our line breaks would be displayed as <span class=\"code\">&lt;br \/&gt;<\/span> rather than being rendered in the browser.<\/p>\n<p>Instead, what we can do is to do things the other way around; begin by escaping any markup that we don&#8217;t want, and then replace the newlines after that. The result is a string with any markup escaped, except for line breaks that were added instead of newlines.<\/p>\n<p>What we have to do, is to create a custom JSTL tag. If you are not familiar with creating custom JSTL tags, then please perform a web search, as explaining this is outside the scope of this article.<\/p>\n<pre>\r\n&lt;?xml version=\"1.0\" ?&gt;\r\n&lt;taglib version=\"2.0\" xmlns=\"http:\/\/java.sun.com\/xml\/ns\/j2ee\" xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:schemaLocation=\"http:\/\/java.sun.com\/xml\/ns\/j2ee web-jsptaglibrary_2_0.xsd\"&gt;\r\n&lt;tlib-version&gt;1.0&lt;\/tlib-version&gt;\r\n    &lt;short-name&gt;custom&lt;\/short-name&gt;\r\n\r\n    &lt;tag&gt;\r\n        &lt;name&gt;lineToBreakLine&lt;\/name&gt;\r\n        &lt;tag-class&gt;com.codingexplained.app.tag.NewLineToBreakLine&lt;\/tag-class&gt;\r\n        &lt;body-content&gt;empty&lt;\/body-content&gt;\r\n        &lt;attribute&gt;\r\n            &lt;name&gt;value&lt;\/name&gt;\r\n            &lt;required&gt;true&lt;\/required&gt;\r\n            &lt;type&gt;java.lang.String&lt;\/type&gt;\r\n            &lt;rtexprvalue&gt;true&lt;\/rtexprvalue&gt;\r\n        &lt;\/attribute&gt;\r\n        &lt;attribute&gt;\r\n            &lt;name&gt;var&lt;\/name&gt;\r\n            &lt;required&gt;false&lt;\/required&gt;\r\n            &lt;type&gt;java.lang.String&lt;\/type&gt;\r\n            &lt;rtexprvalue&gt;true&lt;\/rtexprvalue&gt;\r\n        &lt;\/attribute&gt;\r\n    &lt;\/tag&gt;\r\n&lt;\/taglib&gt;\r\n<\/pre>\n<p>The tag takes two parameters; the value for which we want to turn newlines into line breaks, and an optional name of a variable in which to store the result, in case we don&#8217;t want to output it directly. Below is the implementation of the above tag.<\/p>\n<pre>\r\npublic class NewLineToBreakLine extends TagSupport {\r\n    private static Logger logger = LogManager.getLogger(DomainNameUri.class);\r\n    private String value;\r\n    private String var;\r\n\r\n    @Override\r\n    public int doStartTag() throws JspException {\r\n        try {\r\n            if (this.value != null && !this.value.isEmpty()) {\r\n                String output = GeneralUtils.nl2br(this.value);\r\n\r\n                if (this.var != null && !this.var.isEmpty()) {\r\n                    this.pageContext.getRequest().setAttribute(this.var, output);\r\n                } else {\r\n                    this.pageContext.getOut().write(output);\r\n                }\r\n            }\r\n        } catch (Exception e) {\r\n            logger.fatal(e.getMessage(), e);\r\n        }\r\n\r\n        return super.doStartTag();\r\n    }\r\n\r\n    public void setValue(String value) {\r\n        this.value = value;\r\n    }\r\n\r\n    public void setVar(String var) {\r\n        this.var = var;\r\n    }\r\n}\r\n<\/pre>\n<p>The above code is simple &#8211; especially if you are familiar with writing custom JSTL tags. We just use the utility method that we implemented in the beginning of this article, and if a variable name has been passed as an argument, then we set the result to a request attribute with that name. Otherwise we simply output the result directly, such that it will appear wherever we use the tag within a JSP file. Note that it is important that you remember to add setter methods to the tag&#8217;s instance variables.<\/p>\n<p>To use our new tag within a JSP file, simply do as follows.<\/p>\n<pre>\r\n&lt;%@ page contentType=\"text\/html;charset=UTF-8\" language=\"java\" %&gt;\r\n&lt;%@ taglib prefix=\"fn\" uri=\"http:\/\/java.sun.com\/jsp\/jstl\/functions\" %&gt;\r\n&lt;%@ taglib prefix=\"custom\" uri=\"\/WEB-INF\/tlds\/tags.tld\" %&gt;\r\n\r\n&lt;h1&gt;HTML Line Breaks Test&lt;\/h1&gt;\r\n\r\nTest 1:\r\n&lt;p>&lt;custom:lineToBreakLine value=\"${fn:escapeXml(text)}\" \/>&lt;\/p&gt;\r\n\r\nTest 2:\r\n&lt;p>&lt;custom:lineToBreakLine value=\"${fn:escapeXml(text)}\" var=\"lineBreaks\" \/>&lt;\/p&gt;\r\n${lineBreaks}\r\n<\/pre>\n<p>In the above example, we use the <span class=\"code\">escapeXml<\/span> JSTL function to first escape any potentially harmful markup, before passing the result on to our custom JSTL tag, which then replaces newline characters with HTML line breaks (<span class=\"code\">&lt;br \/&gt;<\/span>). In the first example, the result is output directly, while it is being stored within a <span class=\"code\">lineBreaks<\/span> variable in the second example.<\/p>\n<p>Had we used a JSTL function to do the replacing instead in combination with the <span class=\"code\">&lt;c:out value=&#8221;${text}&#8221; \/&gt;<\/span> tag, then we would have ended up turning our own line breaks into HTML entities!<\/p>\n<p>I hope this helped. Thank you very much for reading!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will take a look at how we can replace newline characters in Java. Additionally, we will implement a custom JSTL tag so that we can replace newline characters with corresponding &lt;br \/&gt; break lines within JSP files. Unlike PHP&#8217;s nl2br function, for instance, this is not as easy in JSTL. Replacing&hellip; <a href=\"https:\/\/codingexplained.com\/coding\/java\/replace-newline-characters-java-jstl\" class=\"more-link\">read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"jetpack_post_was_ever_published":false,"jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false}}},"categories":[8],"tags":[42,131,132],"series":[],"jetpack_publicize_connections":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v20.4 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Replacing Newline Characters in Java and JSTL<\/title>\n<meta name=\"description\" content=\"Learn how to replace newline characters in Java and JSTL. See how to replace newlines with HTML linebreaks (the br tag) in JSP files, similar to nl2br.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/codingexplained.com\/coding\/java\/replace-newline-characters-java-jstl\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Replacing Newline Characters in Java and JSTL\" \/>\n<meta property=\"og:description\" content=\"Learn how to replace newline characters in Java and JSTL. See how to replace newlines with HTML linebreaks (the br tag) in JSP files, similar to nl2br.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/codingexplained.com\/coding\/java\/replace-newline-characters-java-jstl\" \/>\n<meta property=\"og:site_name\" content=\"Coding Explained\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/codingexplained\" \/>\n<meta property=\"article:author\" content=\"https:\/\/www.facebook.com\/codingexplained\" \/>\n<meta property=\"article:published_time\" content=\"2015-10-25T23:07:30+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2015-10-25T23:04:51+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/codingexplained.com\/wp-content\/uploads\/2015\/11\/codingexplained-fb-promote.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"444\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Bo Andersen\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@codingexplained\" \/>\n<meta name=\"twitter:site\" content=\"@codingexplained\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Bo Andersen\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/codingexplained.com\/coding\/java\/replace-newline-characters-java-jstl\",\"url\":\"https:\/\/codingexplained.com\/coding\/java\/replace-newline-characters-java-jstl\",\"name\":\"Replacing Newline Characters in Java and JSTL\",\"isPartOf\":{\"@id\":\"https:\/\/codingexplained.com\/#website\"},\"datePublished\":\"2015-10-25T23:07:30+00:00\",\"dateModified\":\"2015-10-25T23:04:51+00:00\",\"author\":{\"@id\":\"https:\/\/codingexplained.com\/#\/schema\/person\/e19c92ec991f571605f047cefeaa950d\"},\"description\":\"Learn how to replace newline characters in Java and JSTL. See how to replace newlines with HTML linebreaks (the br tag) in JSP files, similar to nl2br.\",\"breadcrumb\":{\"@id\":\"https:\/\/codingexplained.com\/coding\/java\/replace-newline-characters-java-jstl#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/codingexplained.com\/coding\/java\/replace-newline-characters-java-jstl\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/codingexplained.com\/coding\/java\/replace-newline-characters-java-jstl#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/codingexplained.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Replacing Newline Characters in Java and JSTL\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/codingexplained.com\/#website\",\"url\":\"https:\/\/codingexplained.com\/\",\"name\":\"Coding Explained\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/codingexplained.com\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/codingexplained.com\/#\/schema\/person\/e19c92ec991f571605f047cefeaa950d\",\"name\":\"Bo Andersen\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/codingexplained.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/28f5826f9d5d544b0c5e1ec321dfdfb8?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/28f5826f9d5d544b0c5e1ec321dfdfb8?s=96&d=mm&r=g\",\"caption\":\"Bo Andersen\"},\"description\":\"I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!\",\"sameAs\":[\"https:\/\/codingexplained.com\",\"https:\/\/www.facebook.com\/codingexplained\",\"https:\/\/www.linkedin.com\/in\/ba0708\",\"https:\/\/twitter.com\/codingexplained\",\"https:\/\/www.youtube.com\/c\/codingexplained\"],\"url\":\"https:\/\/codingexplained.com\/author\/andy\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Replacing Newline Characters in Java and JSTL","description":"Learn how to replace newline characters in Java and JSTL. See how to replace newlines with HTML linebreaks (the br tag) in JSP files, similar to nl2br.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/codingexplained.com\/coding\/java\/replace-newline-characters-java-jstl","og_locale":"en_US","og_type":"article","og_title":"Replacing Newline Characters in Java and JSTL","og_description":"Learn how to replace newline characters in Java and JSTL. See how to replace newlines with HTML linebreaks (the br tag) in JSP files, similar to nl2br.","og_url":"https:\/\/codingexplained.com\/coding\/java\/replace-newline-characters-java-jstl","og_site_name":"Coding Explained","article_publisher":"https:\/\/www.facebook.com\/codingexplained","article_author":"https:\/\/www.facebook.com\/codingexplained","article_published_time":"2015-10-25T23:07:30+00:00","article_modified_time":"2015-10-25T23:04:51+00:00","og_image":[{"width":1200,"height":444,"url":"https:\/\/codingexplained.com\/wp-content\/uploads\/2015\/11\/codingexplained-fb-promote.png","type":"image\/png"}],"author":"Bo Andersen","twitter_card":"summary_large_image","twitter_creator":"@codingexplained","twitter_site":"@codingexplained","twitter_misc":{"Written by":"Bo Andersen","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/codingexplained.com\/coding\/java\/replace-newline-characters-java-jstl","url":"https:\/\/codingexplained.com\/coding\/java\/replace-newline-characters-java-jstl","name":"Replacing Newline Characters in Java and JSTL","isPartOf":{"@id":"https:\/\/codingexplained.com\/#website"},"datePublished":"2015-10-25T23:07:30+00:00","dateModified":"2015-10-25T23:04:51+00:00","author":{"@id":"https:\/\/codingexplained.com\/#\/schema\/person\/e19c92ec991f571605f047cefeaa950d"},"description":"Learn how to replace newline characters in Java and JSTL. See how to replace newlines with HTML linebreaks (the br tag) in JSP files, similar to nl2br.","breadcrumb":{"@id":"https:\/\/codingexplained.com\/coding\/java\/replace-newline-characters-java-jstl#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/codingexplained.com\/coding\/java\/replace-newline-characters-java-jstl"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/codingexplained.com\/coding\/java\/replace-newline-characters-java-jstl#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/codingexplained.com\/"},{"@type":"ListItem","position":2,"name":"Replacing Newline Characters in Java and JSTL"}]},{"@type":"WebSite","@id":"https:\/\/codingexplained.com\/#website","url":"https:\/\/codingexplained.com\/","name":"Coding Explained","description":"","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/codingexplained.com\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/codingexplained.com\/#\/schema\/person\/e19c92ec991f571605f047cefeaa950d","name":"Bo Andersen","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/codingexplained.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/28f5826f9d5d544b0c5e1ec321dfdfb8?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/28f5826f9d5d544b0c5e1ec321dfdfb8?s=96&d=mm&r=g","caption":"Bo Andersen"},"description":"I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!","sameAs":["https:\/\/codingexplained.com","https:\/\/www.facebook.com\/codingexplained","https:\/\/www.linkedin.com\/in\/ba0708","https:\/\/twitter.com\/codingexplained","https:\/\/www.youtube.com\/c\/codingexplained"],"url":"https:\/\/codingexplained.com\/author\/andy"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p3mJkW-pb","_links":{"self":[{"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/posts\/1561"}],"collection":[{"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/comments?post=1561"}],"version-history":[{"count":6,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/posts\/1561\/revisions"}],"predecessor-version":[{"id":2027,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/posts\/1561\/revisions\/2027"}],"wp:attachment":[{"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/media?parent=1561"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/categories?post=1561"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/tags?post=1561"},{"taxonomy":"series","embeddable":true,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/series?post=1561"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}