介绍
为了应付毕业设计,花了一个多月学习了vue+springboot做一个项目。现在把项目的一些架构和重点整理一下。
1.vue前端
vue主要还是配置问题,我在项目中用到的ajax和element ui是需要自己安装的。然后就是配置问题,主要是应对跨域还有请求头中添加token。
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import Axios from 'axios'
import axios from 'axios'
Vue.prototype.$axios=Axios
Axios.defaults.baseURL="/api"
Vue.use(ElementUI)
Vue.config.productionTip = false
axios.interceptors.request.use(config => {
let token = localStorage.getItem("token");//token保存在本地
if(token){
config.headers.token = token;
}
return config
},error => {
return Promise.reject(error)
})
proxyTable: {
'/api':{
target: "http://localhost:8081/",//我这里后端的端口是8081
changeOrigin:true,
pathRewrite:{
'^/api':''
}
}
},
按照这样配置之后,可以这样访问接口:
this.$axios.get('test',{
params:{
id:'123'
}
}).then(res=>{
console.log(res)
}
})
此外就是看element ui的文档去调配数据。
2.springboot后端
先上后端的目录
comment层
我这里的comment层是主要是跟token相关的,包括生成验证token码,拦截请求配置等,都是一处处借鉴简化来的,比较简单,目的能用就行。
package com.cpu.design.comment;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
//该类就是生成和验证token
public class TokenUitls {
private static final long EXPIRE_TIME= 10*60*60;//token到期时间1小时
private static final String TOKEN_SECRET="ljdyacaads*13nj??"; //密钥盐
public static String generateToken(String username){
String token=null;
try {
Date expireAt=new Date(System.currentTimeMillis()+EXPIRE_TIME);
token = JWT.create()
.withIssuer("auth0")//发行人
.withClaim("username",username)//存放数据
.withExpiresAt(expireAt)//过期时间
.sign(Algorithm.HMAC256(TOKEN_SECRET));
} catch (IllegalArgumentException|JWTCreationException je) {
}
return token;
}
public static Boolean verifyToken(String token){
try {
JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();//创建token验证器
DecodedJWT decodedJWT=jwtVerifier.verify(token);
System.out.println("认证通过:");
System.out.println("username: " + decodedJWT.getClaim("username").asString());
System.out.println("过期时间: " + decodedJWT.getExpiresAt());
} catch (IllegalArgumentException |JWTVerificationException e) {
//抛出错误即为验证不通过
return false;
}
return true;
}
}
package com.cpu.design.comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
//该类作用为配置拦截器,主要是哪些路径会被拦截,哪些不会
@Configuration
public class MvcInterceptorConfig extends WebMvcConfigurationSupport {
@Autowired
private TokenInterceptor tokenInterceptor;
@Override
protected void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(tokenInterceptor).addPathPatterns("/**")//拦截所有路径
.excludePathPatterns("/login");//不被拦截的路径,登录的时候还没有token码,不拦截
super.addInterceptors(registry);
}
}
package com.cpu.design.comment;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//逻辑上的一些拦截,搬运修改的。
@Component
public class TokenInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {
System.out.println("开始拦截");
if (request.getMethod().equals("OPTIONS")) {
System.out.println("options请求");
response.setStatus(HttpServletResponse.SC_OK);
return true;
}
response.setCharacterEncoding("utf-8");
String token = request.getHeader("token");
if (token != null) {
boolean result = JwtUitls.verify(token);
if (result) {
System.out.println("通过拦截器");
return true;
}
}
System.out.println("未通过!");
return false;
}
}
entity层
这一层放的都是实体类
package com.cpu.design.entity;
import javax.persistence.*;
@Entity
@Table(name = "userinfo")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)//数据库里的主键是自动递增的
//变量名最好一一对应,不然还要用注解标定
private Long id;
private String username;
private String password;
private int level;
public User() {
}
public User(Long id, String username, String password, int level) {
this.id = id;
this.username = username;
this.password = password;
this.level = level;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", level=" + level +
'}';
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
}
dao层
dao层跟数据库相关,可以写原生sql语句,也有封装好的接口。
package com.cpu.design.dao;
import com.cpu.design.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface UserRepository extends JpaRepository<User, Long> {
//如果是修改的话还要加上Transactional和Modifying这两个注解
@Query(value = "select * from userinfo where username = ?1",nativeQuery = true)
User findByName(String name);
}
service层
package com.cpu.design.service;
import com.cpu.design.dao.UserRepository;
import com.cpu.design.entity.User;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class UserService {
@Resource
private UserRepository userRepository;
public User findByName(String uname){
return userRepository.findByName(uname);
}
public void saveuser(User user){
userRepository.save(user);//这个就是封装好的接口,直接插入或者更新
}
}
controller层
这层跟前端直接交互
package com.cpu.design.controller;
import com.alibaba.fastjson.JSONObject;
import com.cpu.design.comment.JwtUitls;
import com.cpu.design.entity.User;
import com.cpu.design.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
@RestController
public class UserController {
@Resource
private UserService userService;
@ResponseBody
@PostMapping("/login")
public HashMap<String,Object> login(@RequestBody JSONObject jsonObject) throws JsonProcessingException {
//可以在此处检验用户密码
System.out.println("拦截器无了");
HashMap<String,Object> hs = new HashMap<>();
String username = jsonObject.get("username").toString();
String password = jsonObject.get("password").toString();
User user = userService.findByName(username);
if(user == null){
hs.put("code","400");
hs.put("msg","不存在该账户!");
return hs;
}
String real = user.getPassword();
if(password.equals(real)){
Integer level = user.getLevel();
String token = JwtUitls.sign(username);
hs.put("token",token);
hs.put("code",200);
hs.put("identity",level);
}
else{
hs.put("code",300);
hs.put("msg","密码错误!");
}
return hs;
}
@ResponseBody
@PostMapping("/saveuser")
public HashMap<String,Object> saveuser(@RequestBody User user){
HashMap<String,Object> hs = new HashMap<>();
try {
System.out.println(user.toString());
userService.saveuser(user);
hs.put("code","200");
}catch (Exception e){
hs.put("code","500");
hs.put("msg",e);
}
return hs;
}
}
配置
server:
port: 8081
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: ****
url: jdbc:mysql://localhost:3306/design
依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.9.0</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20190722</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
</dependencies>
结语
新手第一次搞前后端交互的项目真是困难重重,没啥前辈只能自己摸索,发个文章插个眼,以后再搞这样的项目不用到处找。上面说的可能问题不少,欢迎大佬指正!