后端
三层架构搭建
userServlet类
package com.wedu.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wedu.dao.UserDao;
import com.wedu.dao.impl.UserDaoImpl;
import com.wedu.entity.User;
import com.wedu.service.UserService;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
UserDao userDao = new UserDaoImpl();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<User> user = userDao.find();
ObjectMapper objectMapper = new ObjectMapper();
//将数据库查询的结果封装为一个JSON类型的数据
String data = objectMapper.writeValueAsString(user);
//设置一下响应的编码格式
response.setCharacterEncoding("utf-8");
//获取输出流
PrintWriter printWriter = response.getWriter();
printWriter.append(data);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
实体类
package com.wedu.entity;
/**
* @author chunhua
* @date 2023/11/2 20:39
*/
public class User {
private int id;
private int age;
public User() {
}
public User(int id, int age) {
this.id = id;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", age=" + age +
'}';
}
}
dao层实现类
package com.wedu.dao.impl;
import com.wedu.dao.UserDao;
import com.wedu.entity.User;
import com.wedu.util.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class UserDaoImpl implements UserDao {
Connection connection = null;
QueryRunner qr = new QueryRunner();
String sql = null;
@Override
public List<User> find() {
try {
connection = JDBCUtils.getConnection();
sql = "select * from user ";
qr = new QueryRunner(JDBCUtils.getDataSource());
// BeanListHandler<User> handler = new BeanListHandler<>(User.class);
List<User> result = qr.query(connection, sql, new BeanListHandler<>(User.class));
return result;
}catch (Exception e){
e.printStackTrace();
return null;
}finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
接口:
package com.wedu.dao;
import com.wedu.entity.User;
import java.util.List;
public interface UserDao {
List<User> find();
}
mvn仓库:(获取相关的坐标,jar包等)
maven的安装
参考这篇博客: Maven安装与配置,Idea配置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>org.example</groupId>
<artifactId>VUEdemo1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils -->
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.3</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<!-- 端口号-->
<port>8080</port>
<path>/</path>
</configuration>
<version>2.2</version>
</plugin>
</plugins>
</build>
</project>
运行后端测试
前端连接
后端接口写在vue.config.js中
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
// transpileDependencies: true,
devServer: {
port:8082,
proxy: {
'/api': {
target: 'http://127.0.0.1:8080/',// 后端接口
changeOrigin: true, // 是否跨域
pathRewrite: {
'^/api': '/'
}
}
}
}
})
main.js中引入axios
在utils包下新建一个
import axios from 'axios'
export function request(config) {
const request = axios.create({
baseURL: 'api', // 后端请求端口设置,根据自己的端口进行设置
timeout: 4000 // 超时时间
})
// request 请求拦截
// 可以在请求发送前对请求做一些处理
// eg.统一加上token,对请求参数统一加密
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
// console.log(config);
// config.headers['token'] = user.token; // 设置请求头
return config
}, error => {
console.log(error);
});
// response 响应拦截
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
response => {
let res = response.data;
// console.log(res);
// 如果是返回的文件
if (response.config.responseType === 'blob') {
return res
}
// 兼容服务端返回的字符串数据
if (typeof res === 'string') {
// 如果是json字符串,将json字符串转换为json对象
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error) // 控制台打印错误信息,用于调试
})
// 直接返回
return request(config)
}
// export default request
新建一个vue文件,实现前端页面,数据传入前端页面
组件官网element
<template>
<div>
<el-container style="height: 700px; border: 1px solid #eee">
<el-header style="font-size: 40px; background-color: aquamarine;">学习vue平台</el-header>
<el-container>
<el-aside width="200px">
<el-menu :default-openeds="['1', '3']">
<el-submenu index="1">
<template slot="title"><i class="el-icon-message"></i>系统信息管理</template>
<el-menu-item index="1-1">部门管理</el-menu-item>
<el-menu-item index="1-2">人员管理</el-menu-item>
</el-submenu>
</el-menu>
</el-aside>
<el-main>
<!-- 表单 -->
<el-form :inline="true" :model="searchFrom" class="demo-form-inline">
<el-form-item label="姓名">
<el-input v-model="searchFrom.name" placeholder="姓名"></el-input>
</el-form-item>
<el-form-item label="性别">
<el-select v-model="searchFrom.gender" placeholder="性别">
<el-option label="男" value="1"></el-option>
<el-option label="女" value="2"></el-option>
</el-select>
</el-form-item>
<el-form-item label="入职日期">
<el-date-picker v-model="searchFrom.entrytime" type="daterange" range-separator="至"
start-placeholder="开始日期" end-placeholder="结束日期">
</el-date-picker>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">查询</el-button>
</el-form-item>
</el-form>
<!-- 表格 -->
<el-table :data="tableData" >
<el-table-column prop="id" label="序列" width="100">
</el-table-column>
<!-- <el-table-column prop="date" label="日期" width="140">
</el-table-column>
<el-table-column prop="name" label="姓名" width="120">
</el-table-column> -->
<el-table-column prop="age" label="年龄" width="120">
</el-table-column>
<!-- <el-table-column prop="address" label="地址">
</el-table-column> -->
</el-table>
</el-main>
</el-container>
</el-container>
</div>
</template>
<script>
// import axios from "axios";
import { request } from "../../utils/request";
export default {
data() {
return {
tableData: [{
}],
searchFrom: {
name: '',
gender: '',
entrytime: []
}
}
},
methods: {
onSubmit() {
console.log('submit!');
},
queryUserList(){
request({
url: '/userServlet'
}).then(res => {
console.log(res);
this.tableData = res;
}, err => {
console.log(err);
})
}
},
mounted() {
//发送异步请求,获取数据
// request.get('/userServlet').then((result) =>{
// this.tableData = result.data;
// });
this.queryUserList();
},
created() {
}
}
</script>
<style></style>
运行
数据从数据库导入成功