1. An overview of the

This article introduces the use of spring MVC in Spring Boot, including the following:

  • Implementation of Spring Boot integration JSP: @controller + @requestMapping
  • 2. Simulated login function: ModelAndView
  • 3 Spring Boot restful interface: @restController

2. First demo: Spring Boot integration JSP

Project: MVC

This section realizes spring Boot integrated JSP function

2.1. The pom. The XML

Introduce related classes

The < 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 > < artifactId > MVC < / artifactId > < packaging > jar < / packaging > < name > MVC < / name > <description>Demo project for spring mvc</description> <parent> <groupId>com.hry.spring</groupId> < artifactId > parent < / artifactId > < version > 0.0.1 - the SNAPSHOT < / version > < relativePath >). /parent/pom.xml</relativePath> </parent> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <dependencies> <! -- spring mvc --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId> Commons -io</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>com.alibaba</groupId> < artifactId > fastjson < / artifactId > < version > 1.2.12 < / version > < / dependency > < the dependency > <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <! --<scope>provided</scope>--> </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-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> </dependencies> </project>Copy the code

2.2. The application properties

Prefix =/ web-INF /page/ ## response page default suffix spring.mvc.view.suffix=.jspCopy the code

META-INF/resources/ web-INF /page/

2.3. JSP page configuration

Meta-inf /resources/ : Please configure the JSP files in this directory, otherwise the JSP pages will not be found

META-INF/resources/WEB-INF/page/first/index.jsp

<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> This is spring mvc first page. </body> </html>Copy the code

2.4. FirstControl

The first test is control

@controller: defines the Controller layer class @requestMapping: defines the request URL for this request

On request, return the contents of “meta-INF /resources/ web-INF /page/first/index.jsp”

@ Controller public class FirstControl {/ * * * http://127.0.0.1:8080/first * JSP * @param model * @return */ @requestMapping ("/first") public String META-INF/resources/WEB-INF/page/first/index.jsp * @param model * @return */ @requestMapping ("/first") public String first(Model model) { model.addAttribute("message", "Hello World!" ); return "first/index"; }}Copy the code

2.5. Start MvcApplication

MvcApplication need inherit SpringBootServletInitializer, rewrite the configure method. Methods use fastjson fastJsonHttpMessageConverters said as json parsing tools

Spring MVC demos all use this as a startup class

@SpringBootApplication public class MvcApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(MvcApplication.class); } public static void main(String[] args) { SpringApplication.run(MvcApplication.class, args); } / * * * use fastjson as spring MVC @ return json serialization * * / @ Bean public HttpMessageConverters fastJsonHttpMessageConverters () {  FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); fastConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<? > converter = fastConverter; return new HttpMessageConverters(converter); }}Copy the code

2.6. Test

Perform the request: http://127.0.0.1:8080/first return content:

This is spring mvc first page.Copy the code

3. The second demo: to achieve a simple login function

In the same project MVC as in the previous section, this section lists only the differences. JSP. If successful, go to succ.jsp, otherwise go to home.jsp

3.1. Related JSP pages

The following pages are configured in this directory: meta-INF /resources/ web-INF /page/login

Form.jsp login interface

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="login" method="post">
        username:<input type="text" name="username" />
        <p>
            password:<input type="password" name="password" />
        <p>
            <input type="submit" value="submit" />
    </form>
</body>
</html>Copy the code

home.jsp

<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h2>home</h2> </body> </html>Copy the code

succ.jsp

<html> <head> <meta http-equiv="Content-Type" content="text/html; Charset =UTF-8"> <title>Insert title here</title> </head> <body> <h2> Login </h2> username:${username} <p>password:${password  } </body> </html>Copy the code

3.2. LoginController

Controller class for login

String login(): This method goes to the form.jsp page from the previous section, ModelAndView Login (String Username,String Password) : demonstrates the use of ModelAndView, if successful, to succ.jsp, otherwise to home.jsp

@controller public class LoginController {/** * http://127.0.0.1:8080//login/login @ return * * * / @ RequestMapping (value = "/ login/form", method = RequestMethod. GET) to the public String login(){ return "/login/form"; } /*** * user login * <p> annotation configuration, Only posts can be submitted to this method * @param username * @param password * @return */ @RequestMapping(value="/login/login",method=RequestMethod.POST) public ModelAndView login(String username,String Password){// Verify that the parameters passed are correct, otherwise return to the login page. If (this.checkParams(new String[]{username,password})){// specify the page to return as succ.jsp ModelAndView mav = new ModelAndView("/login/succ"); // Return the argument to the page mav.addObject("username",username); mav.addObject("password", password); return mav; } return new ModelAndView("/login/home"); } /*** * Check whether the parameter is empty * @param params * @return */ private Boolean checkParams(String[] params){for(String param:params){ if(param==""||param==null||param.isEmpty()){ return false; } } return true; }}Copy the code

3.3. Test

Login successful function to perform the url: http://localhost:8080/login/form to fill in the information, it returns:

Log in username: lastName password: 2222Copy the code

Login failure function to perform the url: http://localhost:8080/login/form don’t fill in the content, it returns:

homeCopy the code

4. The third demo: Spring Boot restful interface

In the same project MVC as in the previous section, this section lists only the differences.

4.1 VO

class VO { private String name; private String value; / / set/get slightly}Copy the code

4.2. @ RestController

@restController: defines @requestMapping: defines all methods in a class whose URL prefix is REST. VO getUser() : This method shows that it returns an object, and @RestController is automatically converted to a JSON String. String getUserHtml: This method shows that it returns a field String directly

@restController@requestMapping (value = "/rest") Public class RestControllerTest {/** * Method returns object * http://127.0.0.1:8080/rest/vo * @ return * / @ RequestMapping (value = "/ vo", method = RequestMethod.GET) public VO getUser() { VO vo = new VO(); vo.setName("name"); vo.setValue("value"); return vo; } / direct return content * * * * * * @ http://localhost:8080/rest/string return * / @ RequestMapping (value = "/ string", method = RequestMethod.GET) // @ResponseStatus(HttpStatus.OK) public String getUserHtml() { return "{'example':'---'}"; }}Copy the code

4.3. Test

Test demonstration returns an object that @ RestController will automatically be converted to a json string perform url: http://localhost:8080/rest/vo returns:

{ "name":"name", "value":"value" }Copy the code

Testing would be performed directly returns a string: url: http://localhost:8080/rest/string returns:

"{'example':'---'}"Copy the code

6. Code

Please use tag V0.3 as much as possible. Do not use master, because master is always changing. There is no guarantee that the code in this article will always be the same as the code on Github