使用vue写一个登录界面并于spring boot整合
时间: 2023-05-24 17:07:13 浏览: 70
我是AI语言模型,无法编写具体的代码,以下是参考代码供您参考。
前端代码:
<template>
<div class="login-container">
<h1>Login</h1>
<form>
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" v-model="username" placeholder="Enter username">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" v-model="password" placeholder="Enter password">
</div>
<button type="button" @click="login">Login</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
username: '',
password: ''
}
},
methods: {
login() {
axios.post('/login', {
username: this.username,
password: this.password
})
.then(response => {
// 登录成功
window.location.href = '/home'
})
.catch(error => {
// 登录失败
alert('Login failed! Please try again.')
})
}
}
}
</script>
后端代码:
@RestController
@RequestMapping("/api")
public class LoginController {
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginDTO loginDTO) {
// 验证用户名和密码
if (isValid(loginDTO.getUsername(), loginDTO.getPassword())) {
// 登录成功
return ResponseEntity.ok().build();
} else {
// 登录失败
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
private boolean isValid(String username, String password) {
// 验证用户名和密码是否匹配
// 这里省略具体实现
return true;
}
}
@Component
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessURL("/home")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}123456").roles("ADMIN");
}
}
以上代码演示了一个简单的登录页面和使用 spring boot 实现的登录验证。当用户尝试登录时,前端将用户名和密码发送到后端,后端进行验证,如果用户名和密码正确,返回成功状态,前端则跳转到首页(通常为一个需要登录访问权限的页面);如果验证失败,返回错误状态,前端会弹出一个失败提示。此外,上述代码还包括了 Spring Security 的配置,其中默认用户名为 "admin",密码为 "123456"。