Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

My blog is posting "asdfas <br> df <br> asd" !!! How do I get new lines??

Hi!

I am doing a blog in Spark, and it is showing:

"asdfas <br> df <br> asd"

instead of:

"asdfas df asd"

how could I fix it? :) thanks!!!

Here is the code:

post("/new", (request, response) -> {
            String title = request.queryParams("title");
            String text = request.queryParams("entry").replace("\n", "<br>");
            Entry entry = new Entry(title, Calendar.getInstance().getTime(), text, new ArrayList<>());
            blog.add(entry);
            response.redirect("/entries/" + entry.getSlug());
            return null;
        });

1 Answer

I don't know Spark so I can't answer specifically, but I am familiar with publishing text on web pages and how most methods designed to do that typically sanitize text to prevent Cross Site Scripting (XSS) attacks. Here are some recommendations:

  • One of your methods - probably the Entry constructor or blog.add() - are sanitizing the text and turning <br> into &lt;br&gt; behind the scenes so it displays as <br> on the page. You'll have to read their documentation to understand where it's happening and how to work around it - possibly escaping the <br> sequence somehow or deactivating the sanitization.

  • However, if request.queryParams("entry") is retrieving text from some kind of user input, you'll want to be careful that you're not introducing an XSS vulnerability. Sanitize the original text yourself using a method for that purpose and then add your line breaks after that.

  • You might also have to separate the text into sections using the newline characters and add each section separately to your post.

Good luck!