前面发表了vue新建页面https://blog.csdn.net/baozi141990/article/details/103009802
今天实现了一下与ssm结合实现登录的功能,SSM框架搭建前面也写过
https://blog.csdn.net/baozi141990/article/details/102954591
因为实现了前后端分离,所以后台ssm配置需要加一些东西

配置

ssm配置允许任何的跨域请求

1.spring-mvc.xml中要添加

<mvc:cors>
		<!--实现跨域的配置代码 -->
		<mvc:mapping path="/**"
			allowed-origins="*"
			allowed-methods="POST,GET, OPTIONS,DELETE,PUT"
			allowed-headers="Content-Type,ContentType,Access-Control-Allow-Headers, Authorization, X-Requested-With"
			allow-credentials="true" />
	</mvc:cors>
	<mvc:annotation-driven></mvc:annotation-driven>

注:此配置只有在spring版本为4.2以上才有效,否则会报错,不要担心,spring4.2一下只需要配置一个过滤器就好。过滤器代码如下:

package com.sybinal.shop.utils;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 头部过滤器
 * 
 * @author
 */
public class HeaderFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse httpResponse = (HttpServletResponse) res;
		httpResponse.setHeader("Access-Control-Allow-Origin", "*");
		httpResponse.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
		httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
		httpResponse.setHeader("", "");
		httpResponse.setHeader("", "");
		chain.doFilter(request, httpResponse);

	}

	public void init(FilterConfig arg0) throws ServletException {

	}
}

然后配置过滤器,在web.xml中添加下面代码

	<filter>
		<filter-name>header</filter-name>
		<filter-class>com.sybinal.shop.utils.HeaderFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>header</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

Vue脚手架配置跨域

首先在vue项目的confi-index.js。如下:
在这里插入图片描述
找到proxyTable
在这里插入图片描述
添加下面代码:

'/api': {
 	target: 'http://localhost:8081',
	changeOrigin: true, 
	pathRewrite: {
		'^/api': '/'
	}
}

第一个‘/api’会拦截所有访问路径带有‘/api’的访问路径,然后把’/api’替换成target中的内容。我这里是:‘http://localhost:8081’

然后在src目录下的main.js中添加

import axios from "axios"
Vue.prototype.$axios = axios

这样就可以全局使用axios了,也就是vue的ajax请求
注:在导入axios之前首先得下载axios,因为axios是第三方库的插件
使用npm命令下载

npm install axios

到这里基本配置就配置完了,
下面开始写正式的代码

功能代码

1.实体类,这个简单我就不写了
2.mybatis映射以及dao等

在User.xml中添加

	<select id="findUserByUP"  resultType="User" parameterType="User">
		select * from user where name = #{name} and password = #{password}
	</select>

dao

	@Override
	public User findUserByUP(User user) {
		// TODO Auto-generated method stub
		return (User) this.getSqlSession().selectOne("user.findUserByUP", user);
	}

service

	@Override
	public User findUserByUP(User user) {
		// TODO Auto-generated method stub
		return testDao.findUserByUP(user);
	}

contorller

	@RequestMapping("test/login")
	@ResponseBody
	public Map<String,Object>  login(@RequestBody User user) {
		Map<String, Object> map = new HashMap<String, Object>();
		User user2 = testService.findUserByUP(user);
		if(user2!=null) {
			map.put("user",user2);
		}else {
			map.put("msg","用户名或密码错误!");
		}
		return map;
	}

这里使用了springmvc默认的转json配置,在使用之前记得导入jackjson的jar包
在这里插入图片描述

vue项目代码

首先在src/components下面创建login.vue和user.vue

login.ue

<template>
	<div>
		<h1>{{msg}}</h1>
		<table style="margin: auto;">
			<tr>
				<td>
					用户名</td>
				<td><input type="text" v-model="username" name="username" id="username" /></td>
			</tr>
			<tr>
				<td>
					密码</td>
				<td><input type="password" v-model="password" name="pwd" id="pwd" /></td>
			</tr>
			<tr><button @click="login()">登录</button></tr>
		</table>
		<div v-if="username!=''">{{info}}</div>
		<Demo></Demo>
	</div>
</template>

<script>
	import test from '@/components/test'
	import Router from 'vue-router'
	export default {
		name: 'login',
		data() {
			return {
				username: 'myName',
				password: '123',
				msg: "登录",
				info: ''
			}
		},
		methods: {
			login() {
				var b = true;
				if (this.username == "") {
					b = false;
					alert('请输入用户名!')
				}
				if (this.password == "") {
					b = false;
					alert('请输入密码!')
				}
				if (b) {
					this.$axios.post('/api/Test/test/login.do', {
						name: this.username,
						password: this.password
					}).then(
						response => {
							this.info = response.data.user;
							console.log(this.info)
							if (typeof(this.info)!="undefined") {
								this.$router.push({
									path: '/user',
									query: {
										userInfo: this.info
									}
								})
							}else{
								this.info = response.data.msg;
							}
						}
					);

				}
			}
		},
		components: {
			'Demo': test
		}
	}
</script>

<style>
</style>

注意配置路由跳转的那里$ router容易写成$ route
user.vue

<template>
	<div v-if="this.userInfo!=''">您好,{{userInfo.name}}!</div>
	<div v-else>您未登陆!</div>
</template>

<script>
	export default {
		data() {
			return {
				userInfo: ""
			}
		},
		methods: {
			getParams() {
				const rou = this.$route.query.userInfo;
				this.userInfo = rou;
			}
		},
		created() {
			this.getParams();
		}
	}
</script>

<style>
</style>

注意:在这里使用的是$ route不是$ route.否则参数无法收到,而且info必须加this.info否则一直会报错 undefined
然后在stc/router/index.js中添加

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Login from '@/components/login'
import User from '@/components/user'

Vue.use(Router)

export default new Router({
	mode: 'history',
	routes: [{
		path: '/',
		name: 'HelloWorld',
		component: HelloWorld
	}, {
		path: '/login',
		name: 'login',
		component: Login
	}, {
		path: '/user',
		name: "user",
		component: User
	}]
})

这样整个项目的代码就写完了,下面是实现的页面
在这里插入图片描述
密码错误时
在这里插入图片描述
登录成功后
在这里插入图片描述
到这里就完了

Logo

前往低代码交流专区

更多推荐