开发社区首页
1.搭建开发环境2.前置知识
基础测试Spring的一些知识点SpringMVC简单使用Mybatis 3.首页开发4. 项目调试技巧
开发社区首页 1.搭建开发环境使用IntelliJ IDEA的Spring Initializr创建一个新的项目。
并勾选所需要的依赖,并创建项目。
图中红框中的文件暂时用不到,可以先删掉,也可以保留。
进入启动类,并点击运行。
可以看到项目运行在8080端口,我们进入浏览器访问localhost:8080,会得到如下页面,因为这是一个新建的项目,什么也没有。
现在我们做一个简单的测试,给新建的项目提供一个简单的功能,并希望浏览器能够访问到。
首先在com.nowcoder.community包下新建一个名为controller的包然后在controller包下新建一个HelloController类,并添加如下代码
package com.nowcoder.community.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello() {
return "hello, springboot";
}
}
最后启动项目,并访问http://localhost:8080/hello,得到如下结果。
application.properties文件的功能是对项目进行一些配置,例如
server.port=8888 server.servlet.context-path=/community spring.thymeleaf.cache=false #用于关闭模板引擎的缓存
上面两行代码表示项目启动在8888端口,并且项目的访问路径前都要加上/community,才能正确访问资源。此时,我们只有访问http://localhost:8888/community/hello才能得到hello, springboot。
CommunityApplication是一个主启动类也是一个配置类,如果我们想让CommunityApplicationTests也以CommunityApplication为配置类,可以将CommunityApplicationTests按照如下方式修改代码,并运行。
package com.nowcoder.community;
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
@ContextConfiguration(classes = CommunityApplication.class)
class CommunityApplicationTests implements ApplicationContextAware {
@Test
void contextLoads() {
System.out.println(applicationContext);
}
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
会得到org.springframework.web.context.support.GenericWebApplicationContext@58326051,而输出的applicationContext就是spring容器。
继续做一个测试,让applicationContext去管理bean。
首先在com.nowcoder.community包下新建一个名为dao的包然后在dao包下新建一个TestDao接口和TestDaoImpl类,并添加如下代码
package com.nowcoder.community.dao;
public interface TestDao {
String test();
}
package com.nowcoder.community.dao;
import org.springframework.stereotype.Repository;
@Repository
public class TestDaoImpl implements TestDao{
@Override
public String test() {
return "TestDaoImpl method";
}
}
最后在CommunityApplicationTests类的contextLoads方法中添加,如下两行代码并运行
TestDao dao = applicationContext.getBean(TestDao.class); System.out.println(dao.test());
输出TestDaoImpl method
Spring的一些知识点给Bean自定义名字:@Component(“名字”)
初始化方法@PostConstruct,在构造器之后调用. 销毁对象之前调用,@PreDestroy.
@Scope()指定单例或者多例
@Configuration配置类,用以装载使用第三方类.
自动注入:@Autowired
SpringMVC简单使用在HelloController中添加以下代码,测试get请求
访问http://localhost:8888/community/http
@RequestMapping("/http")
public void http(HttpServletRequest request, HttpServletResponse response) {
//获取请求数据
System.out.println(request.getMethod()); //打印请求方法
System.out.println(request.getServletPath()); //打印请求路径
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {//依次打印所有的请求头
String name = headerNames.nextElement();
String value = request.getHeader(name);
System.out.println(name + "=" + value);
}
System.out.println(request.getParameter("message"));//获取请求携带的参数
//返回响应数据
response.setContentType("text/html;charset=utf-8"); //设置返回的响应数据类型
try {
PrintWriter writer = response.getWriter();
writer.write("牛客网"); //设置浏览器显示的文本
} catch (IOException e) {
e.printStackTrace();
}
}
访问http://localhost:8888/community/students?current=1&limit=20
//GET请求
// /student?current=1&limit=20
@RequestMapping(path = "/students", method = RequestMethod.GET)
public String getStudents(
@RequestParam(name = "current", required = false, defaultValue = "1") int current,
@RequestParam(name = "limit", required = false, defaultValue = "10") int limit) {
System.out.println(current);
System.out.println(limit);
return "students list";
}
访问http://localhost:8888/community/students2/current=1/limit=20
@RequestMapping(path = "/students2/current={current}/limit={limit}" , method = RequestMethod.GET)
public String getStudents2(
@PathVariable(name = "current", required = false) int current,
@PathVariable(name = "limit", required = false) int limit) {
System.out.println(current);
System.out.println(limit);
return "students2 list";
}
测试post请求
在static下新建一个StudentInfo.html文件
StudentInfo
在HelloController添加方法
@RequestMapping(path = "/studentInfo", method = RequestMethod.POST)
public String getStudentInfo(String name, int age) {
System.out.println(name);
System.out.println(age);
return "提交成功";
}
访问http://localhost:8888/community/studentInfo并提交,查看控制台和网页显示内容
测试响应html数据
在HelloController添加方法
@RequestMapping(path = "/teacherInfo", method = RequestMethod.GET)
public ModelAndView getTeacherInfo() {
ModelAndView mv = new ModelAndView();
mv.addObject("name", "张三");
mv.addObject("age", "30");
mv.setViewName("/demo/teacherInfo");
return mv;
}
并在templates文件夹下创建demo文件夹,在demo文件夹下新建teacherInfo.html。最后访问http://localhost:8888/community/teacherInfo
teacherInfo
测试响应html数据-2
修改HelloController类上的@RestController为@Controller,并在HelloController添加方法。最后访问http://localhost:8888/community/teacherInfo2
@RequestMapping(path = "/teacherInfo2", method = RequestMethod.GET)
public String getTeacherInfo2(Model model) {
ModelAndView mv = new ModelAndView();
model.addAttribute("name", "李四");
model.addAttribute("age", "40");
return "/demo/teacherInfo";
}
测试响应json数据
在HelloController添加方法
@RequestMapping(path = "/jsonData", method = RequestMethod.GET) public MapMybatisjsonData() { HashMap map = new HashMap<>(); map.put("name", "张三"); map.put("age", 23); map.put("salary", 8000); return map; }
核心组件
SqlSessionFactory:用于创建SqlSession的工厂类。SqlSession:MyBatis的核心组件,用于向数据库执行SQL。主配置文件:XML配置文件,可以对MyBatis的底层行为做出详细的配置。Mapper接口:就是DAO接口,在MyBatis中习惯性的称之为Mapper。Mapper映射器:用于编写SQL,并将SQL和实体类映射的组件,采用XML、注解均可实现。
示例
使用MyBatis对用户表进行CRUD操作。
在application.properties中配置数据库、Mybatis相关。
首先安装MySQL Server和MySQL Workbench,然后新建一个名为community的数据库,依次执行init_schema.sql和init_data.sql文件。
涉及到的资料在https://www.nowcoder.com/study/live/246/1/2视频下的资料下载中可以下载。
导入mysql包
mysql mysql-connector-java
导入mybatis-spring-boot-starter
org.mybatis.spring.boot mybatis-spring-boot-starter2.2.1
配置数据库和mybatis,以及配置日志级别让控制台打印更多信息
# DataSourceProperties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/community?characterEncoding=utf-8&useSSL=false&serverTimezone=Hongkong
spring.datasource.username=root
spring.datasource.password=lihonghe
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.maximum-pool-size=15
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.idle-timeout=30000
# MybatisProperties
mybatis.mapper-locations=classpath:mapper
public class Page {
// 当前页码
private int current = 1;
// 限制上限
private int limit = 10;
// 数据总数(用于计算总页数)
private int rows;
// 查询路径(用来复用分页链接)
private String path;
public int getCurrent() {
return current;
}
public void setCurrent(int current) {
if (current >= 1) {
this.current = current;
}
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
if (limit >= 1 && limit <= 100) {
this.limit = limit;
}
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
if (rows >= 0) {
this.rows = rows;
}
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public int getOffset() {
// current * limit - limit
return (current - 1) * limit;
}
public int getTotal() {
// rows /limit
if (rows % limit == 0) {
return rows / limit;
} else {
return rows / limit + 1;
}
}
public int getFrom() {
int from = current - 2;
return from < 1 ? 1 : from;
}
public int getTo() {
int to = current + 2;
int total = getTotal();
return to > total ? total : to;
}
}
在com/nowcoder/community/controller下新建HomeController,并访问http://localhost:8888/community/index
package com.nowcoder.community.controller;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class HomeController {
@Autowired
private DiscussPostService discussPostService;
@Autowired
private UserService userService;
@GetMapping("/index")
public String getIndexPage(Model model, Page page) {
//方法调用前,SpringMVC会自动实例化Model和Page,并将Page注入Model
//所以,在thymeleaf中可以直接访问Page对象中的数据
page.setRows(discussPostService.findDiscussPostRows(0));
page.setPath("/index");
List list = discussPostService.findDiscussPosts(0, page.getOffset(), page.getLimit());
List
4. 项目调试技巧
响应状态码的含义服务端断点调试技巧客户端断点调试技巧设置日志级别,并将日志输出到不同的终端
在src/test/java/com/nowcoder/community下创建LoggerTests类
package com.nowcoder.community;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class LoggerTests {
private static final Logger logger = LoggerFactory.getLogger(LoggerTests.class);
@Test
public void testLogger() {
System.out.println(logger.getName());
logger.debug("debug log");
logger.info("info log");
logger.warn("warn log");
logger.error("error log");
}
}
在src/main/resources下导入logback-spring.xml文件,配置日志输出文件的位置等信息。
discussPosts.add(map);
}
}
model.addAttribute("discussPosts", discussPosts);
return "/index";
}
}
## 4. 项目调试技巧
* 响应状态码的含义
* 服务端断点调试技巧
* 客户端断点调试技巧
* 设置日志级别,并将日志输出到不同的终端
在src/test/java/com/nowcoder/community下创建LoggerTests类
```Java
package com.nowcoder.community;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class LoggerTests {
private static final Logger logger = LoggerFactory.getLogger(LoggerTests.class);
@Test
public void testLogger() {
System.out.println(logger.getName());
logger.debug("debug log");
logger.info("info log");
logger.warn("warn log");
logger.error("error log");
}
}
在src/main/resources下导入logback-spring.xml文件,配置日志输出文件的位置等信息。



