Following example shows how to handle a Post request submitted by a static html page
Example
Java Config
@EnableWebMvc
@Configuration
public class MyWebConfig {
@Bean
public ExampleController exampleController() {
return new ExampleController();
}
@Bean
public WebMvcConfigurer staticPageConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("/static/");
}
};
}
}
public class MyWebInitializer implements WebApplicationInitializer {
@Override
public void onStartup (ServletContext servletContext) {
AnnotationConfigWebApplicationContext ctx =
new AnnotationConfigWebApplicationContext();
ctx.register(MyWebConfig.class);
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic servlet =
servletContext.addServlet("springDispatcherServlet",
new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
A static html with Form post submission
src/main/webapp/static/simple-form.html<html>
<body>
<h2>Person Details</h2>
<form action="/example-handler" method="post">
<label for="personName">Name:</label><br>
<input type="text" id="personName" name="personName"><br>
<label for="personAddress">Address:</label><br>
<input type="text" id="personAddress" name="personAddress"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Spring MVC controller
@Controller
@RequestMapping("/example-handler")
public class ExampleController {
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public String handlePostRequest(String personName, String personAddress) {
return String.format("simple response. name: %s, address: %s",
personName, personAddress);
}
}
Running example
To try examples, run embedded tomcat (configured in pom.xml of example project below):
mvn tomcat7:run-war
Output
Access static page at http://localhost:8080/static/simple-form.html
Fill form:
On submitting form
Example ProjectDependencies and Technologies Used: - spring-webmvc 5.2.6.RELEASE: Spring Web MVC.
- javax.servlet-api 3.0.1 Java Servlet API
- JDK 1.8
- Maven 3.5.4
|