react+antd+springmvc 實現簡單的登錄功能


 react開發工具create-react-app+vscode
(1)第一步,配置tomcat項目可跨域訪問
我的react項目端口是3000,java的項目端口是8080,所以第一步實現跨域訪問(請參考地址http://blog.csdn.net/u012500848/article/details/51162449自己實現)
(2)springmvc后台登錄代碼
    @RequestMapping(value = { "/test/login" }, method = RequestMethod.POST)
    @ResponseBody
    public String Login(HttpServletRequest request) {
        String username = request.getParameter("username");
        String pwd = request.getParameter("userpwd");
        if (username == null || username.isEmpty()) {
            return "帳號為空";
        }
        if (pwd == null || pwd.isEmpty()) {
            return "密碼為空";
        }
        if (username.equals("test") && pwd.equals("123456")) {
            return "登錄成功";
        } else {
            return "帳號或密碼錯誤";
        }
    }

(3)使用fetch實現登錄功能,要先在項目中安裝fetch(yarn add whatwg-fetch)

import React from 'react';
import {Form, Icon, Input, Button, message} from 'antd';
import 'whatwg-fetch';
import './Login.css';
const FormItem = Form.Item; class Login extends React.Component { //登錄事件 handleSubmit = (e) => { e.preventDefault(); let url = "http://localhost:8080/shiro/test/login"; let formData = new FormData(); formData.append('username', this.props.form.getFieldValue("username")); formData.append('userpwd', this.props.form.getFieldValue("userpwd")); fetch(url, { method: 'post', mode: 'cors', body: formData }).then(function (response) { return response.text() }).then(function (body) { message.info(body); }); } render() { const {getFieldDecorator} = this.props.form; return ( <Form onSubmit={this.handleSubmit} className="login-form"> <FormItem> {getFieldDecorator('username', {})( <Input prefix={< Icon type = "user" style = {{ fontSize: 13 }}/>} placeholder="帳號"/> )} </FormItem> <FormItem> {getFieldDecorator('userpwd', {})( <Input prefix={< Icon type = "lock" style = {{ fontSize: 13 }}/>} type="password" placeholder="密碼"/> )} </FormItem> <FormItem> <Button type="primary" htmlType="submit" className="login-form-button"> 登錄 </Button> </FormItem> </Form> ); } } const WrappedNormalLoginForm = Form.create()(Login); export default WrappedNormalLoginForm;
this.props.form.getFieldValue方法用來獲取input輸入的值。

(4)實現效果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM