本文基于【springboot系列】前端工程之从零开始创建vue工程。
基于springboot+vue项目制作。
springboot后端:github地址
vue前端:github地址
接入axios进行网络访问:
npm install --save axios vue-axios
在main.js引入import配置地址进行使用:
此处使用json做为传入传出参数,对应后台requestbody,responsebody注解。
import VueAxios from 'vue-axios'
var axiosInstance = axios.create({
baseURL: location.protocol + '//127.0.0.1:8096/',
headers: { 'Content-Type': 'application/json' }
})
Vue.use(VueAxios, axiosInstance)
网络请求的使用代码如下:
<script>
export default {
name: "Login",
data() {
return {
username: '',
password: ''
}
},
methods: {
login() {
if (this.username != '' && this.password != '') {
// console.log(this.username + "-------登录-------" + this.password);
//md5加盐
var salt = "1a2b3c4d";
var str = ""+salt.charAt(0)+salt.charAt(2) + this.password +salt.charAt(5) + salt.charAt(4);
var md5pwd = this.$md5(str);
var allData ={
"username":this.username,
"password":md5pwd,
"salt":salt
};
// console.log(allData)
// 网络访问
this.axios.post('login/doLogin',allData).then(res => {
console.log(res.data)
if (res.data.code==0){this.$router.push('/home')}else {
alert(res.data.msg)
}
//res.data do something right
}).catch(res => {
//do something wrong
console.log(res.data)
})
}
}
}
}
script>
此处仅列出controller代码,具体代码请查看源码:
@Controller
@RequestMapping("/login")
public class LoginController {
Logger logger = LoggerFactory.getLogger(LoginController.class);
@Autowired
private UserInfoSerivice userInfoSerivice;
@RequestMapping(value = "/doLogin", method = RequestMethod.POST)
@ResponseBody
public Result<LoginUser> login(@RequestBody LoginUser loginUser){
logger.info("loginUser:"+loginUser.toString());
LoginUser result = userInfoSerivice.getByUsername(loginUser.getUsername());
if (result==null){
return Result.error(CodeMsg.MOBILE_NOT_EXIST);
}
if (MD5Util.formPassToDBPass(loginUser.getPassword(),loginUser.getSalt()).equals(result.getPassword())){
return Result.success(result);
}else {
return Result.error(CodeMsg.PASSWORD_ERROR);
}
}
}
代码说明:
对照源码可知,其中前端密码+salt进行一次md5后传输到后端,然后后端根据前端传来的salt进行二次md5加密。
本地调试的时候由于前后端分离,导致测试请求跨域。可查看我之前写的跨域解决方案文章。
此处由于仅仅为了简单,使用后端处理跨域请求的方式。在代码中加入以下代码即可。具体原因分析请查看文章。
package xyz.haibofaith.miaosha.filter;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CrossFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
// System.out.println(req.getScheme());
// System.out.println(req.getContextPath());
// System.out.println(req.getServletPath());
String origin = req.getHeader("Origin");
if (!org.springframework.util.StringUtils.isEmpty(origin)) {
//带cookie的时候,origin必须是全匹配,不能使用*
response.addHeader("Access-Control-Allow-Origin", origin);
// response.addHeader("Access-Control-Allow-Origin", "*");
}
response.addHeader("Access-Control-Allow-Methods", "*");
String headers = req.getHeader("Access-Control-Request-Headers");
// 支持所有自定义头
if (!org.springframework.util.StringUtils.isEmpty(headers)) {
response.addHeader("Access-Control-Allow-Headers", headers);
}
response.addHeader("Access-Control-Max-Age", "0");
// enable cookie 支持cookie
response.addHeader("Access-Control-Allow-Credentials", "true");
filterChain.doFilter(servletRequest,response);
}
@Override
public void destroy() {
}
}