【Android 安卓】网络编程demo(一) Springboot服务端

汇总:本系列的汇总

下面我们来分别讲一下这些端的配置。

Mysql准备

不需要在mysql中建表,springboot可以自己创建。我们有一个数据库连接,并且记住下面的参数就行了。
在这里插入图片描述

Springboot 配置

  1. 新建Springboot工程,使用maven构建项目(也可以改用gradle构建,但是我看一般非android项目好像都是用maven)。
    在这里插入图片描述
    在这里插入图片描述

  2. 选择如下配置,等待项目构建完成。其中后几个都是和数据库相关的。使用Jdbc和MySQL Driver可以帮助我们访问MySQL数据库,JPA使得我们可以使用Java持久层API(可以帮助我们自动建表、查询等,基本上不用自己写查询语句)。
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

  3. 构建完成后如图所示,其中springboot自动生成的HttptestApplication为程序入口。注意:请不要动这个包的位置,否则springboot可能找不到程序入口。
    在这里插入图片描述

  4. 设置打包成jar。(常规操作,每个教程都是这样的…
    在这里插入图片描述

  5. 配置Mysql。
    找到resources->application.properties:
    在这里插入图片描述
    加入下面内容:

    spring.datasource.url= jdbc:mysql://localhost:3306/httptest?serverTimezone=UTC
    spring.datasource.username= root
    spring.datasource.password= ******(你的密码)
    spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
    spring.datasource.tomcat.max-idle= 10
    spring.datasource.tomcat.max-wait= 1000
    spring.datasource.hikari.minimum-idle= 5 
    spring.datasource.tomcat.initial-size= 5
    

    注意:其中的用户名、密码、端口等要与最开头Mysql连接的设置一致。

    这样Springboot就能够连接到该数据库了。

Springboot 代码编写

  1. 在项目结构中加入下面四个包。其中Controller、Service、Repository对应Javaweb三层架构(Controller调用Service,Service调用Repository);Entity对应数据库中的表格。
    在这里插入图片描述

  2. 在配置文件中加入下述语句,方便spring根据@Entity注解在数据库中创建表格。

    spring.jpa.generate-ddl=true
    
  3. 在Entity中加入User类,并对其使用@Entity 注解,以便自动生成表格。使用@Table注解,可以指定生成的表格名称。
    下面是我写的User的代码。其中的get和set方法最好用IDEA中系统生成的,否则可能出错。

    Tips:写完成员之后,选中所有成员,Alt+insert,在出现的小浮窗中选择Setter and Getter,ctrl+A ,可以一键生成所有成员的get和set函数噢。
    光标停留在哪里,创建的get和set函数就会从哪里插入。

    @Entity
    		@Table(name = "user")
    		public class User {
    		    @Id
    		    String userId;
    		    String userName;
    		    String password;
    		
    		    public String getUserId() {
    		        return userId;
    		    }
    		
    		    public void setUserId(String userId) {
    		        this.userId = userId;
    		    }
    		
    		    public String getUserName() {
    		        return userName;
    		    }
    		
    		    public void setUserName(String userName) {
    		        this.userName = userName;
    		    }
    		
    		    public String getPassword() {
    		        return password;
    		    }
    		
    		    public void setPassword(String password) {
    		        this.password = password;
    		    }
    		}
    

    注意用@Id标识主键:
    在这里插入图片描述

  4. 在Repository中新加入UserRepository接口,使其继承JpaRepository,注意泛型。Jpa会帮我们自动实现一些诸如findAll()这样的简单方法,所以我们不需要在UserRepository中加入这类方法,但是按照用户id密码查找这样的方法需要我们自己实现。不过不用担心,因为IDEA中会有很贴心的代码提示:
    在这里插入图片描述
    最后UserRepository中的代码:

    public interface UserRepository extends JpaRepository<User,String> {
    
        User findByUserIdAndPassword(String userId,String password);
    }
    

    注意:记得在泛型中指定User(需操作的类),和其主键的类型!!!不然会错的错的错的…

  5. 在Service中加入UserService。
    @Service标明其为Service层组件,@Transational保证其事务性。由于UserService会用到UserRepository,故添加userRepository成员,并使用@Autowired注解对其自动注入。

    @Service
    @Transactional
    public class UserService {
        
        @Autowired
        UserRepository userRepository;
    
    }
    

    在其中加入register方法,处理注册。userId重复则注册失败,否则存储用户信息,并返回注册成功。

    public boolean register(String userId, String password){
        List<User> users = userRepository.findAll();
        for (User user : users) {
        	//注意不要用 ==, 用equals
            if(user.getUserId().equals(userId))          //如果userId重复,则返回注册失败
                return false;
        }
    
        //不重复则对其进行注册
        User user = new User();
        user.setUserId(userId);
        user.setPassword(password);
        userRepository.save(user);
        return true;
    }
    

    加入loginCheck方法,返回值为User对象。这里主要是为了后面演示对象在网络中的传输才把返回值设置为对象。

    public User loginCheck(String userId,String password){
            return userRepository.findByUserIdAndPassword(userId,password);
        }
    

    Service层的代码就编写完毕了。

  6. 在Controller中加入UserController。UserController主要调用UserService、接收客户端的网络请求即可。其中比较重要的部分解释:
    @Controller: 标明这是一个Controller层组件
    @ResponseBody:不会返回网页,返回的是java对象对应的JSON串。
    @Autowired:自动注入
    @RequestMapping:标注客户端向服务器发起请求时需要的url,这里以register为例,当客户端需要服务端处理注册事件的时候,需要设置访问的url为http://IP地址:端口号/regist。
    @RequestParam:客户端请求时需要的参数名。

    @Controller
    @ResponseBody
    public class UserController {
    
        @Autowired
        UserService userService;
    
        @RequestMapping(value = "/register",method = RequestMethod.POST)
        public boolean register(@RequestParam("userId") String userId, @RequestParam("password")String password) {
    
            return userService.register(userId,password);
        }
    
        @PostMapping(value = "/login")
        public User loginCheck(@RequestParam("userId") String userId, @RequestParam("password")String password) {
    
            return userService.loginCheck(userId, password);
        }
    
    }
    

    Tips:

    1. @PostMapping = @RequrstMapping + method = RequestMethod.POST
    2. 可以在整个类上添加@RequestMapping注解,假如在UserController上面添加了一个@RequestMapping("/test"),那么注册时需要访问的地址就是http://ip地址:端口号/test/register
    3. @Controller + @ResponseBody = @RestController。
      运行没有错误,服务器就准备完成了。

参考博客:
1. 配置Mysql可能会出现的错误,为什么我中间使用的驱动不是com.mysql.jdbc.Driver的原因
2. 小西芹的spring-boot简单demo系列
(mysql的依赖可以不在建立项目时加入。后续自己加入的版本及配置文件可以看这里~)

  • 8
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Spring Boot NTRIP 服务端示例: ```java @SpringBootApplication public class NtripServerDemoApplication { public static void main(String[] args) { SpringApplication.run(NtripServerDemoApplication.class, args); } @Bean public NtripServer ntripServer() { return new NtripServer(); } @Bean public ServerSocket serverSocket(@Value("${ntrip.server.port}") int port) throws IOException { return new ServerSocket(port); } @Bean public ExecutorService executorService() { return Executors.newFixedThreadPool(10); } @Component public class NtripServer { private final ServerSocket serverSocket; private final ExecutorService executorService; public NtripServer(ServerSocket serverSocket, ExecutorService executorService) { this.serverSocket = serverSocket; this.executorService = executorService; } public NtripServer() { this(null, null); } @Scheduled(fixedRate = 1000) public void acceptConnections() throws IOException { if (serverSocket == null || executorService == null) { return; } Socket clientSocket = serverSocket.accept(); executorService.submit(() -> handleConnection(clientSocket)); } private void handleConnection(Socket clientSocket) { // 处理 NTRIP 客户端连接 try { BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); // 读取客户端发送的 NTRIP 请求 String request = readRequest(in); // 处理请求并发送响应 String response = handleRequest(request); out.println(response); // 关闭连接 clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } } private String readRequest(BufferedReader in) throws IOException { StringBuilder requestBuilder = new StringBuilder(); String line; while ((line = in.readLine()) != null) { requestBuilder.append(line).append("\r\n"); if (line.isEmpty()) { break; } } return requestBuilder.toString(); } private String handleRequest(String request) { // 处理 NTRIP 请求并返回相应的响应 return "OK"; } } } ``` 在上面的示例中,我们创建了一个 `NtripServer` 类来处理 NTRIP 客户端的连接和请求。我们使用了 Spring Boot 的自动配置功能来注入 `ServerSocket` 和 `ExecutorService` 实例。我们还使用了 Spring Boot 的 `@Value` 注解来读取配置文件中的 `ntrip.server.port` 属性,用于指定服务端口。最后,我们使用了 Spring Boot 的 `@Scheduled` 注解来定时接受客户端连接并将连接提交给线程池进行处理。在 `handleConnection` 方法中,我们读取客户端发送的请求,并处理请求并发送响应。注意,这个示例中的 `handleRequest` 方法只是简单地返回了 "OK" 响应,你需要根据你的应用程序需求编写具体的处理逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值