Giter Club home page Giter Club logo

gs-serving-web-content's Introduction

This guide walks you through the process of creating a “Hello, World” web site with Spring.

What You Will Build

You will build an application that has a static home page and that will also accept HTTP GET requests at: http://localhost:8080/greeting.

It will respond with a web page that displays HTML. The body of the HTML will contain a greeting: “Hello, World!”

You can customize the greeting with an optional name parameter in the query string. The URL might then be http://localhost:8080/greeting?name=User.

The name parameter value overrides the default value of World and is reflected in the response by the content changing to “Hello, User!”

Starting with Spring Initializr

You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.

To manually initialize the project:

  1. Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.

  2. Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.

  3. Click Dependencies and select Spring Web, Thymeleaf, and Spring Boot DevTools.

  4. Click Generate.

  5. Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.

Note
If your IDE has the Spring Initializr integration, you can complete this process from your IDE.
Note
You can also fork the project from Github and open it in your IDE or other editor.

Create a Web Controller

In Spring’s approach to building web sites, HTTP requests are handled by a controller. You can easily identify the controller by the @Controller annotation. In the following example, GreetingController handles GET requests for /greeting by returning the name of a View (in this case, greeting). A View is responsible for rendering the HTML content. The following listing (from src/main/java/com/example/servingwebcontent/GreetingController.java) shows the controller:

link:complete/src/main/java/com/example/servingwebcontent/GreetingController.java[role=include]

This controller is concise and simple, but there is plenty going on. We break it down step by step.

The @GetMapping annotation ensures that HTTP GET requests to /greeting are mapped to the greeting() method.

@RequestParam binds the value of the query string parameter name into the name parameter of the greeting() method. This query string parameter is not required. If it is absent in the request, the defaultValue of World is used. The value of the name parameter is added to a Model object, ultimately making it accessible to the view template.

The implementation of the method body relies on a view technology (in this case, Thymeleaf) to perform server-side rendering of the HTML. Thymeleaf parses the greeting.html template and evaluates the th:text expression to render the value of the ${name} parameter that was set in the controller.The following listing (from src/main/resources/templates/greeting.html) shows the greeting.html template:

link:complete/src/main/resources/templates/greeting.html[role=include]
Tip
Make sure you have Thymeleaf on your classpath (artifact co-ordinates: org.springframework.boot:spring-boot-starter-thymeleaf). It is already there in the "initial" and "complete" samples in Github.

Spring Boot Devtools

A common feature of developing web applications is coding a change, restarting your application, and refreshing the browser to view the change. This entire process can eat up a lot of time. To speed up this refresh cycle, Spring Boot offers with a handy module known as spring-boot-devtools. Spring Boot Devtools:

  • Enables hot swapping.

  • Switches template engines to disable caching.

  • Enables LiveReload to automatically refresh the browser.

  • Other reasonable defaults based on development instead of production.

Run the Application

The Spring Initializr creates an application class for you. In this case, you need not further modify the class provided by the Spring Initializr. The following listing (from src/main/java/com/example/servingwebcontent/ServingWebContentApplication.java) shows the application class:

link:complete/src/main/java/com/example/servingwebcontent/ServingWebContentApplication.java[role=include]

Logging output is displayed. The application should be up and running within a few seconds.

Test the Application

Now that the web site is running, visit http://localhost:8080/greeting, where you should see “Hello, World!”

Provide a name query string parameter by visiting http://localhost:8080/greeting?name=User. Notice how the message changes from “Hello, World!” to “Hello, User!”:

This change demonstrates that the @RequestParam arrangement in GreetingController is working as expected. The name parameter has been given a default value of World, but it can be explicitly overridden through the query string.

Add a Home Page

Static resources, including HTML and JavaScript and CSS, can be served from your Spring Boot application by dropping them into the right place in the source code. By default, Spring Boot serves static content from resources in the classpath at /static (or /public). The index.html resource is special because, if it exists, it is used as a "welcome page", which means it is served up as the root resource (that is, at http://localhost:8080/). As a result, you need to create the following file (which you can find in src/main/resources/static/index.html):

link:complete/src/main/resources/static/index.html[role=include]

When you restart the application, you will see the HTML at http://localhost:8080/.

Summary

Congratulations! You have just developed a web page by using Spring.

gs-serving-web-content's People

Contributors

bclozel avatar bert-r avatar btalbott avatar buzzardo avatar cbeams avatar gregturn avatar martin-mfg avatar ms515631 avatar robertmcnees avatar royclarkson avatar rskokan avatar schmittlauch avatar schnwalter avatar spring-operator avatar ultraq avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gs-serving-web-content's Issues

ViewResolver error (Java17+springboot2.6.1~2.6.3, Java11+springboot3.6.2~3.6.3)

Thanks @johnmilimo, replacing @Controller with @RestController works for me. It save my ton of time. But why?

I don't think it resolved your problem. After chaning it to "RestController", it just return the "greeting" string itself -- that's not a view page.
I just found it won't work after using Java11/Java17 (Springboot is now 2.6.3).

Update:
It seem this problem occurs in spring-boot-starter-parent:2.6.1~2.6.3.
2.6.0 works fine with Java 17.

Originally posted by @gyokutoku in #19 (comment)

Verified NG patterns:
-Java17.0.2+springboot2.6.1 - 2.6.3(latest)
-Java11.0.13+springboot3.6.2 - 3.6.3(latest)
-Amazoncorretto17+springboot2.6.3(latest)

Verified OK patterns:
-Java17.0.2+springboot less 2.6.0
-Java11.0.13+springboot3.6.0~3.6.1
-Java1.8.0_131+springboot3.6.3(latest)

Temperory solution:
Changing Java version or using older version of springboot

StackTrace(java11+springboot3.6.2)

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sat Feb 19 00:13:04 JST 2022
There was an unexpected error (type=Internal Server Error, status=500).
Circular view path [greeting]: would dispatch back to the current handler URL [/greeting] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
javax.servlet.ServletException: Circular view path [greeting]: would dispatch back to the current handler URL [/greeting] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:210)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:148)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1401)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1145)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1084)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1732)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:834)

Upgrade Spring Boot to the latest version

Update the guide to use the most recent Spring Boot version.

To do so, change the Spring Boot version in:

initial/build.gradle
initial/pom.xml
complete/build.gradle
complete/pom.xml

missing spring.thymeleaf.cache=false

Hi,
I've just try gs-serving-web-content-complete in SpringIDE and was disappointed when modifying the "greeting.html" template and do not see change in the browser (template was not reloaded).

After searching into the web I found that adding the file scr/main/resources/application.properties
with the line spring.thymeleaf.cache=false resolve the case.

I think you could add this tip to make people happy to discover that Java web app can reload changes without restarting web server (an old bad story).

Cheers.

Modify pom.xml so ./mvnw works

Modify pom.xml so that ./mvnw works

<build> <defaultGoal>spring-boot:run</defaultGoal> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>

why when i new create project with idea it appears cannot resolve MVC view but your project is ok

Sorry to bother i am fresh to program and when i use idea to follow your project i have some problem and also cannot found solution (i have been bothered by two days)
i choose file->new project->Spring Initializr with mave java-> In Dependencies i choose Spring Boot DevTools andLombok
so i dont know what wrong with
image
image
the only i can is to open static everything in templates can not open it (it appears Whitelabel Error Page)
image
image
it can open index which is locate in static
image

Thank you very much

https://spring.io/guides/gs/serving-web-content/ Broken

You can't run this on a separate Tomcat server because your parent pom is providing the jar. Also it's broken because this only works on a specific version of Tomcat in the pom properties. <tomcat.version>7.0.75</tomcat.version>

But the bigger problem is it not working on server. What's the point of a web tutorial if you can't run it on a server? They would literally have to rewrite nearly the entire pom and hunt down a ton of dependencies just to get it running. Rewrite this tutorial so it will actually work in typical situations.

Mapping logging broken

The output doesn't show that greeting is mapped.

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-05-11 15:45:23.446  INFO 5169 --- [  restartedMain] hello.Application                        : Starting Application on phil-desktopubuntu-18-04-1-lts with PID 5169 (/home/phil/eclipse-whatthephil-workspace/whatthephil/target/classes started by phil in /home/phil/eclipse-whatthephil-workspace/whatthephil)
2019-05-11 15:45:23.448  INFO 5169 --- [  restartedMain] hello.Application                        : No active profile set, falling back to default profiles: default
2019-05-11 15:45:23.482  INFO 5169 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2019-05-11 15:45:23.482  INFO 5169 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2019-05-11 15:45:24.419  INFO 5169 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-05-11 15:45:24.439  INFO 5169 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-05-11 15:45:24.440  INFO 5169 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-05-11 15:45:24.500  INFO 5169 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-05-11 15:45:24.501  INFO 5169 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1019 ms
2019-05-11 15:45:24.663  INFO 5169 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-05-11 15:45:24.760  INFO 5169 --- [  restartedMain] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page: class path resource [static/index.html]
2019-05-11 15:45:24.806  INFO 5169 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2019-05-11 15:45:24.853  INFO 5169 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-05-11 15:45:24.855  INFO 5169 --- [  restartedMain] hello.Application                        : Started Application in 1.666 seconds (JVM running for 2.606)

Whitelabel Error Page - GreetingController annotation might be wrong

When the GreetingController has the annotation @Controller annotation the URL to localhost:8080/greeting does not work. Changing the annotation to @RestController (as suggested in https://stackoverflow.com/questions/40797628/spring-boot-thymeleaf-viewresolver-on-rest-controllers) fixes the error.

In the browser the error is shown as:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Dec 30 00:07:06 CET 2018
There was an unexpected error (type=Internal Server Error, status=500).

In the terminal the error:

2018-12-30 00:07:06.767 ERROR 4852 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template "greeting", template might not exist or might not be accessible by any of the configured Template Resolvers] with root cause

org.thymeleaf.exceptions.TemplateInputException: Error resolving template "greeting", template might not exist or might not be accessible by any of the configured Template Resolvers

unable to call web application from the spring boot to send params through url

I am try to using Angularjs2 with spring boot application every thing working fine with the small issue.

Description:

step1. if we have default router like router('') meaning localhost:8080/ it is calling index.html page with out having issues.

step2. if we have added context path like router('accountsummary') meaning localhost:8080/accountsummary its not working. when i give like below configuration in spring boot conf like below:

@configuration
public class WebController extends WebMvcConfigurerAdapter{
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/accountSummary").setViewName("index.html");
}
}

it was working fine.

  1. when i want to configure like route('accountsummary/:reqid). reqid is the parameter meaning i want to call like localhost:8080/accountsummary/abc it is not working. i have given like (/**)

@configuration
public class WebController extends WebMvcConfigurerAdapter{
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/accountSummary/**").setViewName("index.html");
}
}

its not working and giving like below:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Thu Jun 30 15:11:38 EDT 2016
There was an unexpected error (type=Not Found, status=404).
No message available

Can any one please help me out

dependency versions

Hello,

I am trying to go through the tutorial linked below. I am using STS and started by creating a new maven project with no archetype specified.

I was directed to this github project for pom.xml. However, eclipse is complaining that there is not version element within the dependencies.

I must me missing something?

http://spring.io/guides/gs/serving-web-content/#scratch

guide does not work - missing link refs?

The guide at https://github.com/spring-guides/gs-serving-web-content
doesnt seem to pull in the info for the 'what you need' section, nor the code example in 'Create a web controller', this shows:
link:complete/src/main/resources/templates/greeting.html[]
and the 'run the application' code link also just shows the link:
link:complete/src/main/java/com/example/servingwebcontent/ServingWebContentApplication.java[]

Followed by links to 'getting-started' sections that perhaps should be displayed rather than just linked?
code sample from 'add a home page' also just shows a link.

Compared to the guide at: https://spring.io/guides/gs/serving-web-content/
which does show the relevant sections.

Lastly - the 'pre-initialised project' link needs updating, as the start.spring.io page warns:
The following attributes could not be handled:
11 is not a valid Java version, 17 has been selected.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.