How to receive info to put in HTML/JSP from post servlet - java

Basically my goal for this page I'm working on is for users to type in a stock symbol and this information goes to a post method and send back the data to put on the same html/jsp page. I have been able to get this to work where the form leads to another JSP page, but that has to be a separate page, I'd like to be able to stay on the same page and have the info come up. If you have a resource that could teach me how to deal with this problem, I would appreciate that just as much as a solution. I have been using the Gradle Build Tool.
Here is the form(in index.jsp):
<h1>Search Stock</h1>
<form method="POST" action="DataPage.jsp">
<input type = "text" name = "Symbol">
<input type = "submit" name = "getData">
</form>
Here is the functioning JSP code(DataPage.jsp):
<%
String Ticker = request.getParameter("Symbol");
PrintWriter write = response.getWriter();
if((Ticker == null)){
String message = "Please enter a stock symbol";
write.println(message);
}else{
try{
Company object = Serializing.getCompany(Ticker);
object.updateData();
write.println("data last added" + object.getLastUpdate());
write.println(object.getSentiment());
}catch(NullPointerException x){
Company object = Serializing.getCompany(Ticker);
}
}%>
Here is the servlet I tried writing(DataServlet.java), I have very little experience with servlets, I scavenged this from different sources and questions on stackoverflow:
package Default;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created by Ceyer on 9/3/2015.
*/
#javax.servlet.annotation.WebServlet(name = "DataServlet", urlPatterns = ("/"))
public class DataServlet extends javax.servlet.http.HttpServlet {
private static final long serialVersionUID = 1L;
public DataServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
String Ticker = request.getParameter("Symbol");
if ((Ticker == null)||Ticker.trim().isEmpty()) {
String message = "Please enter a stock symbol";
request.setAttribute("data", message);
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} else {
PrintWriter write = response.getWriter();
try {
Company object = Serializing.getCompany(Ticker);
object.updateData();
request.setAttribute("data", object.getSentiment() + "updated last" + object.getLastUpdate());
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} catch (NullPointerException x) {
Company object = Serializing.getCompany(Ticker);
request.setAttribute("data", "We do not have info on this stock");
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

If you want to use only one page and with a servlet, I think you can use session and response.sendRedirect() to do it.
This is index.jsp page
<h1>Search Stock</h1>
<form method="POST" action="DataServlet" onsubmit="dataCheck()">
<input type="text" name="Symbol">
<input type="submit" value="getData">
</form>
<%
if(session.getAttribute("data") != null) {
out.print("<p>" + session.getAttribute("data"));
session.removeAttribute("data");
}
%>
<script>
function dataCheck() {
if(document.getElementsByName[0].value == ""){
alert("Symbol is null!");
return false;
}
return true;
}
</script>
This is DataServlet class
public class DataServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String Ticker = request.getParameter("Symbol");
Company object = Serializing.getCompany(Ticker);
if (object != null) {
object.updateData();
request.getSession().setAttribute("data", object.getSentiment() +
"updated last" + object.getLastUpdate());
} else {
request.getSession().setAttribute("data", "We do not have info on this stock");
}
response.sendRedirect("index.jsp");
}
}

Related

How to show another html page with servlet?

this is my first time with Java's servlet (and JSP) programming and right now I have a doubt. Imagine that I'm building an online shop with a login page (let's suppose is the starting page) and maybe a shopping page (the "second" one). My servlet contains the code for autenticate the users and if the user is correct the servlet should shows the shopping catalog. My answer is, what's the best method for doing this? This is my servlet code (doGet) now:
nb: userName and password come from the login page...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userName = request.getParameter("userName");
String password = request.getParameter("password");
out.println("<html>");
out.println("<body bgcolor = 'green'>");
out.println("<br>" + "Hello " + " " + userName + "<br> LOGGED IN!" + "<br>");
out.println("Your password is : " + " " + password + "<br>");
if(userName.equals("some_correct_user")) {
out.println("<p>Login correct </p>");
response.sendRedirect("/FirstServletExercise/shoppingPage.html");
}
else {
out.println("<p>Access denied</p>");
}
I know it's very simple but is just the concept: it's correct to use "sendRedirect" to display another different page, or I have to upgrade the content of the first page? And how I can do this? Hope I have explained myself well.
Thanks!
I am using Jetty-11 Server standalone/embedded mode. And here is how the Login Servlet looks like.
import java.io.IOException;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
private Logger log = LoggerFactory.getLogger(LoginServlet.class);
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
log.debug("LoginServlet {} userPrincipal: {}", req.getServletPath(), req.getUserPrincipal());
Map<String, String[]> p = req.getParameterMap();
p.forEach((k, v) -> {
log.debug("{} {}", k, v);
});
String un = (p.get("j_username") != null) ? p.get("j_username")[0] : null;
String up = (p.get("j_password") != null) ? p.get("j_password")[0] : null;
try {
if (un != null && up != null) {
req.logout();
req.login(un, up);
}
} catch (Exception e) {
log.error("AuthenticationException: ", e);
}
log.debug("{} userPrincipal: {}", req.getServletPath(), req.getUserPrincipal());
boolean isAuth = (req.getUserPrincipal() == null) ? false : true;
log.debug("isAuth: {}", isAuth);
resp.setContentType("text/html");
if (isAuth) {
/** Session Management */
HttpSession session = req.getSession();
session.setAttribute("user", req.getUserPrincipal().getName());
// setting session to expiry in 30 mins
session.setMaxInactiveInterval(30 * 60);
log.debug("sessionId: {} ", req.getSession().getId());
/** Cookie Management */
Cookie loginCookie = new Cookie("user", req.getUserPrincipal().getName());
loginCookie.setMaxAge(30 * 60);
resp.addCookie(loginCookie);
/** Login Success - so display the Home Page */
resp.sendRedirect("./index.html");
} else {
Cookie loginCookie = new Cookie("user", "unknownUser");
loginCookie.setMaxAge(0);
loginCookie.setPath("/");
resp.addCookie(loginCookie);
req.getRequestDispatcher("./login.html").forward(req, resp);
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

tomcat gives 404 error while my mapping in xml is fine

public class Guestbook extends CacheHttpServlet {
/**
*
*/
private static final long serialVersionUID = 1 L;
private Vector < GuestbookEntry > entries = new Vector < GuestbookEntry > ();
private long lastModified = 0; // Time last entry was added
// Display the current entries, then ask for a new entry
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
printHeader(out);
printForm(out);
printMessages(out);
printFooter(out);
}
// Add a new entry, then dispatch back to doGet()
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
handleForm(req, res);
doGet(req, res);
}
private void printHeader(PrintWriter out) throws ServletException {
out.println("<HTML><HEAD><TITLE>Guestbook</TITLE></HEAD>");
out.println("<BODY>");
}
private void printForm(PrintWriter out) throws ServletException {
out.println("<FORM METHOD=POST action='/hello.html'>"); // posts to itself
out.println("<B>Please submit your feedback:</B><BR>");
out.println("Your name: <INPUT TYPE=TEXT NAME=name><BR>");
out.println("Your email: <INPUT TYPE=TEXT NAME=email><BR>");
out.println("Comment: <INPUT TYPE=TEXT SIZE=50 NAME=comment><BR>");
out.println("<INPUT TYPE=SUBMIT VALUE=\"Send Feedback\"><BR>");
out.println("</FORM>");
out.println("<HR>");
}
private void printMessages(PrintWriter out) throws ServletException {
String name, email, comment;
Enumeration < GuestbookEntry > e = entries.elements();
while (e.hasMoreElements()) {
GuestbookEntry entry = (GuestbookEntry) e.nextElement();
name = entry.name;
if (name == null) {
name = "Unknown user";
email = "Unknown email";
}
email = entry.email;
comment = entry.comment;
if (comment == null) comment = "No comment";
out.println("<DL>");
out.println("<DT><B>" + name + "</B> (" + email + ") says");
out.println("<DD><PRE>" + comment + "</PRE>");
out.println("</DL>");
// Sleep for half a second to simulate a slow data source
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {}
}
}
private void printFooter(PrintWriter out) throws ServletException {
out.println("</BODY>");
out.println("</HTML>");
}
private void handleForm(HttpServletRequest req,
HttpServletResponse res) {
GuestbookEntry entry = new GuestbookEntry();
entry.name = req.getParameter("name");
entry.email = req.getParameter("email");
entry.comment = req.getParameter("comment");
entries.addElement(entry);
// Make note we have a new last modified time
lastModified = System.currentTimeMillis();
}
public long getLastModified(HttpServletRequest req) {
return lastModified;
}
}
class GuestbookEntry {
public String name;
public String email;
public String comment;
}
And in the XML file i used
<web-app>
<servlet>
<servlet-name>
GuestBook
</servlet-name>
<servlet-class>
Guestbook
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
GuestBook
</servlet-name>
<url-pattern>
/hello.html
</url-pattern>
</servlet-mapping>
</web-app>
everything i used are fine but tomcat still gives me a 404 error. although i tried by different methods but still it gives me an error.
if someone will provide a solution then it would be really appreciated.
thanks in advance
we would need to create a separate html page and will write the same content as "PrintForm" method in the code. if we do so then this servlet will work perfectly. Although this servlet used for server cache, i hope it will help you in future.
thank you

Can't call doPost from doGet

When I'm calling doPost directly, it shows me profile page in correct way. But then after login I open new tab in Chrome copy url "http://localhost:8080/17_servlets_jsp/profile" there and it shows me blank page
#WebServlet("/profile")
public class Profile extends HttpServlet {
**private String login;**
private HttpSession httpSession;
private User user;
private Role role;
public static Logger LOGGER = LogManager.getLogger(Profile.class.getName());
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
httpSession = req.getSession();
try (PrintWriter out = resp.getWriter()) {
**if (httpSession.getAttribute("userLoggedIn") == null) {
out.println("<title>Login Page</title>");
out.println("<p>Please follow the link to login</p>");
} else {
login = (String) httpSession.getAttribute("uLogin");
doPost(req, resp);
}**
} catch (IOException | NullPointerException e) {
LOGGER.error(e);
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
**login = req.getParameter("login");
user = new ImplUserDAO().findByLogin(login);**
httpSession = req.getSession();
resp.setContentType("text/html");
try (PrintWriter out = resp.getWriter()) {
out.println("<title>Profile page</title>");
if (user != null && user.getPassword().equals(req.getParameter("pass"))) {
role = new ImplRoleDAO().findById(user.getRoleId());
httpSession.setAttribute("userLoggedIn", true);
httpSession.setAttribute("uLogin",req.getParameter("login"));
httpSession.setAttribute("uPass",req.getParameter("pass"));
out.println("user id = " + user.getUserId());
out.println("login = " + user.getLogin());
out.println("password = " + user.getPassword());
out.println("role = " + role.getRoleName());
out.println("<form action=\"logout\" method=\"get\"/>" +
"<input type=\"submit\" value=\"Logout\"/>" +
"</form>");
if (role.getRoleName().equals("admin")) {
httpSession.setAttribute("isAdmin", true);
out.println("Go to admin page");
}
} else {
out.println("Wrong login or password");
out.println("Please follow the link to login");
}
} catch (IOException | NullPointerException e) {
LOGGER.error(e);
}
}
}
By calling doPost() you also execute this line:
user = new ImplUserDAO().findByLogin(req.getParameter("login"));
Which will throw an Exception or return null or whatever because your GET request didn't include that parameter. If you want to reuse doPost() you'd need to fetch login from either session or request:
String login = req.getParameter("login");
if(null == login) {
login = (String)httpSession.getAttribute("uLogin");
}
Or similar.
On Attributes and Parameters
In your commented out code, you tried to solve this issue by calling setAttribute("login"... on your request. While this is legal, you can not retrieve that value by calling getParameter(). Instead you'd have to call 'getAttribute()` again - which doesn't make much difference to retrieving directly from the session:
//Retrieve Parameter (been send into the servlet from outside)
String login = req.getParameter("login");
if(null == login) {
//Retrieve Attribute you put into the request in doGet()
login = (String)req.getAttribute("login");
}
Another Edit
You have the same issue with req.getParameter("pass").
You should seriously consider splitting login-process (checking username/password from request) from other functionality (display profile page) or reverse your logic: Do login, set user into session in doPost() and if successful call goGet()?
Full Example Code
Consider these changes to somewhat fix your logic:
#WebServlet("/profile")
public class Profile extends HttpServlet {
// Don't use member variables on Servlets - they get reused for all users!
// private String login;
// private HttpSession httpSession;
// private User user;
// private Role role;
public static Logger LOGGER = LogManager.getLogger(Profile.class.getName());
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
HttpSession httpSession = req.getSession();
try (PrintWriter out = resp.getWriter()) {
if (httpSession.getAttribute("userLoggedIn") == null) {
out.println("<title>Login Page</title>");
out.println("<p>Please follow the link to login</p>");
}
else {
User user = httpSession.getAttribute("userLoggedIn");
Role role = httpSession.getAttribute("userRole");
out.println("<title>Profile page</title>");
out.println("user id = " + user.getUserId());
out.println("login = " + user.getLogin());
out.println("password = " + user.getPassword());
out.println("role = " + role.getRoleName());
out.println("<form action=\"logout\" method=\"get\"/>" +
"<input type=\"submit\" value=\"Logout\"/>" +
"</form>");
if("true".equals(httpSession.getAttribute("isAdmin")) {
httpSession.setAttribute("isAdmin", true);
out.println("Go to admin page");
}
}
} catch (IOException | NullPointerException e) {
LOGGER.error(e);
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String login = req.getParameter("login");
User user = new ImplUserDAO().findByLogin(login);
HttpSession httpSession = req.getSession();
try (PrintWriter out = resp.getWriter()) {
if (user != null && user.getPassword().equals(req.getParameter("pass"))) {
Role role = new ImplRoleDAO().findById(user.getRoleId());
httpSession.setAttribute("userLoggedIn", user);
httpSession.setAttribute("userRole", role);
if (role.getRoleName().equals("admin")) {
httpSession.setAttribute("isAdmin", true);
}
// Now refer to display part.
goGet(req, resp);
} else {
out.println("Wrong login or password");
out.println("Please follow the link to login");
}
} catch (IOException | NullPointerException e) {
LOGGER.error(e);
}
}
}

SQL syntax error in pagination query

I'm trying to make pagination in my jsp page. But I didn't get data from Database. I got an error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-10, 5' at line 1".
I didn't understand what's wrong. would you please check my code and help me to solve the problem?
BooksInfo.java
package com.sreejonee.books;
import java.sql.Date;
import java.sql.Timestamp;
public class BooksInfo {
private int book_id;
private String bookName;
private String filename;
private String writerName;
private String book_details;
private Timestamp date_time;
private int rating;
private int parentscat_id;
private String parentscat_name;
private String thumCoverImag;
private String filePath;
public int getBook_id() {
return book_id;
}
public void setBook_id(int book_id) {
this.book_id = book_id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getWriterName() {
return writerName;
}
public void setWriterName(String writerName) {
this.writerName = writerName;
}
public String getBook_details() {
return book_details;
}
public void setBook_details(String book_details) {
this.book_details = book_details;
}
public Timestamp getDate_time() {
return date_time;
}
public void setDate_time(Timestamp date_time) {
this.date_time = date_time;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public int getParentscat_id() {
return parentscat_id;
}
public void setParentscat_id(int parentscat_id) {
this.parentscat_id = parentscat_id;
}
public String getParentscat_name() {
return parentscat_name;
}
public void setParentscat_name(String parentscat_name) {
this.parentscat_name = parentscat_name;
}
public String getThumCoverImag() {
return thumCoverImag;
}
public void setThumCoverImag(String thumCoverImag) {
this.thumCoverImag = thumCoverImag;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
BooksInfoDAO.java
package com.sreejonee.books;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import com.sreejonee.db.ConnectionFactory;
import com.sreejonee.db.DBConnector;
public class BooksInfoDAO {
Connection connection;
Statement stmt;
private int noOfRecords;
private static Connection getConnection()
throws SQLException,
ClassNotFoundException
{
Connection con = ConnectionFactory.
getInstance().getConnection();
System.out.println("connected!");
return con;
}
public List<BooksInfo> viewAllBooksInfo(int offset, int noOfRecords) {
String query = "select SQL_CALC_FOUND_ROWS * from library ORDER by date_time DESC limit"+ offset + ", " + noOfRecords;
List<BooksInfo> bookslist = new ArrayList<BooksInfo>();
BooksInfo books = null;
try {
connection = getConnection();
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
books = new BooksInfo();
books.setBook_id(rs.getInt("book_id"));
books.setBook_details(rs.getString("book_details"));
books.setBookName(rs.getString("bookName"));
books.setWriterName(rs.getString("writerName"));
books.setDate_time(rs.getTimestamp("date_time"));
books.setParentscat_id(rs.getInt("parentscat_id"));
books.setParentscat_name(rs.getString("parentscat_name"));
books.setFilename(rs.getString("filename"));
books.setFilePath(rs.getString("filePath"));
books.setRating(rs.getInt("rating"));
books.setThumCoverImag(rs.getString("thumCoverImag"));
bookslist.add(books);
}
rs.close();
rs = stmt.executeQuery("SELECT FOUND_ROWS()");
if (rs.next())
this.noOfRecords = rs.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e2) {
e2.printStackTrace();
}
}
return bookslist;
}
public int getNoOfRecords() {
return noOfRecords;
}
}
Servlet:
BooksInfoServlet.java
package com.sreejonee.servlet;
import java.io.IOException;
import java.util.List;
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 com.sreejonee.books.BooksInfo;
import com.sreejonee.books.BooksInfoDAO;
#WebServlet("/BooksInfoServlet")
public class BooksInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public BooksInfoServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int page = 1;
int recordsPerPage = 5;
if(request.getParameter("page") != null)
page = Integer.parseInt(request.getParameter("page"));
BooksInfoDAO booksInfoDAO = new BooksInfoDAO();
List<BooksInfo> bookslist = booksInfoDAO.viewAllBooksInfo((page-1)*recordsPerPage, recordsPerPage);
int noOfRecords = booksInfoDAO.getNoOfRecords();
int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
request.setAttribute("booksList", bookslist);
request.setAttribute("noOfPages", noOfPages);
request.setAttribute("currentPage", page);
RequestDispatcher view = request.getRequestDispatcher("user.jsp");
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
JSP page:
<c:forEach var="books" items="${bookslist}">
<div id="${books.filename}" class="single_midlecontent_component">
<div class="socialicon_on_post">
<h4>
<i class="fa fa-facebook-square"></i>
</h4>
</div>
<div class="title_of_post ">
<a href="#" class="media-left">
<img class="media-object" src="${books.getFilePath()+File.separator+books.getThumCoverImag()}" alt="...">
</a>
<h5 class="media-body ">
<span>${books.getBookName()}</span>
</h5>
<h5 class="media-body ">
<span>by ${books.getWriterName()}</span>
</h5>
<p class="date_time media-body">${books.getDate_time()}</p>
</div>
<div class="body_of_post">
<p>${books.getBook_details()}</p>
<img src="" class="img-responsive" alt="Responsive image">
</div>
<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-layout="standard" data-action="like" data-show-faces="true" data-share="true"></div>
<div class="download_book">
<form action="DownloadFileServlet" method="post">
<input type="hidden" name="filename" value="${books.getFilename()}">
<div>
<input type="hidden" name="parentscat_name" value="${books.getParentscat_name()}">
</div>
<div class="download_button">
<input class="btn btn-default " type="submit" value="Download">
</div>
</form>
</div>
<div class="bottom_of_post"></div>
</div>
I can see two errors here.
First one:
String query = "select SQL_CALC_FOUND_ROWS * from library ORDER by date_time DESC limit"+ offset + ", " + noOfRecords;
There is a space missing after limit -- the way you wrote it, it will generate ... limit10, 5.
Second one:
I think the caller of viewAllBooksInfo() gives a wrong offset argument. Based on the error, I assume that offset is -10 which is illegal because the arguments to the limit clause in MySQL need to be non-negative.
In your updated question, you show this code:
if(request.getParameter("page") != null)
page = Integer.parseInt(request.getParameter("page"));
BooksInfoDAO booksInfoDAO = new BooksInfoDAO();
List<BooksInfo> bookslist = booksInfoDAO.viewAllBooksInfo((page-1)*recordsPerPage, recordsPerPage);
Obviously, because recordsPerPage is 5, and offset is -10, page seems to be -1. You have not shown the Code for the page which calls the BooksInfoServlet, but I guess you have entered -1 as the requested page number there.
You should have looked yourself before asking this question. It is expected from you that you should first try to remove these error yourself.
If you would look into the error stack, it says:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-10, 5' at line 1"
If you can look carefully, the limit options are "-10, 5". Limit arguments in MySQL should be non-negative.
And in BooksInfoDAO.java code:
public List<BooksInfo> viewAllBooksInfo(int offset, int noOfRecords) {
String query = "select SQL_CALC_FOUND_ROWS * from library ORDER by date_time DESC limit"+ offset + ", " + noOfRecords;
...
you are missing a space between the limit clause and the offset parameter.

Uploading multiple files using jsp & servlets [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 2 years ago.
I am currently working on a dynamic web application that I want the user to be able to upload multiple files at once for the application to use. I don't know how many files the user may upload at once; it could be 2 or it could 100+ files. I am new to JSP dynamic web applications and I have started with a single upload file but I am not really sure where to go from here. I've looked at few examples searching but I haven't been able to find exactly what I was looking for. This is what I have so far:
Servlet:
package Servlets;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (isMultipart)
{
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
// Parse the request
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext())
{
FileItem item = (FileItem) iterator.next();
if (!item.isFormField())
{
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists())
{
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
if(fileName!="")
item.write(uploadedFile);
else
out.println("file not found");
out.println("<h1>File Uploaded Successfully....:-)</h1>");
}
else
{
String abc = item.getString();
out.println("<br><br><h1>"+abc+"</h1><br><br>");
}
}
}
catch (FileUploadException e)
{
out.println(e);
}
catch (Exception e)
{
out.println(e);
}
}
else
{
out.println("Not Multipart");
}
}
}
.JSP File:
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
<p><input type="file" name="dataFile" id="fileChooser" />
<input type="submit" value="Upload" multiple="multiple" /></p>
</form>
I am looking for a way to upload multiple files instead of just one and show them in a list.
Check the FileUPload Using Servlet 3.0
It has a working code for uploading Single File Using Servlet3.0 As you can see code is now much simplified . And there is no dependancy on apache Library.
just use below index.html
<html>
<head></head>
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
Select File to Upload:<input type="file" name="fileName" multiple/>
<br>
<input type="submit" value="Upload"/>
</form>
</body>
</html>
Only change here is I have used multiple attribute for input type File
Oh... At the first glance, looks like a simple mistake. multiple is an attribute of file input, not of the submit button.
i have upload multiple files using jsp /servlet.
following is the code that i have used.
<form action="UploadFileServlet" method="post">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>
on the other hand server side. use following code.
package com.abc..servlet;
import java.io.File;
---------
--------
/**
* Servlet implementation class UploadFileServlet
*/
public class UploadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadFileServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.sendRedirect("../jsp/ErrorPage.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
HttpSession httpSession = request.getSession();
String filePathUpload = (String) httpSession.getAttribute("path")!=null ? httpSession.getAttribute("path").toString() : "" ;
String path1 = filePathUpload;
String filename = null;
File path = null;
FileItem item=null;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
String FieldName = "";
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
item = (FileItem) iterator.next();
if (fieldname.equals("description")) {
description = item.getString();
}
}
if (!item.isFormField()) {
filename = item.getName();
path = new File(path1 + File.separator);
if (!path.exists()) {
boolean status = path.mkdirs();
}
/* START OF CODE FRO PRIVILEDGE*/
File uploadedFile = new File(path + Filename); // for copy file
item.write(uploadedFile);
}
} else {
f1 = item.getName();
}
} // END OF WHILE
response.sendRedirect("welcome.jsp");
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
images.jsp
choose files:
storeimages.java servlet
public class storeimages extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
String sav_dir=""; //this will be a folder inside
//directory
PrintWriter out =response.getWriter();
//if you want u can give this at run time
sav_dir="6022"; //in my case folder name is 6022
//you can alse set this at dynamic
int flag = 0;
//now set the path
//this is the path where my images are stored
//now u can see the code
String savepath="K:/imageupload"+File.separator +sav_dir;
File file = new File(savepath);
if(!file.exists()){
file.mkdir();
}
String filename="";
List<Part> fileParts = request.getParts().stream().
filter(part->"file".equals(part.getName())).collect(Collectors.
toList());
for(Part filePart: fileParts){
filename=Paths.get(filePart.getSubmittedFileName()).
getFileName().toString();
filePart.write(savepath+File.separator+filename);
flag=1;
}
if(flag==1){
out.println("success");
}
else{
out.println("try again");
}
//now save this and run the project
}
}
You only have to write multiple, because multiple is a boolean var and only defining it, it will be true to your tag. Example below:
<input type="file" name="file" id="file" multiple/>
This will let you choose multiple files at once. Good luck
This is how I did. It will dynamically add and remove the field (multiple files). Validates it and on validation calls the action method i.e the servlet and store in the DB.
** html/jsp **
.jsp file
<div class="recent-work-pic">
<form id="upload_form" method="post" action="uploadFile" enctype="multipart/form-data" >
<input type="hidden" id="counter" value="1" >
Add
<div class="record"><input type="file" placeholder="Upload File" name="uploadFile_0" class="upload_input"></div>
<div id="add_field_div"></div>
<button type="submit" class="btn btn-read">Submit</button>
</form>
<p>${message}</p>
</div>
jquery validation
<script>
$(document).ready(function(){
$('#add_fields').click( function(){
add_inputs()
});
$(document).on('click', '.remove_fields', function() {
$(this).closest('.record').remove();
});
function add_inputs(){
var counter = parseInt($('#counter').val());
var html = '<div class="record"><input type="file" placeholder="Upload File" name="uploadFile_' + counter + '" class="upload_input">Remove</div>';
$('#add_field_div').append(html);
$('#counter').val( counter + 1 );
}
$('form#upload_form').on('submit', function(event) {
//Add validation rule for dynamically generated name fields
$('.upload_input').each(function() {
$(this).rules("add",
{
required: true,
messages: {
required: "File is required",
}
});
});
});
$("#upload_form").validate();
});
</script>
servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// KeycloakPrincipal principal = (KeycloakPrincipal) request.getUserPrincipal();
PrintWriter writer = response.getWriter();
Properties properties = new Properties();
properties.load(this.getClass().getClassLoader().getResourceAsStream("/resources/datenBank.properties"));
if (!ServletFileUpload.isMultipartContent(request)) {
writer.println("Fehler: Form must has enctype=multipart/form-data.");
writer.flush();
return;
}
String message = null;
InputStream inputStream = null;
Connection dbConnection = null;
String page = "";
try {
for (Part filePart : request.getParts()) {
System.out.println("filePart" + filePart.getName() + "-----" + filePart.getSize());
if (filePart != null && filePart.getSize() != 0) {
inputStream = filePart.getInputStream();
System.out.println("inputStream" + inputStream);
HttpSession session=request.getSession();
session.setAttribute("username",request.getRemoteUser());
Class.forName(properties.getProperty("driverClassName"));
dbConnection = DriverManager.getConnection(properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password"));
if (dbConnection != null) {
String sql = "INSERT INTO skl_lieferung (file_name, file_size, file_content,file_content_type, entry_time, user) values (?,?,?,?,?, ?)";
PreparedStatement statement = dbConnection.prepareStatement(sql);
if (inputStream != null) {
statement.setString(1, getFileName(filePart));
statement.setLong(2, filePart.getSize());
statement.setBlob(3, inputStream);
statement.setString(4, filePart.getContentType());
}
Calendar calendar = Calendar.getInstance();
java.sql.Date entryDate = new java.sql.Date(calendar.getTime().getTime());
statement.setDate(5, entryDate);
statement.setString(6, request.getRemoteUser());
//statement.setString(6, username);
int row = statement.executeUpdate();
if (row > 0) {
message = "Datei hochgeladen und in der Datenbank gespeichert";
}else {
message = "Fehler: Connection Problem";
}
} message = "Datei hochgeladen und in der Datenbank gespeichert";
}else {
page = "index.jsp";
System.out.println("cannot execute if condition");
message = "Das Upload-Feld darf nicht leer sein ";
RequestDispatcher dd = request.getRequestDispatcher(page);
dd.forward(request, response);
return;
}
}
}catch (Exception exc) {
page = "index.jsp";
message = "Fehler: " + exc.getMessage();
exc.printStackTrace();
} finally {
if (dbConnection != null) {
try {
dbConnection.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
page = "index.jsp";
request.setAttribute("message", message);
RequestDispatcher dd = request.getRequestDispatcher(page);
dd.forward(request, response);
}
}
}
private String getFileName(Part part) {
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
I hope people find it useful!!
To upload a single file you should use a single tag with attribute type="file". To allow multiple files uploading, include more than one input tags with different values for the name attribute. The browser associates a Browse button with each of them.
That is, use the below line multiple times:
<input type="file" name="dataFile" id="fileChooser" /><br><br>
Refer this link for details
I hope this helps.

Categories

Resources