Narinder Guru Narinder Guru - 2 months ago 16
Java Question

How do i pass raw HTML from java spring controller to jsp view

Im just trying something for feasibility purposes.

I am trying to pass raw HTML code in my Spring controller to a specific view. However i want to know if its possible to convert raw html to a string and then pass the HTML string to the view. Theres errors in "String message" because i havented formatted the HTML into a string.

@Controller
public class TestController {

@RequestMapping(value = "/test", produces = "text/html;charset=UTF-8")
public ModelAndView test (ModelMap model) {
//Map<String, Object> cat = (Map<String, Object>) incidentService.getIncidentCategories();

ModelAndView mv = new ModelAndView("test2.jsp");
String message = <p><img alt="alt text" src="http://localhost:8080/aston.jpg" style="height:974px; width:2386px" />This is my textarea to be replaced with CKEditor.</p> //
return new ModelAndView("welcome", "message", message);

return mv;
}

}

Answer

So i basically come to this solution. In spring controller, i am passing encoded escaped html to the view.

mv.addObject("Description", HtmlUtils.htmlEscape(eknow.get(0).getDescription()));

unescaped:"

testing 12345

"

escaped:<p>testing 12345</p>

<p><img alt="alt text" src="http://localhost:8080/logo.gif&quot; style="height:303px; width:1191px" /></p>

And then on the view i store the escaped value in a hidden input.

And then i get the element by jquery and reverse the action from escaped to unescaped.

var testing = $("#test").val();
alert(decodeURIComponent(testing));
CKEDITOR.instances.description.setData(decodeURIComponent(testing));

This will then set and render html raw code for my HTML editor.

If you know of any way to optimize this, please let me know. But this solution works.