What I am trying to do is read file and send the text to jsp
first, I read the context of my text file from fileGet.java. Then using request.setAttribute(“chat”, chat), I want to send the context to Live_index6.jsp
However, as I use request.getAttribute(“chat”) in Live_index6.jsp to receive the data, it kept print “null”
I checked that request.getAtrribute successfully printed the data I wanted in fileController.java, but it does not in Live_index6.jsp
I searched internet and it said code in controller
RequestDispatcher rd1 = request.getRequestDispatcher(str); rd1.forward(request, response);
will send the request data to place where I directed, which is str == “Live_index6.jsp” that I setted.
can you guys please check my code and what is the problem?
Thank you so much!
this is my Live_index6.jsp
<%@page import="java.util.ArrayList"%> <%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="EUC-KR"> <title>Insert title here</title> <script src="jquery-3.3.1.js"></script> <style> textarea { width: 300px; height: 300px; } </style> </head> <body> <% String user = request.getParameter("userName"); user = "hong"; %> <%=request.getAttribute("chat") %> <h3>Chat</h3> <textarea row = "20" col="50" readonly id = "ta1"> </textarea><br> <h3>Who?</h3> <input type = "Text" id = "who1" value = "<%=user%>" height = "300px" disabled> <h4>보낼 글</h4> <input type = "text" id = "chat1" onkeyup="enterkey()"> <input type = "button" value = "가자" onclick="insertFile(); kajaChool()"> <br> 귓속말시 /wnickname (chatting)을 해야합니다. 닉네임과 chatting에 빈공간이 없을시 귓속말이 안보내집니다. <script> window.onload = function(){ const name = document.getElementById("who1").value; $.ajax({ // $.ajax() $.get $.post url:"getAllFile.do", data: { name : name }, // kaja.jsp?irum=hong&na2=35 dataType:"text", type:"post", success: function(result1){ //place where I want to print my file context alert(); }, error: function(xhr1,status){ alert("에러상태: " + "t" + xhr1.status); } }); } function enterkey(){ if(window.event.keyCode == 13){ insertFile(); kajaChool(); } } function insertFile(){ const name = document.getElementById("who1").value; const chat = document.getElementById("chat1").value; $.ajax({ // $.ajax() $.get $.post url:"insertFile.do", data: { name : name, chat : chat }, // kaja.jsp?irum=hong&na2=35 dataType:"text", type:"post", success: function(result1){ }, error: function(xhr1,status){ alert("error: " + "t" + xhr1.status); } }); } function kajaChool(){ document.getElementById("who1").disabled = true; var tmp = document.getElementById("chat1").value; if(tmp.substring(0,2) != "/w"){ ta1.value += "[" + who1.value + "]" + chat1.value + "n"; ws1.send("[" + who1.value + "]" + chat1.value); }else{ var index = tmp.indexOf(" ") + 1; var toNickName = tmp.substring(2,index-1); if(true){ ta1.value += "[" + who1.value + "]" + " >> " + "[" + toNickName + "]" + tmp.substring(index) + "n"; ws1.send("[" + who1.value + "]" + chat1.value); }else{ alert("존재하지 않는 닉네임입니다."); chat1.value = ""; chat1.focuse(); return; } } /* if(tmp.indexOf("/w") == -1){ ta1.value += "[" + who1.value + "]" + chat1.value + "n"; }else{ var index = tmp.indexOf(" ") + 1; var toNickName = tmp.substring(2,index-1); ta1.value += "[" + who1.value + "]" + " >> " + "[" + toNickName + "]" + tmp.substring(index) + "n"; } */ // ws1.send("[" + who1.value + "]" + chat1.value); chat1.value = ""; chat1.focuse(); } </script> <script> const ws1 = new WebSocket("ws://localhost:8080/Live_Chat6/kaja"); const ta1 = document.getElementById("ta1"); ws1.onerror = function(aa){ alert("error"); }; ws1.onopen = function(aa){ alert("[chat]"); who1.focus(); who1.select(); }; ws1.onmessage = function(aa){ const name = document.getElementById("who1").value; const arr = aa.data.split("]"); const tmp = arr[1]; const comp = tmp.substring(0,2) == "/w" ; //ta1.value += comp + "n"; if(comp){ var index = tmp.indexOf(" ") + 1; var toNickName = tmp.substring(2,index-1); if(name == toNickName){ ta1.value += "["+arr[0].substring(1)+"] >> " + "[" + toNickName + "]" + tmp.substring(index) + "n"; } }else{ ta1.value += aa.data + "n"; } }; </script> </body> </html>
my FileController.java
package frontController; import java.io.IOException; import javax.servlet.RequestDispatcher; 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 Services.fileGet; import Services.fileImpl; import Services.fileInsert; /** * Servlet implementation class FileController */ @WebServlet("*.do") public class FileController extends HttpServlet { /** * @see HttpServlet#HttpServlet() */ public FileController() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //response.getWriter().append("Served at: ").append(request.getContextPath()); System.out.println("완료"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //doGet(request, response); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); /*******************************/ String c =request.getRequestURI().substring (request.getContextPath().length()); /**********************************/ String str = "Live_index6.jsp"; /////////// fileImpl fi = null; switch(c) { case "/insertFile.do": fi = new fileInsert(); try { fi.fileWork(request, response); }catch(Exception e){ System.out.println(e.getMessage()); } break; case "/getAllFile.do": fi = new fileGet(); try { fi.fileWork(request, response); }catch(Exception e) { System.out.println(e.getMessage()); } break; } //swich -end //String chat = (String) request.getAttribute("chat"); //System.out.println(chat); RequestDispatcher rd1 = request.getRequestDispatcher(str); rd1.forward(request, response); } }
My fileGet.java
package Services; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class fileGet implements fileImpl{ @Override public void fileWork(HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO Auto-generated method stub String path = request.getSession().getServletContext().getRealPath("/") + "/Chat_Log/chat_log.txt"; //String path = "c:/Chat_Log/chat_log.txt"; //ArrayList<String> chat = new ArrayList<String>(); String chat = ""; try{ File file = new File(path); FileReader filereader = new FileReader(file); BufferedReader bufReader = new BufferedReader(filereader); String line = ""; while((line = bufReader.readLine()) != null){ chat += line + "n"; } bufReader.close(); }catch (Exception e) { System.out.println(e.getMessage()); } request.setAttribute("chat", chat); } }
Advertisement
Answer
I faced same problem and to solve it I used HttpSession instead of request and response.sendRedirect instead of requestDispatcher this is the code that I used, you need only to reform it
session.setAttribute("eqmsg", "Equipment Added Successfully"); response.sendRedirect("http://localhost:8080/SmartFarmManagementSystem/addView.jsp");