如何将JSP文件内容上载到textarea

fkaflof6  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(171)

我想在浏览器的textarea中编辑一个jsp文件。所以我需要上传jsp内容到textarea。例如,我有一个readMe.jsp文件,如下所示:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<h1>Read Me</h1>
<p> This is read me content</p>

我想要这样编辑:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<h1>Read Me</h1>
<p> This is read me content</p>
<hr>
<h2>Read Me Second Head</h2>
<p>This is read me content 2</p>

我认为能够在浏览器中做到这一点的方法是将jsp内容上传到textarea并在那里编辑它。有人知道我如何做到这一点吗?如果我有一种与浏览器不同的编辑jsp文件的方法,它也可以。

  • 谢谢-谢谢
2g32fytz

2g32fytz1#

这只是一个如何从浏览器编辑JSP页的示例。
webapp/readme.jsp是要编辑的页面。

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>Read Me</title>
</head>
<body>
<h1>Read Me</h1>
<p> This is read me content</p>
<p><a href="${pageContext.request.contextPath}/edit/readme">Edit this page</a></p>
</body>
</html>

webapp/edit/readme.jsp包含可以在其中编辑readme.jsp页面内容的表单。

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>Edit | Read Me</title>
</head>
<body>
<h1>'Read Me' edit page</h1>
<form method="post" action="${pageContext.request.contextPath}/edit/readme">
    <label>
        <textarea name="newContent" cols="96" rows="16">${content}</textarea>
    </label>
    <br><br>
    <button type="submit">Save</button>
</form>
</body>
</html>

EditReadMe.java是一个servlet。
方法doGetwebapp/readme.jsp中的 Edit this page 链接触发,它从webapp/readme.jsp文件中读取内容并将其传递给webapp/edit/readme.jsp
方法doPost负责处理webapp/edit/readme.jsp中得表单,并更新webapp/readme.jsp文件得内容.

package com.example.editjsp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

@WebServlet(name = "readMeEditor", value = "/edit/readme")
public class EditReadMe extends HttpServlet {

    private static final String RESOURCE_PATH = "/readme.jsp";
    private Path pathToFile;

    @Override
    public void init() {
        pathToFile = Path.of(getServletContext().getRealPath(RESOURCE_PATH));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String contentToEdit = Files.readString(pathToFile);
        req.setAttribute("content", contentToEdit);
        req.getRequestDispatcher("/edit/readme.jsp").forward(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        Files.writeString(pathToFile, req.getParameter("newContent"));
        resp.sendRedirect(req.getContextPath() + RESOURCE_PATH);

    }

}

相关问题