转载

Spring Boot系列八 spring boot集成jsp、restful接口、springmvc基本功能

1. 概述

本文介绍spring boot里的spring mvc部分的用法,主要包括如下:

  • 1 实现 spring boot 集成jsp: @Controller+ @RequestMapping
  • 2 模拟登录功能: ModelAndView
  • 3 spring boot 实现restful接口:@RestController

2. 第一个demo: spring boot集成jsp

工程: mvc

本节实现spring boot集成jsp功能

2.1. pom.xml

引入相关的类

<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-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>

        <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>

2.2. application.properties

# 页面默认前缀目录
spring.mvc.view.prefix=/WEB-INF/page/
## 响应页面默认后缀
spring.mvc.view.suffix=.jsp

注意:自己写的jsp页面请放置到这个目录下“META-INF/resources/WEB-INF/page/”

2.3. JSP页面配置

META-INF/resources/:请将jsp文件配置在这个目录下,如果不配置在这个目录下,则会出现无法找到jsp页面的问题

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

<!DOCTYPE html PUBLIC "-//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>

2.4. FirstControl

第一个测试control

@Controller: 定义controller层类

@RequestMapping:定义本请求的请求url

请求后,返回”META-INF/resources/WEB-INF/page/first/index.jsp”的内容

@Controller
public class FirstControl {

    /**
     * http://127.0.0.1:8080/first
     *  返回页面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";
    }   
}

2.5. 启动类MvcApplication

MvcApplication 需要继承SpringBootServletInitializer,重写configure方法。方法fastJsonHttpMessageConverters表示使用fastjson做为json解析的工具

spring mvc的demo都使用这个做为启动类

@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);
    }

    /**
     * 使用fastjson做为spring mvc的json序列化
     * @return
     */
    @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);
    }
}

2.6. 测试

执行请求: http://127.0.0.1:8080/first

返回内容:

This is spring mvc first page.

3. 第二个demo: 实现简单的登陆的功能

和上节在相同的工程mvc中,本节只列出不同的地方。

功能如下 :我们先登录from.jsp后,用户输入到信息,如果成功,则转到succ.jsp,否则转到home.jsp

3.1. 相关jsp页面

以下页面配置在这个目录中:META-INF/resources/WEB-INF/page/login

form.jsp登录界面

<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>

home.jsp

<!DOCTYPE html PUBLIC "-//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>

succ.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>登陆</h2>

    username:${username }
    <p>password:${password }
</body>
</html>

3.2. LoginController

登录的controller类

String login(): 此方法会转到上节的form.jsp页面

ModelAndView login(String username,String password):演示ModelAndView 的用法,如果成功,则转到succ.jsp,否则转到home.jsp

@Controller
public class LoginController {
    /**
     * 登录页面:http://127.0.0.1:8080//login/login
     *
     * @return
     */
    @RequestMapping(value="/login/form",method=RequestMethod.GET)  
    public String login(){
        return "/login/form";
    }

    /*** 
     * 用户登陆 
     * <p>注解配置,只允许POST提交到该方法 
     * @param username 
     * @param password 
     * @return 
     */  
    @RequestMapping(value="/login/login",method=RequestMethod.POST)  
    public ModelAndView login(String username,String password){  
        //验证传递过来的参数是否正确,否则返回到登陆页面。  
        if(this.checkParams(new String[]{username,password})){  
            //指定要返回的页面为succ.jsp  
            ModelAndView mav = new ModelAndView("/login/succ");  
            //将参数返回给页面  
            mav.addObject("username",username);  
            mav.addObject("password", password);  
            return mav;  
        }  
        return new ModelAndView("/login/home");  
    }



    /*** 
     * 验证参数是否为空 
     * @param params 
     * @return 
     */  
    private boolean checkParams(String[] params){  
        for(String param:params){  
            if(param==""||param==null||param.isEmpty()){  
                return false;  
            }  
        }  
        return true;  
    }  
}

3.3. 测试

登录成功功能

执行url : http://localhost:8080/login/form

随便填入信息,则返回:

登陆
username:lastName
password:2222
登录失败功能

执行url : http://localhost:8080/login/form

不填写内容,则返回:

home

4. 第三个demo: spring boot 实现restful接口

和上节在相同的工程mvc中,本节只列出不同的地方。

4.1. VO

class VO {
    private String name;
    private String value;
    // set/get略
}

4.2. @RestController

@RestController: 定义此类是

@RequestMapping:定义在类上,则所有方法的url前缀是rest;定义在方法上,则作用在方法上

VO getUser():此方法演示返回一个对象,@RestController会自动转化为json字符串

String getUserHtml:此方法演示直接返回一个字段串

@RestController
@RequestMapping(value = "/rest")
public class RestControllerTest {


    /**
     * 方法返回对象
     *  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;
    }

    /**
     *
     * 直接返回内容
     *  http://localhost:8080/rest/string
     * @return
     */
    @RequestMapping(value = "/string", method = RequestMethod.GET)
    // @ResponseStatus(HttpStatus.OK)  
    public String getUserHtml() {
        return "{'example':'---'}";
    }
}

4.3. 测试

测试演示返回一个对象,@RestController会自动转化为json字符串

执行url : http://localhost:8080/rest/vo

返回:

{ "name":"name", "value":"value" }
测试直接返回一个字符串:

执行url : http://localhost:8080/rest/string

返回:

"{'example':'---'}"

6. 代码

上文的详细代码 见github代码,请尽量使用tag v0.3,不要使用master,因为master一直在变,不能保证文章中代码和github上的代码一直相同

原文  http://blog.csdn.net/hry2015/article/details/78462512
正文到此结束
Loading...