用Vue编写项目中的前端页面

前言

Ajax 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。使用Vue,同样也可以达到此种效果。这里介绍的,就是用Vue来编写前端页面的例子。
原例子项目来自此博客:https://blog.csdn.net/qq_41151659/article/details/98115573

实现

效果

原来是用动态Jsp编写查看所有书籍(allBook.jsp)的页面,这里换用vue实现(Vue.jsp)。

准备

在webapp目录下新建一个statics包,并在该包下新建vue文件夹,导入vue.js和vue-resources.js文件(去Vue官网下载),如图所示:
在这里插入图片描述

实现

  1. 原先的查看所有书籍页面(allBook.jsp),代码如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--使用JSTL标签--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>全部书籍</title>

    <%--引用BootStarp--%>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

</head>
<body>


<div class="container">

    <%--标题--%>
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>书籍列表--显示所有书籍</small>
                </h1>
            </div>
        </div>
    </div>

    <%--增加--%>
    <div class="row">
        <div class="col-md-4 column">
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增</a>
        </div>
    </div>

    <%--展示页面:表格,修改,删除--%>
    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">

                <%--表头--%>
                <thead>
                 <tr>
                     <th>书籍编号</th>
                     <th>书籍名称</th>
                     <th>书籍数量</th>
                     <th>书籍描述</th>
                     <%--操作:修改,删除--%>
                     <th>操作</th>
                 </tr>
                </thead>
                <%--表的内容--%>
                <tbody>
                    <c:forEach var="book" items="${list}">
                        <tr>
                            <td>${book.getBookID()}</td>
                            <td>${book.getBookName()}</td>
                            <td>${book.getBookCounts()}</td>
                            <td>${book.getDetail()}</td>
                            <td>
                                <a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">更改</a> |
                                <a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">删除</a>
                            </td>
                        </tr>
                    </c:forEach>

                </tbody>

            </table>
        </div>
    </div>





</div>


</body>
</html>

  1. 在控制器的末端添加两个方法:toVue()、vueAllBook(),toVue方法用于跳转到用Vue显示全部书籍的页面,vueAllBook方法用于执行查找所有书籍的service层方法,并且将获取到的集合以JSON格式返回到jsp页面中,代码如下:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kuang.pojo.Books;
import com.kuang.service.BookService;
import com.sun.xml.internal.messaging.saaj.packaging.mime.util.LineInputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    @Qualifier("bookServiceImpl")
    private BookService bookService;

    //展示全部的书籍
    @RequestMapping("/allBook")
    public String list(Model model){
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list",list);
        return "allBook";
    }

    //跳转到新增书籍页面
    @RequestMapping("/toAddBook")
    public String toAddBook(){
        return "addBook";
    }

    //增加书籍页面
    @RequestMapping("/addBook")
    public String addBook(Books books){
        System.out.println("调试信息addBook===="+books);
        bookService.addBook(books);
        return "redirect:/book/allBook"; //重定向到首页
    }

    //跳转到修改页面
    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(int id,Model model){
        Books books = bookService.queryBookByID(id);
        System.out.println("调试信息toUpdateBook===="+books);
        model.addAttribute("book",books);
        return "updateBook";
    }

    //修改书籍
    @RequestMapping("/updateBook")
    public String updateBook(Books books,Model model){
        System.out.println("调试信息updateBook===="+books);
        bookService.updateBook(books);
        //更新最新的书籍
        Books books1 = bookService.queryBookByID(books.getBookID());
        model.addAttribute("books",books1);
        System.out.println("修改后的书籍===="+books1);
        return "redirect:/book/allBook"; //重定向到首页
    }


    //删除书籍,请使用restful风格
    @RequestMapping("/del/{bookID}")
    public String deleteBook(@PathVariable("bookID") int id){
        bookService.deleteBookByID(id);
        return "redirect:/book/allBook"; //重定向到首页
    }

    //跳转到Vue渲染书籍页面
    @RequestMapping("/toVue")
    public String toVue(){
        return "Vue";
    }

    @RequestMapping("/vueAllBook")
    @ResponseBody
    public String vueAllBook() throws JsonProcessingException {
        List<Books> list = bookService.queryAllBook();
        return new ObjectMapper().writeValueAsString(list);
    }



}

  1. 编写Vue.jsp,代码如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--使用JSTL标签--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>全部书籍</title>

    <%--引用BootStarp--%>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

</head>
<body>


<div class="container" id="kuang">

    <%--标题--%>
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>书籍列表--显示所有书籍</small>
                </h1>
            </div>
        </div>
    </div>

    <%--增加--%>
    <div class="row">
        <div class="col-md-4 column">
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增</a>
            &nbsp;&nbsp; | &nbsp;&nbsp;
            <button @click="m_post()"><span class="glyphicon glyphicon-repeat"></span></button>
        </div>
    </div>

    <%--展示页面:表格,修改,删除--%>
    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">

                <thead>
                <tr>
                    <th>书籍编号</th>
                    <th>书籍名称</th>
                    <th>书籍数量</th>
                    <th>书籍描述</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                    <tr v-for="book in books">
                        <td>{{book.bookID}}</td>
                        <td>{{book.bookName}}</td>
                        <td>{{book.bookCounts}}</td>
                        <td>{{book.detail}}</td>
                        <td>
                            <a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">更改</a> |
                            <a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">删除</a>
                        </td>
                    </tr>
                </tbody>

            </table>
        </div>
    </div>
</div>


<script src="${pageContext.request.contextPath}/statics/vue/vue.js"></script>
<script src="${pageContext.request.contextPath}/statics/vue/vue-resource.js"></script>

<script>
    var vm =  new Vue({
        el:"#kuang",
        data:{
            url:"${pageContext.request.contextPath}/book/vueAllBook",
            books:""
        },
        methods:{
            m_post(){
                var _this = this;
                Vue.http.post(_this.url).then(function (success) {
                    console.log(success.body);
                    _this.books = success.body;
                })
            }
        }
    })
</script>


</body>
</html>
  • 2
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
好的,以下是一个简单的登录注册前端页面的实现: 首先,我们需要在 HTML 添加两个表单:一个是登录表单,另一个是注册表单。每个表单都包含用户名和密码输入框以及相应的提交按钮。 ```html <div id="app"> <div v-if="!loggedIn"> <h2>登录</h2> <form @submit.prevent="login"> <label> 用户名: <input type="text" v-model="loginData.username"> </label> <label> 密码: <input type="password" v-model="loginData.password"> </label> <button type="submit">登录</button> </form> <hr> <h2>注册</h2> <form @submit.prevent="register"> <label> 用户名: <input type="text" v-model="registerData.username"> </label> <label> 密码: <input type="password" v-model="registerData.password"> </label> <label> 确认密码: <input type="password" v-model="registerData.confirmPassword"> </label> <button type="submit">注册</button> </form> </div> <div v-else> <h2>欢迎,{{ username }}!</h2> <button @click="logout">退出</button> </div> </div> ``` 接下来,我们需要使用 Vue3 来编写 JavaScript 部分。我们需要定义一个 Vue 实例,并在其添加以下属性和方法: ```javascript const app = Vue.createApp({ data() { return { loggedIn: false, username: '', loginData: { username: '', password: '' }, registerData: { username: '', password: '', confirmPassword: '' } } }, methods: { async login() { // 发送登录请求 const response = await fetch('/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(this.loginData) }) const data = await response.json() if (data.success) { this.loggedIn = true this.username = data.username } else { alert(data.message) } }, async register() { // 发送注册请求 const response = await fetch('/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(this.registerData) }) const data = await response.json() if (data.success) { this.loggedIn = true this.username = data.username } else { alert(data.message) } }, async logout() { // 发送退出请求 const response = await fetch('/logout') const data = await response.json() if (data.success) { this.loggedIn = false this.username = '' } else { alert(data.message) } } } }) ``` 这里我们使用了 async/await 来发起登录、注册和退出请求,并在请求返回后更新界面。对于登录和注册请求,我们需要将用户名和密码作为 JSON 数据发送到服务器,服务器返回一个表示是否成功的 JSON 对象,其 success 表示是否成功,message 表示错误信息(如果有的话),username 表示登录或注册成功后的用户名。 最后,我们需要将 Vue 实例挂载到页面上: ```javascript app.mount('#app') ``` 我们需要在服务器端实现登录、注册和退出功能,以及处理相应的请求。 这里提供的代码只是一个简单的示例,实际实现需要根据具体的需求进行修改和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赈川

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值