package com.liuting.vue.entity;
public class User {
private String uname;
private String pwd;
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User [uname=" + uname + ", pwd=" + pwd + "]";
}
public User(String uname, String pwd) {
super();
this.uname = uname;
this.pwd = pwd;
}
public User() {
super();
}
}
package com.liuting.vue.dao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;
import com.liuting.base.dao.BaseDao;
import com.liuting.vue.entity.User;
import com.liuting.vue.util.PageBean;
import com.liuting.vue.util.StringUtils;
public class UserDao extends BaseDao {
private static final long serialVersionUID = -2644908989655094673L;
public List list(User user,PageBean pageBean) {
BaseDao obj = this;
return (List) this.getHibernateTemplate().execute(new HibernateCallback>() {
@Override
public List doInHibernate(Session session) throws HibernateException {
String hql = "from User where 1=1 ";
Map map = new HashMap<>();
String uname = user.getUname();
String pwd = user.getPwd();
if (StringUtils.isNotBlank(uname)) {
hql += " and uname = :uname";
map.put("uname", uname);
}
if (StringUtils.isNotBlank(pwd)) {
hql += " and pwd = :pwd";
map.put("pwd", pwd);
}
/*return obj.executeQuery(session, hql, map, pageBean);*/
return obj.executeQuery(session, hql, map, pageBean);
}
});
}
}
package com.liuting.vue.biz;
import com.liuting.vue.entity.User;
public interface UserBiz {
public User login(User user);
}
package com.liuting.vue.biz.impl;
import com.liuting.vue.biz.UserBiz;
import com.liuting.vue.dao.UserDao;
import com.liuting.vue.entity.User;
public class UserBizImpl implements UserBiz {
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public User login(User user) {
return userDao.list(user, null).get(0);
}
}
package com.liuting.vue.web;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuting.base.web.BaseAction;
import com.liuting.vue.biz.UserBiz;
import com.liuting.vue.entity.User;
import com.liuting.vue.util.JsonData;
import com.liuting.vue.util.ResponseUtil;
import com.liuting.vue.util.StringUtils;
import com.opensymphony.xwork2.ModelDriven;
public class UserAction extends BaseAction implements ModelDriven{
private UserBiz userBiz;
private User user = new User();
public UserBiz getUserBiz() {
return userBiz;
}
public void setUserBiz(UserBiz userBiz) {
this.userBiz = userBiz;
}
public String login() {
ObjectMapper om = new ObjectMapper();
JsonData jsonData = null;
try {
if(StringUtils.isBlank(user.getUname()) || StringUtils.isBlank(user.getPwd())) {
jsonData = new JsonData(0, "用户或者密码为空", user);
}else {
User u = this.userBiz.login(user);
// Map claims = new HashMap();
// claims.put("uname",user.getUname());
// claims.put("pwd", user.getPwd());
// String jwt = JwtUtils.createJwt(claims, JwtUtils.JWT_WEB_TTL);
// response.setHeader(JwtUtils.JWT_HEADER_KEY, jwt);
jsonData = new JsonData(1, "登录成功", u);
}
} catch (Exception e) {
e.printStackTrace();
jsonData = new JsonData(0, "用户或者密码错误", user);
}finally {
try {
ResponseUtil.write(response, om.writeValueAsString(jsonData));
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public String getAsyncData() {
ObjectMapper om = new ObjectMapper();
try {
Thread.sleep(6000);
ResponseUtil.write(response, om.writeValueAsString("http://www.javaxl.com"));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public User getModel() {
return user;
}
}
1. vue怎么引入和配置使用element-ui框架
1.1 使用vue-cli脚手架工具创建一个vue项目
vue init webpack pro01
1.2 npm安装elementUI
cd pro01 #进入新建项目的根目录
npm install element-ui -S #安装element-ui模块
重要的事情说三遍:在指定位置!!!在指定位置!!!在指定位置!!!~~~添加三行代码
1.3 在项目中src目录下找到main.js,并在指定位置添加三行代码(main.js是入口文件,所以在这里引入就行,页面就不用引入了)
import Vue from 'vue’
import ElementUI from 'element-ui' //新添加1
import 'element-ui/lib/theme-chalk/index.css' //新添加2,避免后期打包样式不同,要放在import App from './App';之前
import App from './App'
import router from './router'
Vue.use(ElementUI) //新添加3
Vue.config.productionTip = false
1.4 测试
修改HelloWorld.vue添加elementUI组件查看效果
3. 后台交互(axios/qs/vue-axios)
3.1 axios
axios是vue2提倡使用的轻量版的ajax。它是基于promise的HTTP库。它会从浏览器中创建XMLHttpRequests,与Vue配合使用非常好。
接下来上代码
login.vue
用户登录
提交
用户注册
忘记密码
Reg.vue(注册界面)
用户注册
提交
用户登录
忘记密码
main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import axios from '@/api/http'
import VueAxios from 'vue-axios'
Vue.use(ElementUI)
Vue.use(VueAxios,axios)
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: ' '
})
注1:axios跨域问题
会一直报错:“http://127.0.0.1:8848’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header”
因为使用了前后端分离开发,跨域访问了,解决方案:需要配置tomcat允许跨域访问,
tomcat跨域配置方法很多,但最简单的方式是自己写一个过滤器CorsFilter实现,添加一个响应头
Access-Control-Allow-Origin即可
httpResponse.addHeader(“Access-Control-Allow-Origin”, “*”);//表示任何域名
httpResponse.addHeader(“Access-Control-Allow-Origin”, “http://localhost:80”);
Access-Control-Allow-Origin: #则允许所有域名的脚本访问该资源。
Access-Control-Allow-Origin:https://www.fujieace.com #允许特定的域名访问
注2:axios.get提交没有问题,axios.post提交后台接收不到数据
因为POST提交的参数的格式是Request Payload,这样后台取不到数据的(详情见资料“05 Vue中axios踩坑之路-POST传参 - RainSun - CSDN博客.mht”),
解决方案:使用qs.js库,将{a:‘b’,c:‘d’}转换成’a=b&c=d’
axios.post(url, qs.stringify(this.ruleForm)).then(function(response)=> {
console.log(response);
if (response.data.code == 1) {
this.$message({
message: response.data.msg,
type: 'success'
});
} else {
this.$message({
showClose: true,
message: response.data.msg,
type: 'error'
});
}
}).catch(function(error) {
console.log(error);
});
注3:为简化axios使用,还可以使用axios全局配置及拦截器,详情见资料“api/http.js”
axios.defaults.baseURL = ‘https://api.example.com’;
//axios.defaults.headers.common[‘Authorization’] = AUTH_TOKEN;//自定义请求头,添加认证令牌
axios.defaults.headers.post[‘Content-Type’] = ‘application/x-www-form-urlencoded’;
注4:为方便开发,建议对请求地址进行封装,详情见资料“api/action.js”
action.js
/**
* vue项目对axios的全局配置
*/
import axios from 'axios'
import qs from 'qs'
//引入action模块,并添加至axios的类属性urls上
import action from '@/api/action'
axios.urls = action
// axios默认配置
axios.defaults.timeout = 10000; // 超时时间
// axios.defaults.baseURL = 'http://localhost:8080/j2ee15'; // 默认地址
axios.defaults.baseURL = action.SERVER;
//整理数据
// 只适用于 POST,PUT,PATCH,transformRequest` 允许在向服务器发送前,修改请求数据
axios.defaults.transformRequest = function(data) {
data = qs.stringify(data);
return data;
};
// 请求拦截器
axios.interceptors.request.use(function(config) {
// var jwt = window.vm.$store.getters.getJwt;
// config.headers['jwt'] = jwt;
return config;
}, function(error) {
return Promise.reject(error);
});
// 响应拦截器
axios.interceptors.response.use(function(response) {
// debugger;
// var jwt = response.headers['jwt'];
// if(jwt){
// window.vm.$store.commit('setJwt',{jwt:jwt});
// }
return response;
}, function(error) {
return Promise.reject(error);
});
// // 路由请求拦截
// // http request 拦截器
// axios.interceptors.request.use(
// config => {
// //config.data = JSON.stringify(config.data);
// //config.headers['Content-Type'] = 'application/json;charset=UTF-8';
// //config.headers['Token'] = 'abcxyz';
// //判断是否存在ticket,如果存在的话,则每个http header都加上ticket
// // if (cookie.get("token")) {
// // //用户每次操作,都将cookie设置成2小时
// // cookie.set("token", cookie.get("token"), 1 / 12)
// // cookie.set("name", cookie.get("name"), 1 / 12)
// // config.headers.token = cookie.get("token");
// // config.headers.name = cookie.get("name");
// // }
// return config;
// },
// error => {
// return Promise.reject(error.response);
// });
// // 路由响应拦截
// // http response 拦截器
// axios.interceptors.response.use(
// response => {
// if (response.data.resultCode == "404") {
// console.log("response.data.resultCode是404")
// // 返回 错误代码-1 清除ticket信息并跳转到登录页面
// // cookie.del("ticket")
// // window.location.href='http://login.com'
// return
// } else {
// return response;
// }
// },
// error => {
// return Promise.reject(error.response) // 返回接口返回的错误信息
// });
export default axios;