Spring Boot Controller

Source: Internet
Author: User

After the last article, HelloWorld program we have created a hellcontroller, which contains a response to the JSON method, this article for the controller to do a bit more explanation.

Recalling the previous article, we used @RestController annotations in the controller, which was introduced in Spring 4.0. Check the source to see that it contains @Controller and @ResponseBody annotations. We can understand it as an enhanced version of @Controller. Specifically designed to respond to a content-style Controller, you can directly respond to the object as JSON.
While @Controller is used to respond to pages, Spring-boot supports a variety of template engines including:
1,freemarker
2,groovy
3,thymeleaf (Use this on Spring website)
4,velocity
5,jsp (seemingly spring boot officially does not recommend, STS created project will have a templates directory under Src/main/resources, here is let us put the template file, and then did not generate such as Springmvc WebApp directory)
However, this article is to choose everyone familiar with the JSP for example, because the use of JSP and the default Support Template needs special processing, so take the example better.

The Controller method can receive parameters using @requestbody, @RequestParam, @ModelAttribute, Jsonobject, httpentity, and so on, all the same as the use of spring, here do not repeat.

Let's take a look at how to implement the response JSP page using the @Controller (same as SPRINGMVC).
Create the Pagecontroller, encoded as follows:

 PackageOrg.springboot.sample.controller;ImportJava.util.Date;ImportJava.util.Map;ImportOrg.springframework.beans.factory.annotation.Value;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.ui.Model;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.servlet.ModelAndView;@Controller Public  class pagecontroller {    //Read the configuration from application.properties, such as the default value of Hello Shanhy    @Value("${application.hell:hello Shanhy}")PrivateString Hello ="Hello shanhy";/** * Default page <br/> * @RequestMapping("/") and @RequestMapping are different * if you do not write the parameters, then the global default page, add the output     On page 404, this page is also automatically accessed.     * If the parameter "/" is added, it is considered to be the root page only. * * @return * @author shanhy * @create January 5, 2016 * *    @RequestMapping(value = {"/","/index"}) PublicStringIndex(map<string, object> model) {//Return string directly, the framework defaults to the Spring.view.prefix directory (index splicing spring.view.suffix) page        //This example is/web-inf/jsp/index.jspModel.put ("Time",NewDate ()); Model.put ("Message", This. Hello);return "Index"; }/** * Response to JSP page Page1 * * @return * @author shanhy * @create January 5, 2016 */    @RequestMapping("/page1") PublicModelandviewPage1(){//Page location/web-inf/jsp/page/page.jspModelandview Mav =NewModelandview ("Page/page1"); Mav.addobject ("Content", hello);returnMav }/** * Response to JSP page Page1 (can directly use the model package content, directly return the page string) * * @return * @author shanhy *
     
       @create January 5, 2016 *
      /    @RequestMapping("/page2") PublicStringPage2(Model model) {//Page location/web-inf/jsp/page/page.jspModel.addattribute ("Content", Hello +"(second type)");return "Page/page1"; }}

Pom.xml Add Dependency:

        <dependency>            <groupId>Org.springframework.boot</groupId>            <artifactid>Spring-boot-starter-tomcat</artifactid>        </Dependency>        <dependency>            <groupId>Org.apache.tomcat.embed</groupId>            <artifactid>Tomcat-embed-jasper</artifactid>            <scope>Provided</Scope>        </Dependency>        <dependency>            <groupId>Javax.servlet</groupId>            <artifactid>Jstl</artifactid>        </Dependency>

Above said Spring-boot does not recommend JSP, want to use JSP need to configure Application.properties.
Add src/main/resources/application.properties content:

# 页面默认前缀目录spring.mvc.view.prefix=/WEB-INF/jsp/# 响应页面默认后缀spring.mvc.view.suffix=.jsp# 自定义属性,可以在Controller中读取application.hello=Hello Shanhy

Create the webapp/web-inf/jsp directory below Src/main to store our JSP pages.
index.jsp

<%@ page language="java" pageencoding="UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" ><html><head><title>Spring Boot Sample</title></head><body>Time: ${time}<br>Message: ${message}</body></html>

page1.jsp

<%@ page language="java" pageencoding="UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" ><html><head><title>Spring Boot Sample</title></head><body>    <H1>${content}</H1></body></html>

To make Spring-boot support JSP, you need to make the project into a war package.
Let's make a final change, modify the Pom.xml file, and modify the jar in the jar to the war

Then start the Spring-boot service.
Visit the page to view the results:
http://localhost:8080
Http://localhost:8080/page1
Http://localhost:8080/page2

Finally, the engineering structure is attached:

If you need to use Freemarker's classmates, please follow the instructions below to modify:
1, remove the application.properties in the Spring.mvc.view.prefix and Spring.mvc.view.suffix configuration.
2. Place the. FTL template page in the Resources/templates (as shown in the project above)
Where ERROR.FTL is the default error page for the system, and the content is self-determined.
3, modify the Pom.xml, as follows:

<?xml version= "1.0" encoding= "UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://maven.apache.org/POM/ 4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd ">        <modelversion>4.0.0</modelversion>    <groupId>Org.springboot.sample</groupId>    <artifactid>Spring-boot-sample</artifactid>    <version>0.0.1-snapshot</version>    <packaging>Jar</Packaging><!--<packaging>war</packaging> --    <name>Spring-boot-sample</name>    <description>Spring Boot Sample WEB Application</Description>    <parent>        <groupId>Org.springframework.boot</groupId>        <artifactid>Spring-boot-starter-parent</artifactid>        <version>1.3.1.RELEASE</version>        <relativepath/> <!--lookup parent from repository --    </Parent>    <properties>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        <java.version>1.8</java.version>    </Properties>    <dependencies><!--<dependency> --<!--<groupId>org.springframework.boot</groupId> --<!--<artifactId>spring-boot-starter-web</artifactId> --<!--</dependency> --<!--<dependency> --<!--<groupId>org.springframework.boot</groupId> --<!--<artifactId>spring-boot-starter-tomcat</artifactId> --<!--</dependency> --<!--<dependency> --<!--<groupId>org.apache.tomcat.embed</groupId> --<!--<artifactId>tomcat-embed-jasper</artifactId> --<!--<scope>provided</scope> --<!--</dependency> --<!--<dependency> --<!--<groupId>javax.servlet</groupId> --<!--<artifactId>jstl</artifactId> --<!--</dependency> --        <dependency>            <groupId>Org.springframework.boot</groupId>            <artifactid>Spring-boot-starter-test</artifactid>            <scope>Test</Scope>        </Dependency>        <dependency>            <groupId>Org.springframework.boot</groupId>            <artifactid>Spring-boot-starter-freemarker</artifactid>        </Dependency>    </dependencies>    <build>        <plugins>            <plugin>                <groupId>Org.springframework.boot</groupId>                <artifactid>Spring-boot-maven-plugin</artifactid>            </plugin>        </plugins>    </Build></Project>

Spring Boot Controller

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.