欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot开发web api应用实践(一)入门 博客分类: spring boot 实践笔记 spring boot入门教程 

程序员文章站 2024-03-07 09:54:45
...

利用Spring Boot快速搭建一个web应用,简直是太方便了。本例快速搭建一个spring mvc应用,为前端提供api请求接口,不包含web页面,数据库持久层采用默认的spring-jdbc。

一、环境准备:

     1.安装maven及ide(eclipse或idea)并安装maven插件;

     2.mysql或其他数据库(本例使用mysql);

     3.jdk1.8+

 

二、建立工程

     步骤:1.编辑pom.xml文件添加spring-boot依赖

                2.编写启动类(AppMain.java)

                3.编写Controller路由类(LoginController.java)

                4.启动测试

 

     1.在ide里建立一个简单maven工程,编辑pom.xml文件,内容如下:

<?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>com.zweichxu.springboot</groupId>
	<artifactId>spring-boot-web</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>spring-boot-web</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.1.RELEASE</version>
		<relativePath/>  
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
		<!-- 创建一个web应用,默认j2ee容器是spring boot内置的tomcat,
		     默认访问端口是8080,默认访问context-path是“/”  
		 -->
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<exclusions>
			    <exclusion>
			        <groupId>org.springframework.boot</groupId>
			        <artifactId>spring-boot-starter-logging</artifactId>
			    </exclusion>
			</exclusions>
		</dependency>
                
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>21.0</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-log4j</artifactId>
			<version>1.3.8.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
			    <groupId>org.springframework.boot</groupId>
			    <artifactId>spring-boot-maven-plugin</artifactId>
			    <configuration>
			        <executable>true</executable> 
			    </configuration>
			</plugin>
		</plugins>
	</build>
</project>

    2.建立应用启动类(AppMain.java),也是应用启动入口:

package com.zweichxu.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 *  
 * @author zweichxu
 * @date 2017年3月30日 14:12:41
 * @version 1.0
 */
@SpringBootApplication
public class AppMain {
    public static void main(String[] args){
          SpringApplication.run(AppMain.class, args);
    }
}

    spring boot应用只允许惟一一个类拥有public static void main(String[] args)方法。该类最主要的是@SpringBootApplication注解,该注解是@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan三个注解的组合。三个注解的功能,从名字上可以猜测出来,不多解释。

 启动spring boot应用只需要一句代码:SpringApplication.run(AppMain.class, args);

 

   

3. 建立Controller类(LoginController.java)接收客户端请求

package com.zweichxu.springboot.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zweichxu.platform.entity.BaseResp;
import com.zweichxu.platform.util.Util;
import com.zweichxu.springboot.model.User; 

@RestController
public class LoginController { 
    @RequestMapping(value="login")
    public BaseResp doLogin(@RequestParam("acct") String userName, 
                            @RequestParam("pwd") String password){
        if (Util.isEmpty(userName) || Util.isEmpty(password)){
            return BaseResp.fail(BaseResp.RET_CODE_PROTOCOL_ERROR, "用户名及密码均不能为空");
        }
       
        //do something
        User user = new User();
        user.setName("小王");
        user.setAccount(userName);
        return BaseResp.success().setRetMsg("登录成功").addProperty("loginUser", user);
    }
    
    @RequestMapping(value="logout")
    public BaseResp doLogout(){
        //do something
       
        return BaseResp.success().setRetMsg("登出成功");
    }
}

   注意:所有需要通过注解自动注入的类(如LoginController类,有@RestController注解),都必须放在启动类所在的包(com.zweichxu.springboot)或子包(如com.zweichxu.springboot.controller)下面,否则需要指定扫描路径。

 

    返回值基础类(BaseResp.java)

package com.zweichxu.platform.entity;

import java.util.HashMap;

import com.fasterxml.jackson.annotation.JsonIgnore;

/**
 * 响应信息基础类
 * 
 * @author zweichxu
 * 
 */
public class BaseResp extends HashMap<String, Object> {
    private static final long serialVersionUID = -4036551233822181281L;
     
    public BaseResp() {
        this(0, "");
    }
    
    public BaseResp(Integer retCode) {
        setRetCode(retCode);
    }
    
    public BaseResp(Integer retCode, String retMsg) {
        setRetCode(retCode);
        setRetMsg(retMsg);
    }

    public String getToken(){
        return (String) get("token");
    }

    public BaseResp setToken(String token){
        put("token", token);
        return this;
    }

    public Integer getRetCode(){
        return (Integer) get("retCode");
    }

    public BaseResp setRetCode(Integer retCode){
        put("retCode", retCode);
        return this;
    }

    public String getRetMsg(){
        return (String) get("retMsg");
    }

    public BaseResp setRetMsg(String retMsg){
        put("retMsg", retMsg);
        return this;
    }
    
    public BaseResp addProperty(String propName, Object propValue){
        put(propName, propValue);
        return this;
    }
      
    @JsonIgnore
    public boolean isFail() {
        return !(isSuccess());
    }
    
    @JsonIgnore
    public boolean isSuccess() {
        Integer retCode = getRetCode();
        return retCode != null && retCode == RETURN_SUCCESS;
    }
    
    public static BaseResp success(){
        return new BaseResp(RETURN_SUCCESS, "操作成功");
    }
    
    public static BaseResp success(String retMsg){
        BaseResp resp = success();
        resp.setRetMsg(retMsg);
        return resp;
    }
    
    public static BaseResp fail(Integer retCode, String retMsg){
        return new BaseResp(retCode, retMsg);
    }
    
    public static BaseResp fail(String retMsg){
        return new BaseResp(RETURN_FAILURE, retMsg);
    }
    
    /**操作成功*/
    public static final int RETURN_SUCCESS = 1;
    
    /**操作失败*/
    public static final int RETURN_FAILURE = 0;
    
    /**数据记录不存在:0x00001002*/
    public static final int DATA_NOT_EXIST = 0x00001002;
    
    /**返回码:协议参数错误:0x00002001*/
    public static final int RET_CODE_PROTOCOL_ERROR = 0x00002001;
}

 

4.启动应用:在ide上直接运行AppMain.java类,然后在浏览器地址栏访问:http://localhost:8080/login?acct=zweichxu&pwd=123,可以看到浏览器页面返回值:

spring boot开发web api应用实践(一)入门
            
    
    博客分类: spring boot 实践笔记 spring boot入门教程 
 

至此,一个简单的web应用搭建成功。

下一篇介绍如何修改访问端口(上面浏览器图片中可以看出,我已将默认的8080端口改成了18081),如何开启数据库访问层;

 

  

 

 

 

 

 

  • spring boot开发web api应用实践(一)入门
            
    
    博客分类: spring boot 实践笔记 spring boot入门教程 
  • 大小: 14.1 KB