I am trying to use jsp and java to display information read from a csv to a website. I'm using Tomcat v9.0 with Eclipse.
The java code works as expected when running it just in java—it reads the csv data into an ArrayList of Song objects. However, when running the jsp file, it throws a filenotfoundexception.
The original java code reads and parses the csv in the getter function of "ReadBillboardCSV" here:
public ArrayList<BillboardSong> getReadBillboardCSV() throws FileNotFoundException {
Reader in = new FileReader("testFile.csv");
ArrayList<BillboardSong> readSongs = new ArrayList<BillboardSong>();
try {
Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);
for (CSVRecord record : records) {
BillboardSong newSong = new BillboardSong();
readSongs.add(newSong);
newSong.setPosition(Integer.parseInt(record.get(0)));
My servlet calls the getter, then sets the attribute.
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession ses = request.getSession(true);
ReadBillboardCSV readData = new ReadBillboardCSV();
ArrayList<BillboardSong> songsArray = readData.getReadBillboardCSV();
ses.setAttribute("billboardArray", songsArray);
}
Here is the main portion of the jsp:
<%
RequestDispatcher rd = request.getRequestDispatcher("/ServletOne");
rd.forward(request, response);
%>
Is there a reason it cannot read the file when I run it on Tomcat?
Related
My web application has a new requirement that if parameter coming in url then land to email page. otherwise on index page like always.
Its a very old client product and not much scope to change lot in code so i put a check in controller that if encrypted email coming in then land to email page.
example url -
http://localhost:8080/R2/Controller?email=jAOtTv22BfkTkVrhTN/RHQ==
Everything works fine but i want to change URL.
How can i get rid of " /Controller " in URL but still it hits to controller.???
Controller code like -
public class Controller extends HttpServlet {
static Logger logger = Logger.getLogger(Controller.class);
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// get the action property from the request
String theAction = request.getParameter("action");
String theSource = request.getParameter("s");
String theSource1 = request.getParameter("email");
String em ="";
Action action=null;
em = EncryptEmail.decrypt(theSource1,GFWConstants.BLOWFISH_KEY);
if (em.equals(""))
rd = request.getRequestDispatcher("index.jsp?emailRtv=0");
else
rd = request.getRequestDispatcher("email-preferences.jsp?emailRtv=2&emailAddress="+em);
rd.forward(request,response);
return;
}
Thanks in advance.
adding two url-pattern to web.xml file worked.
I am using OpenCsv API and now i am stuck in some problem.Here's my code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
List<UserRegData> userRegDataList = new ArrayList<UserRegData>();
HttpSession session = request.getSession();
userRegDataList = (List<UserRegData>) session.getAttribute("referralData");
List<String[]> dataToWrite = new ArrayList<String[]>();
String csv = "E:\\carewave_backup\\csv\\UserReferral.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
for (UserRegData obj : userRegDataList) {
dataToWrite.add(new String[]{obj.getReferred_by_name(), obj.getInvitee_name(), obj.getInvitee_email(), obj.getInvitee_date(), obj.getIsInviteeRegistered(), obj.getDate_of_invitee_registered()});
}
writer.writeAll(dataToWrite);
writer.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
out.close();
}
}
This servlet basically retrieves list from session and writes it to csv file.This servlet is triggered after user clicks download csv button.Now what i need is, browser should give a download dialogue.Is there anyway to download it in csv format without writing it to file first?.
I assume you're asking about how to stream the output on the server directly to the client without writing it first to a temp file on the server.
You don't need to write the data to a file first.
Set the resonse content-type to text/csv
Call getOutputStream() on the response object
Write the contents of dataToWrite as individual lines to the output stream
No disk file needed.
I want to create an application that will fetch a JSON object from a servlet to deserialize it, and then use its variables to do other things.
My servlet has the following code in the doPost:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ObjectOutputStream os;
os = new ObjectOutputStream(response.getOutputStream());
String s = new String("A String");
Gson gson = new Gson();
String gsonObject= gson.toJson(s);
os.writeObject(gsonObject);
os.close();
}
Now, while the servlet is running, I can access it via a browser, if I post same code in the doGet method, that would download a servlet file, which is not what I want.
What should I use in my second application that would connect to the servlet, fetch the object, so that I can manipulate it later?
Thanks in advance.
You need few changes in your servlet :
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String s = new String("A String");
String json = new Gson().toJson(s);
this.response.setContentType("application/json");
this.response.setCharacterEncoding("UTF-8");
Writer writer = null;
try {
writer = this.response.getWriter();
writer.write(json);
} finally {
try {
writer.close();
}
catch (IOException ex) {
}
}
}
If its downloading the servlet file instead of showing it in the browser , most probably you have not set the content type in the response. If you are writing a JSON string as the servlet response , you have to use
response.setContentType("text/html");
response.getWriter().write(json);
Please note the order , its "text/html" and not "html/text"
IfI understood the question correctly then you can use, java.net.HttpURLConnection and java.net.URL objects to create a connection to this servlet and read the JSON streamed by the above JSON servlet in your second servlet.
Okay, so I have created a music uploading website that uploads OGG music. It also has an audio tagger incorporated. I also put the album art into my database as a string.
Now, I want to display that string (representing my album art) to my JSP:
#WebServlet(name = "LoadAlbumArt", urlPatterns = { "/LoadAlbumArt" })
public class LoadAlbumArt extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("image/jpg");
try {
OutputStream outputStream = response.getOutputStream();
DBConnector bConnector = new DBConnector();
PreparedStatement preparedStatement = bConnector
.Connect("SELECT * FROM devwebmp3.musicdatabase where musicno = ?");
preparedStatement.setInt(1,
Integer.parseInt(request.getParameter("musicno")));
ResultSet resultSet = preparedStatement.executeQuery();
Blob blob = null;
String imagestring = null;
while (resultSet.next()) {
imagestring = resultSet.getString("albumart");
}
//BufferedImage bi = ImageIO.read(ImageIO.createImageInputStream(new ByteArrayInputStream(Base64Coder.decode(imagestring.toCharArray()))));
//outputStream.write(blob.getBytes(1, (int) blob.length()));
byte[] hello = Base64Coder.decode(imagestring);
//ImageIO.write(bi, "jpg", outputStream);
//System.out.println("byte" + hello);
outputStream.write(hello);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
// ...
}
// ...
}
}
In addition, this is the java servlet page:
src=<%="\"LoadAlbumArt?musicno="+request.getParameter("musicno") +"\""%>>
First of all, where do you call this processRequest(..) method?
Are you sure that you included a call for processRequest(..) in that servlet's doGet(..) method like this:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
processRequest(req,resp);
}
Did you check the output of a known record by requesting
http://.../LoadAlbumArt?musicno=1
Does your Servlet properly response with a JPEG image? If not, then you should check your Servlet code.
Also change your expression in your View page to this:
<img src="/LoadAlbumArt?musicno=${param.musicno}" />
Those JSP scriptlets and expressions (<% %> and <%= %>) are antique relics now, you should NEVER use them unless you have some old code to resurrect.
You didn't give enough details about your database table, BLOB field, even there are random commented code in your question which is hard to decide whether you used them or not.
I need to implement a web server in Java. The web server should download image files that were uploaded by the clients in an HTTP PUT request. What is the procedure for doing it? What Java classes should I use?
Also, if you can recommend a good book that covers these topics it would be great. But the specific question is more important right now.
You should read about Java servlets and servlet containers. Start by implementing a simple servlet that returns "Hello world" string.
Here is the shortest upload/download servlet ever:
import org.apache.commons.io.IOUtils;
#WebServlet(urlPatterns = {"/test"})
public class DownloadServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
File f = new File("test.txt");
resp.setContentLength((int) f.length());
final FileInputStream input = new FileInputStream(f);
IOUtils.copy(input, resp.getOutputStream());
input.close();
}
#Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final FileOutputStream output = new FileOutputStream("test.txt");
IOUtils.copy(req.getInputStream(), output);
output.close();
}
}
First hit:
$ curl -X PUT -d "Hello, servlet" localhost:8080/test
To store given text in a file named test.txt somewhere on your disk. Then simply enter localhost:8080/test in your browser. I think it is a good start.