【Java项目实战】牛客网论坛项目1 - Spring入门与初识SpringMVC

Spring 入门

SpringInitializr

IDEA 专业版自带的功能,也可以直接搜索对应网站,通过网站生成包后导入 IDEA 中使用

下面是初始化的参数:

  • 选用 SpringBoot2.7.15
  • 导入依赖 Web、DevTools、Thymeleaf

之后等待构建完毕即可


ApplicationContextAware

在测试函数中使用 ApplicationContextAware 来获取应用上下文

package com.zhiller.community.zhillercommunity;

import com.zhiller.community.zhillercommunity.dao.AlphaDao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeansException;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.test.context.ContextConfiguration;

@SpringBootTest
// @SpringBootTest 是 Spring Boot 提供的测试注解,用于表示这是一个 Spring Boot 的测试类。
// 它会自动加载 Spring Boot 的配置,并启动 Spring 容器,以便进行集成测试。
@ContextConfiguration(classes = ZhillerCommunityApplication.class)
// @ContextConfiguration 用于指定 Spring 容器的配置信息。
// 这里使用 ZhillerCommunityApplication.class 表示使用该类所在的包作为配置信息。
class ZhillerCommunityApplicationTests implements ApplicationContextAware {
    
    

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    
    
        this.applicationContext = applicationContext;
    }
    // 实现 ApplicationContextAware 接口的方法,用于获取 Spring 应用上下文对象。

}

Controller

创建 controller 文件

package com.zhiller.community.zhillercommunity.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/alpha")
public class AlphaController {
    
    

    // 处理"/alpha/helloworld"请求,返回字符串响应
    @RequestMapping("/helloworld")
    // @ResponseBody注解表示将方法的返回值直接作为响应体返回,而不是将其解析为视图名称
    @ResponseBody
    public String hello(){
    
    
        return "shit man!";
    }
}

运行 Application,之后打开浏览器,输入 localhost:10086/alpha/helloworld 获取请求结果


DAO

主应用包下新建两个文件,分别是 DAO 接口以及其对应实现类

代码清单:AlphaDao.java

package com.zhiller.community.zhillercommunity.dao;

public interface AlphaDao {
    
    
    String select();
}

代码清单:AlphaDaoImpl.java

package com.zhiller.community.zhillercommunity.dao;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;

@Repository
// @Repository 是 Spring 提供的注解,用于表示该类是一个数据访问对象(DAO)。
// 它会被 Spring 自动扫描并将其注册为 Spring 容器中的一个 Bean。
@Primary
// @Primary 是 Spring 提供的注解,用于表示当存在多个同一类型的 Bean 时,优先选择被标记为 @Primary 的 Bean。
// 在自动装配时,如果没有明确指定要注入哪个 Bean,将会选择被标记为 @Primary 的 Bean。
public class AlphaDaoImpl implements AlphaDao {
    
    
    // AlphaDao 是一个接口,AlphaDaoImpl 类实现了该接口。

    @Override
    public String select() {
    
    
        return "hibernate";
    }
    // 实现了 AlphaDao 接口中的 select() 方法,返回字符串 "hibernate"。
}

最后在主测试类中对这个 DAO 进行测试

@SpringBootTest
@ContextConfiguration(classes = ZhillerCommunityApplication.class)
class ZhillerCommunityApplicationTests implements ApplicationContextAware {
    
    

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    
    
        this.applicationContext = applicationContext;
    }

    @Test
    public void testContext(){
    
    
        System.out.println(applicationContext);
        AlphaDao alphaDao = applicationContext.getBean(AlphaDao.class);
        System.out.println(alphaDao.select());
    }
}

DAO 名称索引

对 DAO 实现类的注解@Repository添加一段字符串描述,即可直接通过该字符串获取该 DAO

@Repository("alpha_hibernate")
@Primary
public class AlphaDaoImpl implements AlphaDao {
    
    
    @Override
    public String select() {
    
    
        return "hibernate";
    }
}

故对应的测试类可以这么写

@Test
public void testContext(){
    
    
    System.out.println(applicationContext);
    AlphaDao alphaDao = applicationContext.getBean("alpha_hibernate",AlphaDao.class);
    System.out.println(alphaDao.select());
}

Service

创建 service 包,下含一个 Service 类

代码清单 AlphaService.java

package com.zhiller.community.zhillercommunity.service;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Service
// @Service 是 Spring 提供的注解,用于表示该类是一个服务类。
// 它会被 Spring 自动扫描并将其注册为 Spring 容器中的一个 Bean。
@Scope("prototype")
// @Scope 是 Spring 提供的注解,用于指定 Bean 的作用域。
// 这里的 "prototype" 表示每次请求该 Bean 都会创建一个新的实例。
public class AlphaService {
    
    
    public AlphaService() {
    
    
        System.out.println("实例化service");
        // 在构造函数中打印一条实例化的信息。
    }

    @PostConstruct
    // @PostConstruct 是 Java 的注解,用于指定在构造函数执行后执行的方法。
    // 在该方法上添加 @PostConstruct 注解后,Spring 会在构造函数执行完毕后调用该方法。
    public void init(){
    
    
        System.out.println("初始化service");
        // 在 init() 方法中打印一条初始化的信息。
    }

    @PreDestroy
    // @PreDestroy 是 Java 的注解,用于指定在 Bean 销毁之前执行的方法。
    // 在该方法上添加 @PreDestroy 注解后,Spring 会在销毁 Bean 之前调用该方法。
    public void destory(){
    
    
        System.out.println("销毁service");
        // 在 destory() 方法中打印一条销毁的信息。
    }
}

对应的测试文件这里不在给出,使用方式和 DAO 完全一致


Config

配置 Config 文件和 service、dao 如出一辙

代码清单 AlphaConfig.java

package com.zhiller.community.zhillercommunity.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;

@Configuration
public class AlphaConfig {
    
    

    @Bean
    public SimpleDateFormat simpleDateFormat(){
    
    
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }
}

自动装配

springboot 提供了自动装配,我们无需获取 applicationcontext 就可以直接使用对应的实例了

// 测试类中使用@Autowired和@Qualifier注解来自动装配依赖关系
@Autowired
// @Qualifier("alpha_hibernate")用于指定要注入的alphaDao的Bean名称为"alpha_hibernate"
@Qualifier("alpha_hibernate")
private AlphaDao alphaDao;

@Autowired
private AlphaService alphaService;

初识 SpringMVC

Http 请求

AlphaService.java 修改代码

添加一个 http 请求,并通过该请求获取指定参数

package com.zhiller.community.zhillercommunity.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

@Controller
@RequestMapping("/alpha")
public class AlphaController {
    
    

    /**
     * 处理映射到 "/alpha/http" 路径的请求
     * 打印请求的 HTTP 方法、请求头信息和请求参数
     * 设置响应内容类型为 text/html;charset=utf-8
     * 获取响应输出流并进行异常处理
     */
    @RequestMapping("/http")
    public void http(HttpServletRequest request, HttpServletResponse response) {
    
    
        // 打印请求的 HTTP 方法
        System.out.println(request.getMethod());

        // 获取所有请求头的名称并打印
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
    
    
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            System.out.println(name + ":" + value);
        }

        // 打印请求参数 "code"
        System.out.println(request.getParameter("code"));

        // 设置响应内容类型为 text/html;charset=utf-8
        response.setContentType("text/html;charset=utf-8");
        try (PrintWriter writer = response.getWriter();)
        {
    
    
            writer.write("<h1>zhiller labs</h1>");
        }catch(IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

GET

package com.zhiller.community.zhillercommunity.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/alpha")
public class AlphaController {
    
    
    /**
     * 处理映射到 "/alpha/getage" 路径的 GET 请求
     * 接受名为 "age" 的请求参数,如果参数不存在则使用默认值 1
     * 打印参数值并返回字符串 "age"
     */
    @GetMapping("/getage")
    @ResponseBody
    public String getAge(
            @RequestParam(name = "age", required = false, defaultValue = "1") int age
    ) {
    
    
        System.out.println(age);
        return "age";
    }

    /**
     * 处理映射到 "/alpha/getid/{id}" 路径的 GET 请求
     * 接受路径变量 "id"
     * 打印路径变量值并返回字符串 "get the id"
     */
    @GetMapping("/getid/{id}")
    @ResponseBody
    public String getId(
            @PathVariable("id") int id
    ) {
    
    
        System.out.println(id);
        return "get the id";
    }
}

POST

随便写一个登录页面,存放位置:resource/static/html/student.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<title>oh my god</title>
	</head>
	<body>
		<div class="main">look this big shit!!!</div>

		<!-- 要注意这里的请求方法为POST,请求url要和springboot里面定义的一致 -->
		<form
			method="post"
			action="/alpha/student"
		>
			<p>
				姓名:<input
					type="text"
					name="name"
					placeholder="请输入您的姓名"
				/>
			</p>
			<p>
				密码:<input
					type="password"
					name="pwd"
					placeholder="******"
				/>
			</p>
			<p>
				<input
					type="submit"
					value="保存"
				/>
			</p>
		</form>
	</body>
</html>

<style>
	.main {
      
      
		font-size: large;
		font-weight: bold;
	}
</style>

然后就是我们的 controller 方法了

@PostMapping("/student")
public void postStudent(String name, String password) {
    
    
    System.out.println(name);
    System.out.println(password);
    return;
}

HTML 渲染

thymeleaf 的作用是帮助我们后端渲染简单的前端界面

但是很明显,在现在前后端分类的大趋势下,这玩意就和当年的 JSP 一样没有前景

建议不学


响应 JSON 数据

package com.zhiller.community.zhillercommunity.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/alpha")
public class AlphaController {
    
    
    /**
     * 处理映射到 "/alpha/emp" 路径的 GET 请求
     * 返回一个包含员工信息的 Map 对象
     */
    @GetMapping("/emp")
    @ResponseBody
    public Map<String, Object> getEmp() {
    
    
        // 创建一个 Map 对象用于存储员工信息
        Map<String, Object> map = new HashMap<>();
        map.put("name", "张三");
        map.put("age", 123);
        return map;
    }
}

猜你喜欢

转载自blog.csdn.net/delete_you/article/details/132645713
今日推荐