How to change a user file after a user has changed it in textarea? Here is the servlet code where the user file in textarea is displayed:

@WebServlet(name = "Change", urlPatterns = {"/Change"}) public class Change extends HttpServlet { static String filenamefile, filename, jjj; public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession httpSession = req.getSession(true); filenamefile = (String) httpSession.getAttribute("filenamefile"); filename = (String) httpSession.getAttribute("filename"); resp.setContentType("text/html;charset=utf-8"); PrintWriter pw = resp.getWriter(); /*PrintWriter writer = new PrintWriter("/home/zhuk/Downloads/" + "jj.txt", "UTF-8");*/ pw.println("" + "<!DOCTYPE html>\n" + "<html>\n" + " <head>\n" + " <meta charset=\"UTF-8\">\n" + " <title>Изменения страницы</title>\n" + " </head>\n" + " \n" + " \n" + " <body>\n" + " <h3>\n" + " Страница: "+filenamefile+"\n" + " </h3>\n"); pw.println(" <form action=\"SaveServlet\">"); pw.println(" <textarea cols=\"70\" rows=\"20\">"); try (BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream(filename), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { pw.println(line); //jjj+=line; } } catch (IOException e) { e.printStackTrace(); } /*for(int i = 0; i < jjj.length(); i++) { writer.println(jjj); }*/ pw.println( " </textarea>\n" + " <input type=\"submit\" value=\"Сохранить\">" + " </form>\n" + " </body>\n" + "</html>"); //writer.close(); } } 
  • I understand correctly that you need to implement the logic on the textarea element before submitting the form? Then you need to send through the button and hang up the listener on it and implement the logic in JS in the listener. - ezhov_da
  • @ezhov_da, that's right, and you need to do it, but I didn’t understand how to implement it - Zhuk

1 answer 1

To implement, you need:
1. Add a button that will send information:

  <center><button type="button" id="done" class="btn btn-primary">Отправить</button></center> 
  1. Add the output of the JS script to the head block:

     <script> $(document).ready(function () { document.getElementById("done").addEventListener("click", function () { //ЗДЕСЬ ПОЛУЧАЕТЕ ВАШУ ТЕКСТОВУЮ ОБЛАСТЬ, ЕЕ ЗНАЧЕНИЕ И ИСПРАВЛЯЕТЕ КАК ХОТИТЕ $.ajax({ type: 'POST', url: "ВАШ URL", data: ВАШИ ДАННЫЕ, dataType: 'json', success: function (response) { //Если все нормально ЧТО ДЕЛАТЬ В СЛУЧАЕ УДАЧНОЙ ОТПРАВКИ И ОБРАБОТКИ }, error: function (response) { //Если ошибка ЧТО ДЕЛАТЬ ЕСЛИ ОШИБКА } }); }); }); </script> 

With the logic you need.

Important! Sending request happens through AJAX.

  • Thanks for the help)) - Zhuk