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.
Related
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?
Whenevr i m trying to do it in plain sql command then it is working but when i try it throgh java it notworking.only a blank table is created with no data?
DELIMITER $$
CREATE PROCEDURE `create_tb_tw`(IN tableName varchar(255),IN x varchar(255),IN y varchar(255))
BEGIN
SET #sql = CONCAT('CREATE TABLE ',tableName,' SELECT * FROM emp
WHERE hiredate >= ',x,'
AND hiredate <= ',y);
PREPARE s FROM #sql;
EXECUTE s;
DEALLOCATE PREPARE s;
END $$
DELIMITER;
call create_tb_tw("x","'1980-12-17'","'1981-02-22'");//working
public class emdetails extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
//db connection
Connection con = DbConnection.getcon();
String Sdate = request.getParameter("Sdate");
String Edate = request.getParameter("Edate");
String TName = request.getParameter("TName");
try {
CallableStatement cStmt = con.prepareCall("{call create_tb_tw(?, ?,?)}");
cStmt.setString(1, TName);
cStmt.setString(2, Sdate);
cStmt.setString(3, Edate);
cStmt.executeQuery();
}
} catch (SQLException ex) {
// System.out.println(emdetails.class.getName()).log(Level.SEVERE, null, ex);
Logger.getLogger(emdetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletReq`enter code heenter code herere`uest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Whenevr i m trying to do it in plain sql command then it is working but when i try it throgh java it notworking.only a blank table is created with no data?
You need to quote the dates
call create_tb_tw("t","'2014-01-01'","'2017-12-31'");
This is the code (Validate.java Servlet File)
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("u");
String password = request.getParameter("p");
Connection con = DBConnection.Connect();
String sql = "select *from users where name=? and pass=?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
request.getRequestDispatcher("WelcomeServlet").forward(request, response); //This line calls another servlet
} catch (SQLException e) {
System.out.println(e.toString());
}
}
}
WelcomeServlet.java Servlet File
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
response.setContentType("html/text");
PrintWriter pw = response.getWriter();
pw.write("<html><body>");
pw.write("<title>Welcome User</title>");
pw.write("<h1>" + username + "</h1>");
pw.write("</body></html>");
pw.close();
}
Output
I want the validate servlet to call welcome servlet but its asking me whether to download a validate servlet file .PFA for more details
I am getting the popup to download Validate Ser
The content type should be text/html (you wrote html/text) otherwise the browser does not know what to do with the file and asks for downloading it.
There are also a few other problems with the code worth mentioning
You do not really check the result from the DB, so you will forward even if the user does not exist.
You use the parameter name u in one servlet but username in the other.
I want to save the image file name submitted in the HTML form in the database as it is the student ID.
So, I first get the image file from the HTML form using:
Part filePart = request.getPart("photo");
However, when I use filePart.getName(); I just get "photo" which is the name of the input tag in the HTML form - <td><input type="file" name="photo" size="50"/></td>.
And if I use filePart.getSubmittedFileName(); I get the entire path like: C:\Users\bnbih\Pictures\testo.jpg.
Is there a way to get the file name only? which is "testo"
This is my JSP file for reference.
/**
*
* #author bnbih
*/
#WebServlet(urlPatterns = {"/uploadServlet"})
#MultipartConfig(maxFileSize = 16177215) // upload file's size up to 16MB
public class FileUploadDBServlet extends HttpServlet {
// database connection settings
private String dbURL = "jdbc:mysql://server_IP:3306/db_name";
private String dbUser = "root";
private String dbPass = "";
/**
* 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 doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
InputStream inputstream = null;//input stream of the uploaded photo
Part filePart = request.getPart("photo");
if(filePart != null){
//print out file info for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
//get the file
inputstream = filePart.getInputStream();
}
Connection con = null;
String message = null;
try{
//connect to the database
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
con = DriverManager.getConnection(dbURL, dbUser, dbPass);
//construct sql statement
String sql = "INSERT INTO StudentInfo (img, student) values (?,?)";
PreparedStatement statement = con.prepareStatement(sql);
if(inputstream != null){
//fetches input stream of the upload file for the blob column
statement.setBlob(1, inputstream);
statement.setString(2, filePart.getSubmittedFileName());
}
//sends the statement to the database server
int row = statement.executeUpdate();
if(row > 0){
message = "Student image uploaded successfully";
}
}catch(SQLException ex){
message = "Something went wrong!! see below \n" + ex.getMessage() + filePart.getSubmittedFileName();
}finally{
if(con != null){
//close db connection
try{
con.close();
}catch(SQLException ex){
ex.printStackTrace();
}
}
//sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet FileUploadDBServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet FileUploadDBServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
}
If you look into some dev tools (I prefer Chrome) on you client while sending upload request, you can notice that in its header there are probably 2 items asociated with each file (each part of multipart has its own header and body). First is name, which as you already know identifies form field ID, and second is filename, which is submitted by browser, since filenames are not part of the file but property of the filesystem which needs to be sent extra. You can get this information by calling getSubmittedFileName() if you are using servlet API 3.1, or parse it yourself.
Just a little warning, not every browser sends the same information, as I believe some send whole filepath. But there are plenty of libraries which can parse just the filename, for example Java 7 Path Paths.get(filePart.getSubmittedFileName()).getFileName().toString() should suffice.
This is the method that solved my problem completely in terms of getting the file name itself with no path or extension.
protected String getFileName(Part p){
String GUIDwithext = Paths.get(p.getSubmittedFileName()).getFileName().toString();
String GUID = GUIDwithext.substring(0, GUIDwithext.lastIndexOf('.'));
return GUID;
}
First of all, this might seem like a duplicate but I assure you I have tried many questions and still hasn't got a proper answer. So I'm asking this here.
I have an HTML form from which I would like to submit a query to a servlet and show the results in a different division.
My HTML code essentially consists of the following:
<form>
<input name="query" id="query" placeholder="Query">
<button id="searchDoc">Search</button>
</form>
<div id="search-results"></div>
I have the following jQuery in order to handle the ajax call.
$('#searchDoc').click(function() {
var q = $('#query').val();
$.ajax({
url: "QueryServlet",
data: {query:q},
success: function(data) {
alert("data: " + data);
$('#search-results').html(data);
}
});
});
My QueryServlet is:
#WebServlet("/QueryServlet")
public class QueryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public QueryServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String query = request.getParameter("query");
QueryUtil qu = new QueryUtil();
String mySqlQuery = qu.buildMySQLSearchQuery(query);
System.out.println(mySqlQuery);
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
con = new DbConnection().getConnection();
st = con.createStatement();
rs = st.executeQuery(mySqlQuery);
if(rs != null) {
response.setStatus(HttpServletResponse.SC_OK);
while(rs.next()) {
out.println("" + rs.getString("fileName") + "");
}
} else {
// TODO add keywords to database
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Even when I submit a valid query, the div does not get loaded up with the data from the servlet. The data reaches the servlet and gets displayed in the console, but I am unable to retrieve that data from the script.
The <button> tag is equivalent to an <input type="submit"/>. If you in your form tag don't declare any action attribute, the standard action causes that the page is reloaded. This causes that, although the returned data are inserted in #search-results div, you'll never be able to see them, because the page is immediately reloaded.
You should deactivate the default "Submit" button this way:
$('#searchDoc').click(function(e) {
e.preventDefault();
[....]
});
This should fix your problem!
the issue seems related to context path, your path should look like this if servlet is not in context root :-
<host> / <context path>/ <servlet>
Thanks :)