【springboot】sprinMVC练习

发布时间:2024年01月12日

Spring MVC练习

1. 加法计算器练习

前端页面:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
</head>

<body>
    <div id="app">
        <h1>计算器</h1>
        数字1:<input v-model="num1" type="text"><br>
        数字2:<input v-model="num2" type="text"><br>
        <button @click="add()">点击相加</button>
        <div v-if="flg">
            两数相加之和:{{result}}
        </div>
    </div>
</body>
<script>
    new Vue({
        el: '#app',
        data: {
            flg: false,
            num1: "",
            num2: "",
            result: 0
        },
        methods: {
            add: function () {
                axios
                    .post('calc/sum', {
                        "num1": this.num1,
                        "num2": this.num2
                    })
                    .then(response => (this.flg = true, this.result = response.data))
                    .catch(function (error) { // 请求失败处理
                        console.log(error);
                    });
            }

        }
    })
</script>

</html>

后端代码:

@RestController
@RequestMapping("/calc")
public class CalController {
    @RequestMapping("/sum")
    public Integer add(@RequestBody Map<String,Integer> map){
        System.out.println(map);
        return map.get("num1") + map.get("num2");
    }
}

2. 登录练习

前端代码:

登录页面login.html核心代码:

<body>
    <div id="app">
        <h1>用户登录</h1>
        用户名:<input v-model="username" name="userName" type="text" id="userName"><br>
        密码:<input v-model="password" name="password" type="password" id="password"><br>
        <button @click="login()">登录</button>
    </div>

    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    username: "",
                    password: ""
                }
            },
            methods: {
                login: function () {
                    axios
                        .get('user/login', {
                            params: {
                                "username": this.username,
                                "password": this.password
                            }
                        })
                        .then(response => {
                            if (response.data == true) {
                                location.href = "/index.html";
                            } else {
                                alert("账号或密码错误登录失败");
                            }
                        })
                        .catch(function (error) { // 请求失败处理
                            console.log(error);
                        });
                }
            }
        })

    </script>
</body>

用户登录首页index.html核心代码

<body>
    <div id="app">
        登录人: {{username}}
    </div>
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    username: ""
                }
            },
            mounted() {//钩子函数
                axios
                    .get('user/getUserInfo')
                    .then(response => {
                        if(response.data != ""){
                            this.username = response.data;
                        }else{
                            this.username = "没有用户登录";
                        }
                    })
                    .catch(function (error) { // 请求失败处理
                        console.log(error);
                    });
            }
        })
    </script>
</body>

接口定义:

1. 登录接口
	/user/login
	username=?&password=?
	返回校验:校验成功/失败
		true:登录成功
		false:登录失败
2. 获取用户登录信息
	/user/getUSerInfo
	接口返回:当前登录用户的名称
前端需要注意的是,用axios发送请求,post请求是在body中,是json格式。get请求的参数是在URL参数中。

后端代码:

@RestController
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/login")
    public boolean login(String username, String password, HttpServletRequest request){
        if(!StringUtils.hasLength(username)||!StringUtils.hasLength(password)){
            return false;
        }
        if (username.equals("admin") && password.equals("admin")){
            //存储session
            request.getSession().setAttribute("username",username);
            return true;
        }
        return false;
    }
    @RequestMapping("/getUserInfo")
    //获取session
    public String getUserInfo(@SessionAttribute(required = false) String username){
        return username;
    }
}

3. 留言板

接口定义

1. 提交留言
	/message/publish
	参数:MessageInfo(from,to,message)
	返回结果:true
2. 查看所有留言
	/message/getMessageList
	参数:无
	返回结果:List<MessageInfo>

前端代码:

<body>
    <div id="app">
        <div class="container">
            <h1>留言板</h1>
            <p class="grey">输入后点击提交, 会将信息显示下方空白处</p>
            <div class="row">
                <span>谁:</span> <input type="text" v-model="messageInfo.from" id="from">
            </div>
            <div class="row">
                <span>对谁:</span> <input type="text" v-model="messageInfo.to" id="to">
            </div>
            <div class="row">
                <span>说什么:</span> <input type="text" v-model="messageInfo.message" id="say">
            </div>
            <button id="submit" @click="submit()"> 提交 </button>
            <div v-for="(item,index) in messageList" :key="index">
                {{item.from}} 对 {{item.to}} 说: {{item.message}}
            </div>
        </div>

    </div>
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.js"></script>
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                messageInfo: {
                    from: "",
                    to: "",
                    message: ""
                },
                messageList: []
            },
            mounted() {//钩子函数
                axios
                    .get('message/getMessageList')
                    .then(response => {
                        this.messageList = response.data;
                    })
                    .catch(function (error) { // 请求失败处理
                        console.log(error);
                    });
            },
            methods: {
                submit: function () {
                    if (this.messageInfo.from == '' || this.messageInfo.to == '' || this.messageInfo.message == '') {
                        return;
                    }
                    axios
                        .post('message/publish', this.messageInfo)
                        .then(response => {
                            if (response.data == true) {
                                //alert("留言发布成功");
                                this.messageList.push({
                                    from: this.messageInfo.from,
                                    to: this.messageInfo.to,
                                    message: this.messageInfo.message
                                });
                                //清空输入框中的值
                                this.messageInfo.from = "";
                                this.messageInfo.to = "";
                                this.messageInfo.message = "";
                            } else {
                                //添加失败
                                alert("留言发布失败");
                            }
                        })
                        .catch(function (error) { // 请求失败处理
                            console.log(error);
                        });
                }
            }
        })

    </script>
</body>

后端代码

实体类代码:

@Data
public class MessageInfo {
    private String from;
    private String to;
    private String message;
}

controller代码:

@RestController
@RequestMapping("/message")
public class MessageController {
    List<MessageInfo> messageInfoList = new ArrayList<>();
    @RequestMapping("/publish")
    public boolean publishMessage(@RequestBody MessageInfo messageInfo){
        System.out.println(messageInfo);
        if (!StringUtils.hasLength(messageInfo.getFrom()) ||
            !StringUtils.hasLength(messageInfo.getTo()) ||
            !StringUtils.hasLength(messageInfo.getMessage())){
            return false;
        }
        messageInfoList.add(messageInfo);
        return true;
    }
    @RequestMapping("/getMessageList")
    public List<MessageInfo> getMessageList(){
        return messageInfoList;
    }
}

4. 图书管理系统简单练习

这里只做简单的练习,后面会补充练习

接口定义

1. 登录
	URL:/user/login
	参数:username=?& password=?
	响应:true/false
2. 图书列表展示
	URL:/book/getBookList
	参数:无
	响应:List<BookInfo>

前端核心代码

登录页面:

<body>
    <div id="app">
        <div class="container-login">
            <div class="container-pic">
                <img src="pic/computer.png" width="350px">
            </div>
            <div class="login-dialog">
                <h3>登陆</h3>
                <div class="row">
                    <span>用户名</span>
                    <input type="text" v-model="username" name="userName" id="userName" class="form-control">
                </div>
                <div class="row">
                    <span>密码</span>
                    <input type="password" v-model="password" name="password" id="password" class="form-control">
                </div>
                <div class="row">
                    <button type="button" class="btn btn-info btn-lg" @click="login()">登录</button>
                </div>
            </div>
        </div>
    </div>
    <script src="js/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    username: "",
                    password: ""
                }
            },
            methods: {
                login: function () {
                    axios
                        .get('user/login', {
                            params: {
                                "username": this.username,
                                "password": this.password
                            }
                        })
                        .then(response => {
                            if (response.data == true) {
                                location.href = "/book_list.html";
                            } else {
                                alert("账号或密码错误登录失败");
                            }
                        })
                        .catch(function (error) { // 请求失败处理
                            console.log(error);
                        });
                }
            }
        })

    </script>
</body>

列表页(目前只实现查询列表):

<table>
    <thead>
        <tr>
            <td>选择</td>
            <td class="width100">图书ID</td>
            <td>书名</td>
            <td>作者</td>
            <td>数量</td>
            <td>定价</td>
            <td>出版社</td>
            <td>状态</td>
            <td class="width200">操作</td>
        </tr>
    </thead>
    <tbody>
        <tr  v-for="(item,index) in bookList" :key="index">
            <td><input type="checkbox" name="selectBook" value="1" id="selectBook" class="book-select"></td>
            <td>{{item.id}}</td>
            <td>{{item.bookName}}</td>
            <td>{{item.author}}</td>
            <td>{{item.count}}</td>
            <td>{{item.price}}</td>
            <td>{{item.publish}}</td>
            <td>{{item.statusCN}}</td>
            <td>
                <div class="op">
                    <a :href="baseUrl + item.id">修改</a>
                    <a href="javascript:void(0)" onclick="deleteBook(item.id)">删除</a>
                </div>
            </td>
        </tr>
    </tbody>
</table>
<script>
    new Vue({
        el: '#app',
        data: {
            baseUrl:"book_update.html?bookId=",
            bookList: []
        },
        mounted() {//钩子函数
            axios
                .get('book/getBookList')
                .then(response => {
                    this.bookList = response.data;
                })
                .catch(function (error) { // 请求失败处理
                    console.log(error);
                });
        },
        methods: {

        }
    })
</script>

后端代码:

实体类:

@Data
public class BookInfo {
    private int id;
    private String bookName;
    private String author;
    private int count;
    private BigDecimal price;
    private String publish;
    //状态 0-?效 1-允许借阅 2-不允许借阅
    private Integer status;
    private String statusCN;
}

用户controller类

@RestController
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/login")
    public boolean login(String username, String  password, HttpSession session){
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)){
            return false;
        }
        if ("admin".equals(username) && "admin".equals(password)){
            session.setAttribute("username",username);
            return true;
        }
        return false;
    }
}

图书controller类

@RestController
@RequestMapping("/book")
public class BookController {
    @RequestMapping("/getBookList")
    public List<BookInfo> getBookList(){
        //1.获取图书数据
        //2.对图书数据进行处理
        //3.返回数据
        //mock:表示虚拟的假数据
        List<BookInfo> bookInfos = mockData();
        for (BookInfo bookInfo:bookInfos) {
            if (bookInfo.getStatus() == 1){
                bookInfo.setStatusCN("可借阅");
            }else {
                bookInfo.setStatusCN("不可借阅");
            }
        }
        return bookInfos;
    }
    private List<BookInfo> mockData(){
        //优化小Tips:对于已知的数据量,或者大于这个集合的数据时,创建list时,建议指定初始化容量。
        List<BookInfo> bookInfos = new ArrayList<>(15);
        for (int i = 0; i < 15; i++) {
            BookInfo bookInfo = new BookInfo();
            bookInfo.setId(i);
            bookInfo.setBookName("图书" + i);
            bookInfo.setAuthor("作者" + i);
            bookInfo.setCount(new Random().nextInt(200));
            bookInfo.setPrice(new BigDecimal(new Random().nextInt(100)));
            bookInfo.setPublish("出版社" + i);
            bookInfo.setStatus(i % 5 == 0 ? 2: 1);
            bookInfos.add(bookInfo);
        }
        return bookInfos;
    }
}
文章来源:https://blog.csdn.net/weixin_66409969/article/details/135550051
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。