前言
这两天开始学习使用Vue实现前后端分离,以下内容实现了简单的登录操作。
开发工具和环境:VS Code、IDEA、Maven、Jpa、Mysql
创建vue项目
1.我是使用vue-cli来创建项目的,首先是安装vue-cli。
npm install vue-cli -g
2.cd进入你存放项目的文件夹下,创建helloworld项目
vue init webpack helloworld
这一步会有一些选项,直接默认就好
Project name //项目名
Project description //项目描述
Author //作者
Vue build //选择默认就好
Install vue-router? //Y
Use ESLint to lint your code? //n 这个还是选择no,代码检测太烦人了
Set up unit tests //Y
Pick a test runner //Jest
Setup e2e tests with Nightwatch? //Y
Should we runnpm install
for you after the project has been created? (recommended) //Yes, use NPM
这样项目就创建完成了,cd 进入刚刚创建的项目下,然后npm run dev
就可以启动项目了,会提示你访问哪个地址,浏览器中输入就行了。
页面实现
登录页面 Login.vue
<template>
<div >
<input id="username" name="username" type="text" placeholder="输入用户名" autocomplete="off" v-model="userName">
<input id="password" name="password" type="password" placeholder="Password" v-model="password">
<button @click="login()">登陆</button>
</div>
</template>
<script>
import axios from 'axios'
import Qs from 'qs'
export default {
name: 'Login',
data () {
return {
userName: "",
password: "",
}
},
created(){
},
methods:{
login:function(){
//console.log(this.userName);
//console.log(this.password);
var data = Qs.stringify({"username":this.userName,"password":this.password});
axios.post('http://localhost:8081/login',data,{withCredentials:true}).then(res=>{
console.log(res);
if(res.data.code===111){
this.$router.push({
path:'/success'
})
console.log(res)
}else{
console.log("失败")
}
}).catch(res=>{
alert("账号或密码不正确");
console.log("err",res)
})
}
}
}
</script>
登陆成功页面 success.vue
<template>
<div >
<h2>欢迎您</h2>
</div>
</template>
<script>
export default{
name: 'Success',
data(){
return {
msg: '登陆成功'
}
}
}
</script>
页面路由配置
src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Login from '@/components/Login'
import Success from '@/components/Success'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/login',
name: 'login',
component: Login
},
{
path: '/success',
name: 'success',
component: Success
}
]
})
将路由添加到程序入口,设置main.js
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router, //有默认将router添加进来了
components: { App },
template: '<App/>'
})
运行项目
npm run dev
可以直接在VS Code上的terminal操作就行了,可以在Login.vue中用console.log看一下是不是取到了用户信息。vue 中使用v-model双向数据绑定,会自动更新元素。
后端实现
我是使用Spring Data Jpa作为系统的持久化框架的,下面只展示主要代码
实体类 UserEntity
@Entity(name = "user")
@Data
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
@Column(name = "name")
private String name ;
@Column(name = "pwd")
private String pwd;
public UserEntity(){
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
结果集
public class ResponseEntity {
int code;
String message;
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
public void setCode(int code){this.code = code;}
public void setMessage(String message){this.message = message;}
}
创建UserController
@CrossOrigin(origins = "http://localhost:8082", maxAge = 3600)
@Controller
public class UserController {
//restful 风格的api
@Autowired
UserService userService;
@ResponseBody
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity login(HttpSession session, ModelMap map, @RequestParam("username")String name,
@RequestParam("password")String password){
ResponseEntity re = new ResponseEntity();
UserEntity userEntity = userService.findUserByName(name);
if(userEntity!=null && userEntity.getPwd().equals(password)){
session.setAttribute("id", userEntity.getId());
session.setAttribute("name",name);
session.setAttribute("user",userEntity);
System.out.println("success");
re.setCode(111);
re.setMessage("登陆成功");
return re;
}else{
System.out.println("123123123");
map.put("msg", "用户名或者密码错误");
map.addAttribute("tip","密码或者用户名错误");
re.setCode(222);
re.setMessage("用户名或者密码错误");
return re;
}
}
创建UserService
public interface UserService {
public UserEntity findUserByName(String email);
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Transactional
@Override
public UserEntity findUserByName(String name) {
try {
return userDao.findUserEntitiesByName(name);
} catch (Exception e) {
return null;
}
}
}
创建UserDao
public interface UserDao extends JpaRepository<UserEntity, Integer> {
UserEntity findUserEntitiesByName(String name);
}
找到application.properties配置文件
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/sbtest?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=**********
spring.datasource.password=***********
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
到此,就可以再次运行项目了,但是通常会有跨域问题
解决跨域问题
1.加入注解CrossOrigin
@CrossOrigin(origins = "*", maxAge = 3600)
还是不行,再来。
2.新建WebMvcConfiguration
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600);
}
}
ok ,我的项目可以跑了,就不继续百度了。
跨域问题前后端都能解决,但是我们先尝试从后端解决。
到此,登陆功能基本实现。撒花。。