Devolviendo una View desde Controller (VC) con Thymeleaf

¿Qué vamos a hacer?

El objetivo de este artículo, es tener un controlador, que devuelva páginas. En este caso, el formato será HTML, pero estas páginas perfectamente podrían tener extensión JSP y se cargarían de la misma manera.

¿Cómo lo vamos a hacer?

Existen muchas manera de realizarlo, nosotros vamos a utilizar Thymeleaf.

¿Qué es Thymeleaf?

Thymeleaf, es un motor de plantillas Java para servidores. El objetivo principal es crear plantilla de una forma elegante y mantenible. Este motor de plantillas, nos permite procesar HTML, XML, JavaScript, CSS y texto sin formato. Y se basa en el concepto de Natural Templates (Plantillas Naturales), las cuales nos permiten inyectar lógica (datos) sobre los archivos sin que esto afecte a la plantilla.

Basándonos en el proyecto que creemos en el artículo Creando un proyecto de Spring Boot. Añadimos la dependencia Thymeleaf, dentro del root de dependencias (dependencies) del fichero pom.xml. Con la finalidad de poder devolver documentos HTML desde el propio controlador de Spring.

<!-- Spring boot Thymeleaf -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Añadiendo Thymeleaf a las dependencias de pom.xml

Obtendremos como resultado:

Creando la vista HTML a devolver

Una vez añadida la dependencia, creamos un fichero index con extensión .html dentro de la carpeta templates ubicada en src/main/resources:

El contenido del index.html será:

Añadiendo el controlador que devuelve la vista

Y finalmente, el controlador que devuelve la vista será el siguiente:

Si nos fijamos, el return de la ruta del controlador, apunta hacía el fichero index. Si queremos devolver un String y no una vista, deberemos añadir el @ResponseBody que ahora mismo tenemos comentado.

Testeando el proyecto Vista Controlador de Spring Boot

Si arrancamos el proyecto y realizamos una petición:

Podemos ver como se responde a la petición, pero esta vez, en vez de responder desde el controlador, realmente, estamos devolviendo una vista.

Ya empezamos a estar muy cerca del famoso MVC. Para ello, solo nos faltaría la capa de datos. Ya que en este artículo, podríamos decir que, estamos trabajando con VC.

En próximos artículos, veremos cómo cargar datos en las vistas antes de devolverlas. Saludos javer@s!

48 comentarios

  1. Everyone loves what you guys tend to be up too. Such clever work and coverage!
    Keep up the excellent works guys I’ve included you guys to my blogroll.

  2. Right away I am going away to do my breakfast, when having my breakfast coming yet
    again to read more news.

  3. Great article, exactly what I needed.

  4. I think that is one of the so much important info for me.
    And i’m glad reading your article. But wanna statement
    on some general issues, The website style is wonderful, the articles is
    in point of fact excellent : D. Excellent process,
    cheers

  5. Hello, its pleasant post about media print, we all be familiar with media is a enormous source of information.

  6. Thank you for sharing your thoughts. I truly appreciate your efforts and I am waiting for your next write ups thank
    you once again.

  7. I do not even know how I ended up here, but I thought
    this post was good. I do not know who you are but definitely
    you’re going to a famous blogger if you aren’t already 😉 Cheers!

  8. I couldn’t refrain from commenting. Well written!

  9. This is the right site for everyone who would like to understand this topic.

    You know a whole lot its almost tough to argue with you (not
    that I really would want to…HaHa). You definitely put a fresh
    spin on a subject that has been written about for many
    years. Excellent stuff, just great!

  10. I am regular visitor, how are you everybody?
    This article posted at this web site is in fact fastidious.

  11. Good way of describing, and fastidious paragraph to
    get facts concerning my presentation subject matter, which i am going to deliver in institution of higher education.

    my site :: Health Flow Male Enhancement Review

  12. I’m really enjoying the design and layout of your site. It’MosQiller S Zapper a very easy on the eyes which makes it much more pleasant for me to come
    here and visit more often. Did you hire out a
    designer to create your theme? Superb work!

  13. I am not rattling fantastic with English but I line up this real easygoing
    to read.

    my website – http://www.koan.at

  14. Hmm it looks like your site ate my first comment (it was super long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly
    enjoying your blog. I as well am an aspiring blog blogger
    but I’m still new to the whole thing. Do you have any suggestions for beginner blog writers?
    I’d definitely appreciate it.

    Check out my web page: Guy

  15. Thanks for sharing your thoughts on children smoking. Regards

    My blog: http://walnut.ut.ac.ir

  16. You can definitely see your expertise within the paintings you write.
    The world hopes for even more passionate writers like you who are not afraid to say how they
    believe. All the time follow your heart.

    My web blog Health Flow Pills Review

  17. Hi there! This is my first visit to your blog!
    We are a collection of volunteers and starting a new initiative in a community in the same niche.
    Your blog provided us useful information to work on. You have
    done a extraordinary job!

    Here is my blog :: Clarence

  18. This web site truly has all of the information and facts I wanted about this subject and didn’t know who to ask.

  19. Hey there! I know this is kinda off topic but I
    was wondering which blog platform are you using for this website?
    I’m getting sick and tired of WordPress because I’ve had
    problems with hackers and I’m looking at alternatives
    for another platform. I would be fantastic if you could point me
    in the direction of a good platform.

  20. Greetings from Carolina! I’m bored at work
    so I decided to check out your website on my iphone during lunch break.

    I enjoy the knowledge you provide here and can’t wait to take a look when I
    get home. I’m surprised at how quick your blog loaded on my cell phone ..
    I’m not even using WIFI, just 3G .. Anyways, superb blog!

    My web blog Infinity CBD Review

  21. Hi there to all, how is all, I think every one is
    getting more from this web site, and your views are fastidious for new viewers.

  22. Hi there! This post couldn’t be written any better!

    Reading through this post reminds me of my previous room mate!

    He always kept chatting about this. I will forward this write-up to him.
    Fairly certain he will have a good read. Thanks for sharing!

    Take a look at my webpage: http://www.fotosombra.com.br

  23. Hello.This article was really fascinating, especially
    since I was investigating for thoughts on this matter last couple of days.

    Stop by my blog … Brilliance Keto Review

  24. You’re so awesome! I don’t believe I’ve read a single thing like this before.
    So good to find another person with some original thoughts on this topic.

    Really.. many thanks for starting this up. This site
    is something that’s needed on the internet, someone with some originality!

  25. Howdy! I know this is kinda off topic but I’d figured I’d ask.
    Would you be interested in trading links or maybe guest writing a blog post or vice-versa?

    My blog addresses a lot of the same topics as yours and I believe we could greatly benefit from each other.

    If you are interested feel free to shoot me an email.

    I look forward to hearing from you! Terrific blog by the way!

  26. Oh my goodness! Awesome article dude! Thank you, However I am having problems with your RSS.
    I don?t know the reason why I cannot subscribe to it.
    Is there anybody having the same RSS problems? Anyone who knows the solution can you kindly
    respond? Thanks!!

    Also visit my blog post – Glacier Portable AC

  27. This is the right web site for anybody who hopes to understand this topic.

    You understand so much its almost tough to argue with you (not
    that I really would want to?HaHa). You definitely put a new
    spin on a subject that’s been discussed for decades. Wonderful stuff, just great!

    Look at my web site :: True Keto 1800 Reviews

  28. I just like the valuable information you provide on your articles.
    I will bookmark your weblog and check once more right here frequently.
    I’m fairly sure I will learn plenty of new stuff right right here!
    Good luck for the next!

    Have a look at my blog post; Fast Dash Keto Ingredients

  29. I just wanted to thank you a lot more for the amazing blog you have designed here.

    It really is full of ideas for those who are really interested in that subject, especially this very post.
    Your all absolutely sweet and also thoughtful of others as well as reading your blog posts is a wonderful delight in my opinion. And that of a generous treat!
    Jeff and I really have excitement making use
    of your ideas in what we have to do next week.

    Our list is a mile long and simply put tips will definitely be put to great use.

    My webpage; Green Flame CBD Reviews

  30. You should take part in a contest for one of the finest websites on the internet.

    I’m going to highly recommend this website!

    Visit my web page – Maximum Recall

  31. Good post. I learn something totally new and challenging on websites I stumbleupon on a daily basis.

    It will always be interesting to read through content from other authors
    and use something from other websites.

    My webpage; Evo Naturals Hemp Gummy Bears Review (forum.m2clasic.ro)

  32. hey there and thank you for your info – I have definitely picked up something new from right here.

    I did however expertise a few technical
    issues using this website, as I experienced to reload
    the website a lot of times previous to I could get it to load correctly.
    I had been wondering if your hosting is OK?
    Not that I’m complaining, but sluggish loading instances times will sometimes affect your placement in google and can damage your high-quality score
    if advertising and marketing with Adwords. Well I’m adding this RSS to my e-mail and could look out for much more
    of your respective exciting content. Make sure you update this again soon.

  33. I was just searching for this info for a while.
    After six hours of continuous Googleing, finally I got it in your website.
    I wonder what is the lack of Google strategy that do not rank this kind of informative websites in top of the list.
    Normally the top sites are full of garbage.

    Also visit my blog post – Green Naturals CBD Reviews

  34. Thank you for being my personal coach on this niche. We enjoyed your current
    article very much and most of all preferred how you handled
    the areas I widely known as controversial.
    You are always really kind towards readers like me and assist
    me in my lifestyle. Thank you.

    Feel free to visit my web blog: http://www.sa-mp.ugu.pl

  35. This design is wicked! You certainly know how to keep
    a reader amused. Between your wit and your videos, I was almost moved to start my own blog
    (well, almost…HaHa!) Wonderful job. I really enjoyed what you had to say, and more than that, how you presented it.

    Too cool!

    Feel free to surf to my homepage … WifiLift Cost

  36. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point.
    You obviously know what youre talking about,
    why waste your intelligence on just posting videos to your blog when you could be
    giving us something enlightening to read?

    Feel free to surf to my blog post Maximum Recall Reviews

  37. It’s actually a great and helpful piece of information. I am glad that you just shared this useful info with us.
    Please keep us informed like this. Thank you for sharing.

  38. Good way of explaining, and nice article to get information on the topic of my presentation subject matter, which
    i am going to deliver in institution of higher education.

    Look at my page; Imarais Beauty Review

  39. Its great as your other articles :D, thanks for putting up.

    My page – Kisha

  40. I have read several excellent stuff here. Definitely price bookmarking for revisiting.
    I wonder how a lot effort you set to make the sort of great informative site.

    Here is my homepage True Keto 1800 Review

  41. I like this web blog it’s a master piece! Glad I found this
    on google.

    My page; True Keto 1800 Review

  42. As soon as I noticed this internet site I went on reddit
    to share some of the love with them.

    Feel free to visit my web site; Total Keto 365 Pills

  43. Everyone loves it when people get together and share opinions.
    Great site, stick with it!

  44. It’s very trouble-free to find out any topic on web as compared to
    books, as I found this post at this website.

    my blog – Rapid Fire Keto

  45. Hi there! I realize this is sort of off-topic but I had to
    ask. Does running a well-established website such as yours take a massive amount work?
    I’m brand new to operating a blog however I do write in my
    journal on a daily basis. I’d like to start a
    blog so I can share my experience and thoughts online.
    Please let me know if you have any kind of suggestions or tips
    for brand new aspiring bloggers. Appreciate it!

    Also visit my website :: http://shihan.com.ru/

  46. Excellent beat ! I wish to apprentice whilst you amend your web site, how could i subscribe for a
    weblog site? The account helped me a appropriate deal. I have been a little bit acquainted of this
    your broadcast offered vibrant transparent idea

    Here is my web-site :: http://www.hltkd.tw/hl4/userinfo.php?uid=105649

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

La Ley 34/2002 nos obliga a avisarte de que usamos cookies propias y de terceros con objetivos estadísticos y de sesión y para mostrarte la 'publi' que nos da de comer. Tranquilo, este mensaje solo sale una vez. Más información

Java desde 0 comunica a los usuarios, a través de este aviso, que puede utilizar cookies cuando el usuario navega por las diferentes pantallas y páginas del sitio. Durante el uso de nuestra página Web usted acepta y autoriza expresamente el uso de cookies, de acuerdo con nuestra Política de Privacidad. Este sitio web utiliza las siguientes cookies propias: - Cookies de sesión, para garantizar que los usuarios que escriban comentarios en el blog sean humanos y no aplicaciones automatizadas. De esta forma se combate el spam. Este sitio web utiliza las siguientes cookies de terceros: - Google AdManager y AdSense: Utiliza cookies para mejorar la publicidad. Entre otros fines, suelen utilizarse para segmentarla según el contenido que sea relevante para los usuarios o su ubicación, mejorar los informes de rendimiento de las campañas y evitar mostrar anuncios que los usuarios ya hayan visto. Las cookies no contienen información personal identificable. Consulta cómo utiliza Google la información de sitios web o aplicaciones. y cómo bloquear determinados anuncios. - Google Analytics: Almacena cookies para poder elaborar estadísticas sobre el tráfico y volumen de visitas de esta web. Al utilizar este sitio web está consintiendo el tratamiento de información acerca de usted por Google. Por tanto, el ejercicio de cualquier derecho en este sentido deberá hacerlo comunicando directamente con Google. - Redes sociales: Cada red social utiliza sus propias cookies para que usted pueda pinchar en botones del tipo Me gusta o Compartir.

Cerrar