1、创建Maven项目
2、创建包
3、登录数据库
4、生成entity、Mapper、mapper、mappers
添加Lombok依赖
<dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.10</version> </dependency> </dependencies>
5、配置sql连接
1.创建jdbc.properties配置文件
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/pig_farm?characterEncoding=utf-8&serverTimezone=UTC&useSSL=false&zeroDateTimeBehavior=convertToNull user=root pwd=123
2.创建mybatis-config.xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="jdbc.properties" /> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${user}"/> <property name="password" value="${pwd}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mappers/TabBoarMapper.xml" /> </mappers> </configuration>
添加mybatis依赖
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.1</version> </dependency>
3.创建连接数据库工具类SqlSessionUtil
package util; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; /** * @description SqlSessionFactory 工厂构建,获取SqlSession对象 * @auther: CDHONG.IT * @date: 2019/10/18-9:46 **/ public class SqlSessionUtil { private static SqlSessionFactory sqlSessionFactory; static{ try { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } public static void main(String[] args) { System.out.println(SqlSessionUtil.getSqlSession()); } }
添加mysql
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.18</version> </dependency>
6、创建测试类测试
package test; import entity.TabBoar; import mapper.TabBoarMapper; import org.apache.ibatis.session.SqlSession; import util.SqlSessionUtil; /** * @Auther: Administrator * @Date: 2020/6/29 15:23 * @Description: */ public class Test { TabBoar tabBoar = new TabBoar(); static TabBoar find(int a) { SqlSession sqlSession = SqlSessionUtil.getSqlSession(); TabBoarMapper tabBoarMapper=sqlSession.getMapper(TabBoarMapper.class); return tabBoarMapper.selectByPrimaryKey(a); } public static void main(String[] args) { System.out.println(find(1)); } }
打印结果:
7、创建GsonUtil工具类
package entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @description * @auther: Lily * @date: 2019/10/17-10:57 **/ @Data @NoArgsConstructor @AllArgsConstructor public class ResponseEntity { private int code; private String msg; private Long count; private Object data; public static ResponseEntity isAdim(Object obj){ return new ResponseEntity(2,null,null,obj); } public static ResponseEntity ok(){ return new ResponseEntity(0,null,null,null); } public static ResponseEntity ok(String msg){ return new ResponseEntity(0,msg,null,null); } public static ResponseEntity error(String msg){ return new ResponseEntity(1,msg,null,null); } public static ResponseEntity data(Object obj){ return new ResponseEntity(0,null,null,obj); } public static ResponseEntity page(long count,Object obj){ return new ResponseEntity(0,null,count,obj); } public static boolean isSuccess(ResponseEntity responseEntity){ return responseEntity.getCode() == 2; } public static boolean isSucce(ResponseEntity responseEntity){ return responseEntity.getCode() == 0; } }
package util; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializer; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * @description * @auther: CDHONG.IT * @date: 2019/10/18-14:31 **/ public class GsonUtil { private static Gson gson = new GsonBuilder() .registerTypeAdapter(LocalDate.class, (JsonSerializer<LocalDate>) (localDate, type, jsonSerializationContext) -> new JsonPrimitive(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))) .registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) (localDateTime, type, jsonSerializationContext) -> new JsonPrimitive(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))) .create(); public static String toJson(Object object){ return gson.toJson(object); } public static <T> T fromJson(String json,Class<T> clazz){ return gson.fromJson(json,clazz); } }
添加json
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency>
8、创建service
package service;
import entity.ResponseEntity;
import entity.TabBoar;
import mapper.TabBoarMapper;
import org.apache.ibatis.session.SqlSession;
import util.SqlSessionUtil;
/**
* @Auther: Administrator
* @Date: 2020/6/29 22:54
* @Description:
*/
public class TabBoarService {
private SqlSession sqlSession = SqlSessionUtil.getSqlSession();
private TabBoarMapper tabBoarMapper = sqlSession.getMapper(TabBoarMapper.class);
public ResponseEntity findById(int id) {
TabBoar tabBoar = tabBoarMapper.selectByPrimaryKey(id);
return ResponseEntity.data(tabBoar);
}
}
9、创建BaseServlet
package servlet; import entity.ResponseEntity; import util.GsonUtil; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Objects; /** * @description * @auther: Lily * @date: 2019/10/17-10:55 **/ public class BaseServlet extends HttpServlet { protected HttpServletRequest request; protected HttpServletResponse response; protected HttpSession session; protected final String REDIRECT = "redirect:"; @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { request = req; response = resp; session = req.getSession(); //student/add , student/add?name=aa String uri = req.getRequestURI(); //StringBuffer url = req.getRequestURL(); //System.out.println(uri); //System.out.println(url); //通过请求地址获取到对应的方法名称 String methodName = uri.substring(uri.lastIndexOf("/") + 1); try { //使用反射获取指定方法名称的方法对象 Class Class<? extends BaseServlet> clazz = this.getClass(); Method method = clazz.getDeclaredMethod(methodName); //打破规则,调用私有方法 method.setAccessible(true); //执行方法,获取结果 Object result = method.invoke(this); if(Objects.nonNull(result)){ if(result instanceof ResponseEntity){ //JSON转换 String jsonStr = GsonUtil.toJson(result); //设置返回格式 resp.setContentType("application/json;charset=utf-8"); //out输出 PrintWriter out = resp.getWriter(); out.write(jsonStr); out.close(); }else if(result instanceof String){ String path = result + ".jsp"; //重定向 if(path.startsWith(REDIRECT)){ path = path.substring(path.indexOf("/")); resp.sendRedirect(path); return; } req.getRequestDispatcher(path).forward(req,resp); }else{ throw new RuntimeException("数据格式不匹配,想清楚。。"); } } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
TabBoarServlet
package servlet; import entity.ResponseEntity; import entity.TabBoar; import service.TabBoarService; import javax.servlet.annotation.WebServlet; /** * @Auther: Administrator * @Date: 2020/6/29 22:49 * @Description: */ @WebServlet("/tabBoar/*") public class TabBoarServlet extends BaseServlet { private TabBoarService tabBoarService = new TabBoarService(); //根据id查询 public ResponseEntity list(){ ResponseEntity tabBoar = tabBoarService.findById(1); System.out.println(tabBoar); return tabBoar; } }
添加servlet
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency>
添加Tomcat
<build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <port>80</port> <path>/</path> <uriEncoding>utf-8</uriEncoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>8</source> <target>8</target> </configuration> </plugin> </plugins> </build>
结果