后端开发
后端开发的步骤:
- 根据需求,分析数据库建库、建表、准备数据(主键类型应是包装类,bigint)
- 建立web模块web类型的maven项目
- 手动创建src、resources、test-java目录
- 建立package、entity、dao、service、controller
- pom依赖,web模块依赖,webmvc,jackson依赖
- entity实体类
- dao接口,增加自定义的复杂关联查询(注解)
- service接口注入dao,调用相应方法
- 对service做单元测试(junit)
- controller,使用RESTful风格请求,完成控制层
- 对controller进行测试(使用postman,get查,put修改,post插,delete删)VO(试图对象)
新建一个模块web
依赖
- pom依赖
<?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>com.spring</groupId>
<artifactId>web</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>web Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.1.5.RELEASE</spring.version>
<aspectj.version>1.9.2</aspectj.version>
<junit.version>4.12</junit.version>
<log4j.version>1.2.17</log4j.version>
<slf4j.version>1.7.12</slf4j.version>
<mysql.version>5.1.47</mysql.version>
<mybatis.version>3.5.0</mybatis.version>
<mybatis-spring.version>2.0.0</mybatis-spring.version>
<tk-mybatis.version>4.1.5</tk-mybatis.version>
<druid.version>1.1.14</druid.version>
<lombok.version>1.18.6</lombok.version>
<jackson.version>2.9.8</jackson.version>
<jackson-mapper.version>1.9.13</jackson-mapper.version>
</properties>
<dependencies>
<!--Spring-context依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring-tx事务依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring-jdbc依赖,主要使用其中的JPA和事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring-web依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring-webmvc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--mybatis-spring依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<!--通用mapper依赖-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>${tk-mybatis.version}</version>
</dependency>
<!--druid连接池依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!--lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!--junit依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- log4j日志依赖 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!--jackson相关依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${jackson-mapper.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<build>
<finalName>web</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<!-- war插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<warName>web</warName>
</configuration>
</plugin>
</plugins>
<!-- 加载资源 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
- web依赖
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>web</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<!-- web容器配置,当tomcat启动,加载 web.xml配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 加载spring容器 ,当服务器启动,加载spring_mybatis.xml配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:Spring-mybatis.xml</param-value>
</context-param>
<!-- 过滤器统一编码 -->
<filter>
<filter-name>Spring character encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param><!-- 过滤请求字符集 -->
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param><!-- 过滤响应字符集 -->
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Spring character encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 控制器配置,当tomcat启动,加载springMVC-servlet.xml配置 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- mvc控制器映射 -->
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- CORS Filter -->
<filter>
<filter-name>CORSFilter</filter-name>
<filter-class>com.spring.web.util.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
- springMVC-servlet
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--启动mvc注解-->
<mvc:annotation-driven/>
<!--扫描含有注解的包 (控制器所在包)-->
<context:component-scan base-package="com.spring.web.controller"/>
<!--保证静态资源不被拦截-->
<mvc:default-servlet-handler/>
</beans>
- Spring-mybatis
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--读入外部数据库连接属性文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--扫描Service包的组件-->
<context:component-scan base-package="com.spring.web.service"/>
<!--通过druid配置数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- 初始化大小 -->
<property name="initialSize" value="20"/>
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20"/>
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0"/>
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000"/>
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000"/>
<!-- 连接空闲时测试是否有效 -->
<property name="testWhileIdle" value="false"/>
<!-- 获取连接时测试是否有效 -->
<property name="testOnBorrow" value="false"/>
<!-- 归还连接时是否测试有效 -->
<property name="testOnReturn" value="false"/>
<!-- 打开PSCache缓存,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true"/>
<property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>
</bean>
<!-- 配置mybatis的Session -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.spring.web.entity"/>
</bean>
<!-- 配置通用Mapper -->
<bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.spring.web.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="markerInterface" value="com.spring.web.dao.BaseDAO"/>
<property name="properties">
<value>
mappers = com.spring.web.dao.BaseDAO
IDENTITY = MYSQL
</value>
</property>
</bean>
<!--事务管理bean -->
<bean id="manager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 使用声明式事务 -->
<tx:annotation-driven transaction-manager="manager"/>
</beans>
建立Course,CourseVO,SysUser类
- Course类
package com.spring.web.entity;
import lombok.Data;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name="t_course")
@Data
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long courseId;
private String courseName;
private Long userId;
private String courseClass;
private String cover;
private String courseCode;
private Short finished;
}
- CourseVO类
package com.spring.web.entity;
import lombok.Data;
@Data
public class CourseVO {
private Long courseId;
private String courseName;
private Long userId;
private String courseClass;
private String cover;
private String courseCode;
private Short finished;
private String username;
private String avatar;
}
- SysUser类
package com.spring.web.entity;
import lombok.Data;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name="t_sys_user")
@Data
public class SysUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
private String mobile;
private String password;
private String username;
private String avatar;
}
建立BaseDAO,CourseDAO,SysUserDAo接口
- BaseDAO接口
package com.spring.web.dao;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
/**
* 通用DAO接口
*/
public interface BaseDAO<T> extends Mapper<T>, MySqlMapper<T> {
}
- CourseDAO接口
package com.spring.web.dao;
import com.spring.web.entity.Course;
import com.spring.web.entity.CourseVO;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface CourseDAO extends BaseDAO<Course> {
//自定义的多表关联查询
@Results({@Result(column = "course_id",property = "courseId"),
@Result(column = "course_name",property = "courseName"),
@Result(column = "user_id",property = "userId"),
@Result(column = "course_class",property = "courseClass"),
@Result(column = "cover",property = "cover"),
@Result(column = "course_code",property = "courseCode"),
@Result(column = "finished",property = "finished"),
@Result(column = "username",property = "username"),
@Result(column = "avatar",property = "avatar")
})
@Select("SELECT a.*,b.username,b.avatar FROM t_course a LEFT JOIN t_sys_user b ON a.`user_id`=b.`user_id`")
List<CourseVO> selectCurrentCourses();
}
- SysUserDAO接口
package com.spring.web.dao;
import com.spring.web.entity.SysUser;
public interface SysUserDAO extends BaseDAO<SysUser> {
}
Service类
- CourseService类
package com.spring.web.service;
import com.spring.web.entity.CourseVO;
import java.util.List;
public interface CourseService {
List<CourseVO> selectCurrentCourses();
}
- CourseService实现类
package com.spring.web.service.impl;
import com.spring.web.dao.CourseDAO;
import com.spring.web.entity.CourseVO;
import com.spring.web.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class CourseServiceImpl implements CourseService {
@Autowired
private CourseDAO courseDAO;
@Override
public List<CourseVO> selectCurrentCourses() {
return courseDAO.selectCurrentCourses();
}
}
对CourseServiceImpl进行测试
- CourseServiceImplTest类
package com.spring.web.service.impl;
import com.spring.web.entity.CourseVO;
import com.spring.web.service.CourseService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/Spring-mybatis.xml"})
public class CourseServiceImplTest {
@Autowired
private CourseService courseService;
@Test
public void selectCurrentCourses() {
List<CourseVO> courseVOList = courseService.selectCurrentCourses();
courseVOList.forEach(courseVO -> System.out.println(courseVO));
}
}
controller包
- CourseController类
package com.spring.web.controller;
import com.spring.web.entity.CourseVO;
import com.spring.web.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class CourseController {
@Autowired
private CourseService courseService;
@RequestMapping(value = "courses", method = RequestMethod.GET)
public List<CourseVO> selectCourses() {
List<CourseVO> courseVOList = courseService.selectCurrentCourses();
return courseVOList;
}
}
-
对controller进行测试
测试结果
util包
- CORSFilter
package com.spring.web.util;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CORSFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("work");
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
- ResponseUtil
package com.spring.web.util;
public class ResponseUtil {
private int code;
private String message;
private Object data;
public ResponseUtil(int code, String message) {
this.code = code;
this.message = message;
}
public ResponseUtil(int code, String message, Object data) {
this.code = code;
this.message = message;
this.data = data;
}
@Override
public String toString() {
return "ResponseUtil{" +
"code=" + code +
", message='" + message + '\'' +
", data=" + data +
'}';
}
}
前端开发
-新建一个html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Vue.js-访问API接口数据-蓝墨云班课练习</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- 通过CDN引入Vue.js -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 通过CDN引入axios -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<style type="text/css">
body {
background-color: #eee;
}
.top {
width: 80%;
margin: 0 auto;
display: flex;
justify-content: space-between;
}
hr{
width: 80%;
color: #efefef;
}
.container {
width: 80%;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
padding-left: 20px;
padding-top: 10px;
}
.card {
width: 215px;
height: 330px;
display: flex;
flex-direction: column;
border: 1px solid #eee;
margin-right: 25px;
margin-bottom: 10px;
background-color: #fff;
justify-content: center;
padding-left: 5px;
padding-right: 5px;
padding-top: 5px;
}
.cover {
width: 95%;
height: 75%;
margin-left: 7px;
overflow: hidden;
}
.cover img{
width: 100%;
transition: all 5s;
}
.cover img:hover{
transform: scaleX(1.1);
}
p {
font-size: 12px;
margin-bottom: 5px;
}
.teacher {
display: flex;
justify-content: space-between;
}
.left {
display: flex;
}
.avatar img {
width: 30px;
height: 30px;
border-radius: 50%;
margin-right: 5px;
}
.code {
color: #00BBDD;
margin-top: 5px;
}
.card1{
width: 215px;
height: 330px;
display: flex;
flex-direction: column;
border: 1px solid #eee;
margin-right: 25px;
margin-bottom: 10px;
background-color: #fff;
justify-content: center;
padding-left: 5px;
padding-right: 5px;
padding-top: 5px;
-webkit-filter: grayscale(100%);
filter: grayscale(100%);
}
</style>
</head>
<body>
<div id="app">
<div class="top">
<p>进行中的班课</p>
<p>{{count}}个进行中的班课</p>
</div>
<hr>
<div class="container">
<div class="card" v-show="iffinished===course.finished" v-for="(course, index) in courses" :key="index">
<div class="cover">
<img :src="'img/'+course.cover">
</div>
<div class="course-class">
<p>{{course.courseClass}}</p>
</div>
<div class="course-name">
<p>{{course.courseName}}</p>
</div>
<div class="teacher">
<div class="left">
<div class="avatar">
<img :src="'img/'+course.avatar">
</div>
<div class="username">
<p class="code">{{course.username}}</p>
</div>
</div>
<div class="course-code">
<p class="code" v-if="loginUserId === course.userId">{{course.courseCode}}</p>
</div>
</div>
</div>
</div>
<div class="top">
<p>已结束的班课的班课</p>
<p>{{courses.length-count}}个已结束的班课</p>
</div>
<hr>
<div class="container">
<div class="card1" v-show="iffinished!==course.finished" v-for="(course, index) in courses" :key="index">
<div class="cover">
<img :src="'img/'+course.cover">
</div>
<div class="course-class">
<p>{{course.courseClass}}</p>
</div>
<div class="course-name">
<p>{{course.courseName}}</p>
</div>
<div class="teacher">
<div class="left">
<div class="avatar">
<img :src="'img/'+course.avatar">
</div>
<div class="username">
<p class="code">{{course.username}}</p>
</div>
</div>
<div class="course-code">
<p class="code" v-if="loginUserId === course.userId">{{course.courseCode}}</p>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
iffinished:0,
loginUserId: 1,
courses: []
},
created: function() {
var _this = this;
axios.get('http://192.168.43.194:8080/web/courses')
.then(function(response) {
console.log(response.data);
_this.courses = response.data;
})
},
computed:{
count:function(){
var clength=this.courses.length;
var num=0;
for(var i=0;i<clength;i++){
if(this.iffinished===this.courses[i].finished){
num++
}
}
return num;
}
}
})
</script>
</body>
</html>
结果