How to get value without accessing database? - java

I need your help. I'm currently doing a project on purchase. After the user click on Add to cart, the item will be added to the cart but not yet persist into database. Then later on, I will have the user to click checkout. PurchaseCart.jsp will do action and bring them to PurchaseCheckOut servlet. So, how can I get the data from previous ?
PurchaseCart.jsp
<body>
<%!List<Double> stockArray = new ArrayList<Double>() ;%>
<%!List<Object> list1 = new ArrayList<Object>();%>
<% Object o = request.getAttribute("purchased");
list1.add(o);
int size = list1.size();
double stockPrice = (Double)request.getAttribute("stockPriceReal");
if(stockArray.size() == 0)
{
stockArray.add(stockArray.size(),stockPrice);
}
else {
stockArray.add(stockArray.size(), stockPrice); } %>
<form action = "../PurchaseCheckOut">
<table border="1">
<thead>
<tr>
<th>No.</th>
<th>Purchase Details ID</th>
<th>Stock ID</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<% for (int g = 0; g < size; g ++) { %>
<tr>
<% String toString = list1.get(g).toString();
String subString1 = toString.substring(0,7);
String subString2 = toString.substring(7,9);
String subString3 = toString.substring(9,14);
%>
<td><%= g +1 %></td>
<td><%= subString1 %></td>
<td><%= subString2 %></td>
<td><%= subString3 %></td>
<td><%= stockArray.get(g).toString() %></td>
</tr>
<% } %>
</tbody>
</table>
<input type = submit name="checkout" value="Check Out">
</form>
</body>
PurchaseCheckOut.java (I've done the persist part and redirect part but I have no idea how to get the value. ? is the value i'm passing in.)
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
PurchaseService ps = new PurchaseService(em);
utx.begin();
boolean success = ps.addPurchaedetails(?);
utx.commit();
HttpSession session = request.getSession();
session.setAttribute("success", success);
response.sendRedirect("MemberAccess/AddConfirm.jsp");
}
catch (Exception ex) {
Logger.getLogger(PurchaseCheckOut.class.getName()).log(Level.SEVERE, null, ex);
}
PurchaseService for addPurchasedetails
public boolean addPurchasedetails(Purchasedetails purcD) {
mgr.persist(purcD);
return true; }
Structure of the purchase works like this : PurchaseM.jsp(let user to choose) -> PurchaseCreate.java(pass all the value to cart) -> PurchaseCart.jsp (display the value(not yet persist))-> PurchaseCheckOut.java(persist) -> AddConfirm.jsp(display "You've done")

You can store the add to cart value in a Session object and refer anywhere you need to.

Related

Trouble running overridden doPost method in a java servlet [duplicate]

This question already has answers here:
How do I call a specific Java method on a click/submit event of a specific button in JSP?
(4 answers)
How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
(1 answer)
Closed 3 years ago.
The code below is from the jsp file.
<table class="table table-striped table-hover table-responsive ezoo-datatable">
<thead>
<tr>
<th class="text-center">Schedule ID</th>
<th class="text-center">Feeding Time</th>
<th class="text-center">Recurrence</th>
<th class="text-center">Notes</th>
<th class="text-center">Food</th>
<th class="text-center">Animal ID</th>
<th></th>
</tr>
</thead>
<% int counter = 0; %>
<tbody>
<form action="feedingSchedules" method="post">
<c:forEach var="schedule" items="${feeding_schedules}">
<tr>
<td><c:out value="${schedule.schedule_ID}" /></td>
<td><c:out value="${schedule.feeding_time}" /></td>
<td><c:out value="${schedule.recurrence}" /></td>
<td><c:out value="${schedule.notes}" /></td>
<td><c:out value="${schedule.food}" /></td>
<td><c:out value="${schedule.animalID}" /></td>
<td><button class="btn-danger-stale" name="btn${counter}" value="val${counter}">Delete Schedule</button></td>
<% counter++; %>
</tr>
</c:forEach>
<input type="hidden" name="numSchedules" value="${counter}"/>
</form>
</tbody>
</table>
This code builds a table of data. I have a servlet to populate the table by fetching data from a database in a call to a dao method. I need to add buttons to the table to delete the row corresponding to the button. I have the buttons in place, but I'm not sure how to get them to perform the actual deletion.
#WebServlet(description = "This servlet is the main interface into the Feeding Schedules System", urlPatterns = { "/feedingSchedules" })
public class FeedingSchedulesServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Grab a list of Animals from the Database
FeedingScheduleDAO dao = DAOUtilities.getFeedingScheduleDao();
List<FeedingSchedule> schedules = dao.getAllSchedules();
// Populate the list into a variable that will be stored in the session
request.getSession().setAttribute("feeding_schedules", schedules);
request.getRequestDispatcher("feedingScheduleHome.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
FeedingScheduleDAO dao = DAOUtilities.getFeedingScheduleDao();
List<FeedingSchedule> schedules = dao.getAllSchedules();
//Get Parameters
System.out.println("got here");
int count = Integer.parseInt(request.getParameter("numSchedules"));
for(int i = 0; i < count; i++) {
String btn = null;
btn = request.getParameter("btn" + i);
if(btn == ("val" + i)) {
System.out.println("got here");
// call delete method from DAO
try {
dao.deleteSchedule(schedules.get(i));
request.getSession().setAttribute("message", "Schedule successfully deleted");
request.getSession().setAttribute("messageClass", "alert-success");
response.sendRedirect("feedingSchedules");
} catch (Exception e) {
e.printStackTrace();
request.getSession().setAttribute("message", "There was a problem deleting the schedule at this time");
request.getSession().setAttribute("messageClass", "alert-danger");
request.getRequestDispatcher("feedingScheduleHome.jsp").forward(request, response);
}
}
}
}
}
The above code is the servlet. The print lines I put in the overridden doPost method do not show in the console when I click the buttons, so I do not believe the method is being called properly. Does anyone know what I'm doing wrong? I've spent a few hours staring at this and could use some fresh eyes.
Assign an id to your form e.g.
<form id="myForm" action="feedingSchedules" method="post">
And replace
<button class="btn-danger-stale" name="btn${counter}" value="val${counter}">Delete Schedule</button>
with
<button class="btn-danger-stale" name="btn${counter}" value="val${counter}" onclick="document.getElementById('myForm').submit();">Delete Schedule</button>
Alternatively,
Assign an id to your form as mentioned above and also to your button as mentioned below:
<button id="myButton" class="btn-danger-stale" name="btn${counter}" value="val${counter}">Delete Schedule</button>
and add the following javascript in your jsp file:
var form = document.getElementById("myForm");
document.getElementById("myButton").addEventListener("click", function () {
form.submit();
});

how to convert Calendar type to String?

i tried to convert calendar type to String for display the date in my jsp page
here is my servlet code where i convert string to calendar type
private Evaluation EvaluationMapper(HttpServletRequest request)
{
try {
Evaluation eval = new Evaluation();
eval.setNumero(Integer.parseInt(request.getParameter("numero")));
eval.setNom(request.getParameter("nom"));
eval.setPrenom(request.getParameter("prenom"));
eval.setTelephone(request.getParameter("telephone"));
eval.setCourriel(request.getParameter("courriel"));
eval.setSexe(request.getParameter("sexe").charAt(0));
eval.setNote(request.getParameter("note"));
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(df.parse(request.getParameter("date")));
eval.setDateEvaluation(cal);
eval.setCommentaire(request.getParameter("commentaires"));
return eval;
} catch (ParseException ex) {
throw new IllegalArgumentException("Erreur..??");
}
}
and here is my code for my jsp page but its didn't display the date
<% for(Evaluation e:(List<Evaluation>)request.getAttribute("ListeEvaluation")){%>
<tr><td><%= e.getNumero()%> </td>
<td><%= e.getNom() %> </td>
<td><%= e.getPrenom()%> </td>
<td><%= e.getTelephone()%> </td>
<td><%= e.getCourriel()%> </td>
<td><%= e.getSexe()%> </td>
<td><%= e.getNote()%> </td>
<td><%= e.getDateEvaluation()%> </td>
<td><%= e.getCommentaire()%> </td>
<td>
<a href="/Labo2/SupprimerServlet?numero=<%= e.getNumero()%>" >Supprimer</a> |
<a href="/Labo2/ModifierServlet?numero=<%= e.getNumero()%>" >Modifier</a>
</td>
</tr>
<%}%>
here my listEvaluation
private static List<Evaluation> ListeEvaluation = new ArrayList<Evaluation>();
public Evaluation evaluation = new Evaluation();
//set method
public void setListeEvaluation(List value){this.ListeEvaluation = value;}
//getmethod
public List<Evaluation> getListeEvaluation(){return this.ListeEvaluation;}
so how cant i convert getDateEvaluation in string?
If you want to get values of attribute "ListeEvaluation" from request in JSP as follows:
<% for(Evaluation e:(List<Evaluation>)request.getAttribute("ListeEvaluation")){%>
you should set attribute "ListeEvaluation" in your servlet:
List<Evaluation> listeEvaluation = new ArrayList<>();
for (...) {
Evaluation evaluation = new Evaluation();
evaluation.setNumero(...);
evaluation.setNom(...);
...
listeEvaluation.add(evaluation);
}
request.setAttribute("ListeEvaluation", listeEvaluation);

I can't read input values in jsp from Servlet

In my jsp I have many input type number tags. When I submit them I go to my servlet who needs to read them to save the values in a database. I have tried request get attribute , get parameter, but they always return null values. I have also tried using Servlet File Upload but it returns a class cast exception saying that it can not cast MonitorRequestWrapper to RequestContext.
my jsp code:
<form method="GET" action="HomeServlet">
<c:forEach var="kat" items="${requestScope.Category}">
<h2 style="background-color:blue; color: white; width:150px;">${kat.getName()}</h2>
<c:if test='${kat.getName() == "Bike"}'>
<table>
<c:forEach var="pro" items="${requestScope.Bikes}">
<tr>
<td><label>${pro.getName()}</label></td>
<td><label>${pro.getPrice()}</label> <span>kn</span></td>
<td><label>Amount:</label></td>>
<c:set var="pr" value="proz"></c:set>
<c:set var="prp" value="${pro.getStringID()}"></c:set>
<c:set var="id" value="${pr.concat(prp)}"></c:set>
<td><input type="number" name="${id}"></td>
</tr>
</c:forEach>
</table>
</c:if>
<c:if test='${kat.getName() == "Ball"}'>
<table>
<c:forEach var="pro" items="${requestScope.Balls}">
<tr>
<td><label>${pro.getName()}</label></td>
<td><label>${pro.getPrice()}</label> <span>kn</span></td>
<td><label>Amount:</label></td>>
<c:set var="pr" value="proz"></c:set>
<c:set var="prp" value="${pro.getStringID()}"></c:set>
<c:set var="id" value="${pr.concat(prp)}"></c:set>
<td><input type="number" name="${id}"></td>
</tr>
</c:forEach>
</table>
</c:if>
</c:forEach>
<br>
<input type="submit" value="Choose">
</form>
my servlet code:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession sesija =request.getSession();
try {
r = new Repository();
bouth = r.getBouthProducts();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletContext servletContext = this.getServletConfig().getServletContext();
File rep= (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(rep);
List<FileItem> items = new ServletFileUpload(factory).parseRequest((RequestContext) request);
for (FileItem item : items) {
for (Product pro : r.GetProducts()) {
String s = "proz";
String concat = s.concat(pro.getStringID());
String name = item.getFieldName();
if(name.equals(concat)){
int i = Integer.parseInt(item.getString());
if(i > 0)
{
- doesn't matter
}
}
}
}
} catch (SQLException ex) {
response.sendError(ex.getErrorCode());
} catch (FileUploadException ex) {
Logger.getLogger(HomeServlet.class.getName()).log(Level.SEVERE, null, ex);
}
-- doesn't matter
}

Getting list of strings from servlet to jsp

I have a JSP page in which I have two tags. In first I am trying get input such as Car Maker name such as Tata, Hyundai, Toyota, Audi etc. When user selects any option in first , it should display car models from that maker such as Innova,Land Cruiser etc. So when user selects any option in first tag, I am calling a servlet which gets all the models from database in a list and setting the list as attribute of session and forwarding the request back to JSP. But in jsp when I try to fetch the list it is giving NULL POINTER EXCEPTION. How to solve it?
The code is as below:
DbReviewCar.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn= null;
PreparedStatement pstmt= null;
ResultSet rs;
String sql= null;
String maker= request.getParameter("make");
List modellist= new ArrayList();
/*if(maker==null)
{
modellist.add("ferrari");
modellist.add("hummer");
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
else
{*/
try {
Class.forName("com.mysql.jdbc.Driver");
conn= DriverManager.getConnection("jdbc:mysql://localhost/cardetails", "root", "Welcome123");
sql= "select model from cars where make=?;";
pstmt= conn.prepareStatement(sql);
pstmt.setString(1, maker);
rs= pstmt.executeQuery();
while(rs.next())
{
String mod= rs.getString(1);
modellist.add(mod);
System.out.println(mod+">>>>>>>>>>>>>>>>>>.");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
CarReview.jsp
Here is my JSP file
<form action="DbReviewCar" method="get" name="myform">
<table>
<tr>
<td>
<tr>
<td>Make:</td>
<td><select name="make" onchange="this.form.submit()"><option>select</option>
<option>Maruti</option>
<option>Ford</option>
<option>Honda</option>
<option>Skoda</option>
<option>Tata</option>
<option>Audi</option>
<option>Toyota</option></select><br></br></td>
</tr>
<%
List list = new ArrayList();
list.addAll((List) (request.getSession().getAttribute("value")));
%>
<tr>
<td>Model:</td>
<td><select name="model">
<%
for (int i = 0; i < list.size(); i++) {
%>
<option value=<%=list.get(i)%>><%=list.get(i)%></option>
<%
}
%>
</select><br></br></td>
</tr>
<tr>
<td>Rating For Style:</td>
<td><input type="text" name="style"><br></br></td>
</tr>
<tr>
<td>Rating for comfort:</td>
<td><input type="text" name="comfort"><br></br></td>
</tr>
<tr>
<td>Rating for Performance:</td>
<td><input type="text" name="performance"><br></br></td>
</tr>
<tr>
<td>Rating for FuelEconomy:</td>
<td><input type="text" name="economy"><br></br></td>
</tr>
<tr>
<td>Review:</td>
<td><textarea cols="18" rows="3"></textarea><br></br></td>
</tr>
<tr>
<td><Button>Save</Button></td>
<td><input type="reset" name="cancel" value="Cancel" /></td>
</tr>
</table>
</form>
When jsp loading for the first time the "value" atribute is not set.
Try to check null for value:
request.getSession().getAttribute("value")

How to check validations for the Ajax pop up JSP page in Struts 1.x

I got some issue during validation of Struts 1.x. I'm opening a JSP page on the Ajax call. In this JSP page (opened popup) if I want to put some validation like user title is required etc, and while submitting the form I'm directly submitting the details to the required action class method. While submitting I'm not using Ajax submit. I also tried with Ajax submit but it didn't work for me. The below code is my action class method and the JSP page:
Action class
public ActionForward saveNotificationsFormDetails(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
DynaValidatorActionForm notificationsForm=(DynaValidatorActionForm)form;
log.info("In saveNotificationsFormDetails method of NotificationsManagementAction");
String forwardName="failure";
String filePath = null;
String webPath = null;
FileOutputStream outputStream = null;
ActionMessages messages = new ActionMessages();
User user=null;
try
{
int userId=0;
HttpSession session=request.getSession(false);
if(session!=null)
{
user=(User)session.getAttribute("user");
if(user!=null)
{
if(user.isAdmin()==true)
{
userId=user.getPrimaryKey();
log.info("user is admin");
}
else
{
log.info("User has no rights to access this page ");
return mapping.findForward("userrestricted");
}
}
else
{
return mapping.findForward("login");
}
}
log.info("The user id -"+userId+"-- is is requesting to Notification Details.");
NotificationsDto notificationsDto = new NotificationsDto();
NotificationsDao notificationsDao = NotificationsDao.getInstance();
String title = (String) notificationsForm.get("title");
String content = (String) notificationsForm.get("content");
// uploading the file to notifications directory.
FormFile url =(FormFile)notificationsForm.get("url");
String fileName = url.getFileName();
filePath = getServlet().getServletContext().getRealPath("")+"/notifications/"+ fileName;
if(fileName != null && !fileName.equals("")) {
outputStream = new FileOutputStream(new File(filePath));
outputStream.write(url.getFileData());
// getting the web path for the uploaded file
//String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
webPath =request.getContextPath()+"/notifications/"+url.getFileName();
}
String fromDate = (String) notificationsForm.get("fromDate");
String toDate = (String) notificationsForm.get("toDate");
String notifyUsersFlag = (String) notificationsForm.get("notifyUsersFlag");
boolean notifyUsers = (notifyUsersFlag!=null && notifyUsersFlag.trim().length() > 0 && ( (notifyUsersFlag.trim().equals("on")) || (notifyUsersFlag.trim().equals("true")) ) ) ? true : false;
//code written for sending the mails to user, if user click on notification checkbox
if(notifyUsers){
//NotificationEmailDispatcherJob();
UserDao userDao = new UserDao();
try {
Properties pro = new Properties();
InputStream in = PropertiesFileReader.getInstance().getInputStreamInstance("mail.properties");
pro.load(in);
String basePath = pro.getProperty("basePath");
// Algorithm Steps:
/*
* Step1: Get all the notifications which are still available to show.
* Step2: If notifications size > 0 do the steps(3,4,5) else stop processing.
* Step3: Get all users registered and activated in prep511.
* Step4: Prepare email content to be sent for each user.
* Step5: Validate the email content and send it to user.
*/
// Get all the notifications which are still available to show.
List<NotificationsDto> notifications = NotificationsDao.getInstance().getDisplayNotifications();
if(notifications !=null && notifications.size() > 0){
List<User> activatedUsers = userDao.getAllUsersForAnnoucement();
for (Iterator<NotificationsDto> iterator = notifications.iterator(); iterator
.hasNext();) {
notificationsDto = iterator.next();
Iterator<User> usersIterator = activatedUsers.iterator();
while( usersIterator.hasNext() ) {
user = usersIterator.next();
String emailContent = getEmailContent(user, basePath, notificationsDto);
//verify the emailContent for validness before sendig email.
if(emailContent !=null && emailContent.trim().length()>0 && !emailContent.contains("Due to internal server problems your request could not be completed.") && emailContent.contains("Wayne Jones") ){
// send email
String subject = "Prep511 Announcement: "+notificationsDto.getTitle();
sendAnnouncementEmail(pro, basePath, user, emailContent, subject);
}
else{
// send an email or notification to ven regarding the exception.
// continue for other users.
continue;
}
}
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/*if(title == null || title.equals("")){
ActionMessage message = new ActionMessage("NotificationForm.title.required");
messages.add("NotificationForm.title.required", message);//jsp
saveMessages(request, messages);
return mapping.findForward("NotificationForm.title.required");
} */
content = content.replace("\n", "<br />");
notificationsForm.set("path",filePath);
notificationsDto.setTitle(title);
notificationsDto.setContent(content);
notificationsDto.setFromDate(DateUtils.convertDateFormat(fromDate, "MMM dd, yyyy", "yyyy-MM-dd HH:mm:ss", false) );
notificationsDto.setToDate(DateUtils.convertDateFormat(toDate, "MMM dd, yyyy", "yyyy-MM-dd HH:mm:ss", false) );
notificationsDto.setUrl(webPath);
notificationsDto.setCreatedBy(user);
notificationsDto.setLastModifiedBy(user);
notificationsDto.setNotifyUsersFlag(notifyUsers);
notificationsDto = notificationsDao.insertRecord(notificationsDto);
if (notificationsDto.getNotificationsId() > 0 ) {
//forward to notificationsList.jsp
// reload notifications
ServletContext application = this.getServlet().getServletContext();
new NotificationsLoader().reloadNotifications(application);
return mapping.findForward("success");
} else {
// forward display VendorForm
// Add action message also
//record insertion failed.
ActionMessage message = new ActionMessage("request.process.failed");// resources.properties
messages.add("request.process.failed", message);//jsp
saveMessages(request, messages);
return mapping.findForward(forwardName);
}
}
catch(Exception e)
{
e.printStackTrace();
log.error(e.getMessage());
return mapping.findForward(forwardName);
}
}
jsp page code is and it is a child page ..
<html:form action="processNotifications.do?processName=saveNotificationsFormDetails" styleId="NotificationForm" method="POST" enctype="multipart/form-data">
<%-- <html:form action="/processNotifications" styleId="NotificationForm" method="POST" enctype="multipart/form-data"> --%>
<table width="100%" border="0" cellspacing="6" cellpadding="1" class="tabcont">
<tr>
<td align="right">Title<span style="color:red">*</span></td>
<td>
<html:text property="title" styleClass="registration_form_text1"></html:text>
</td>
</tr>
<tr>
<td align="right">Content<span style="color:red">*</span></td>
<td>
<html:textarea property="content" styleClass="registration_form_textArea"></html:textarea>
</td>
</tr>
<tr>
<td align="right">Url</td>
<td>
<html:file property="url" />
<%--<html:text property="url" styleClass="registration_form_text"></html:text> --%>
</td>
</tr>
<tr>
<td align="right">From Date<span style="color:red">*</span></td>
<td><html:text property="fromDate" styleClass="registration_form_text1" styleId="fromDate" style="autocomplete:off"></html:text>
</td>
</tr>
<tr>
<td align="right">To Date<span style="color:red">*</span></td>
<td>
<html:text property="toDate" styleClass="registration_form_text1" styleId="toDate" style="autocomplete:off"></html:text>
</td>
</tr>
<tr>
<td align="right"> </td>
<td>
<html:checkbox property="notifyUsersFlag" styleId="notifyUsersFlag" ></html:checkbox> Notify All Users.
</td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<tr>
<td></td>
<td colspan="2" align="left">
<%-- <input type="button" value="Save" onclick="submitNotificationForm();"> --%>
<input type="submit" value="Save">
</td>
</tr>
</table>
</html:form>
the required ajax call for calling this page is in parent class and the code for this is ........
function displayNotificationForm(){
var basePath='<%=basePath%>';
j("#notificationFormDetails").html(waitImage);
j('#notificationFormDetails').dialog('open');
j('#notificationFormDetails').dialog('option', 'title', 'Add Home Page Announcement');
j.ajax({
type : "GET",
url : "notifications.do?processName=displayNotificationsFormDetails",
success : function(data) {
j("#notificationFormDetails").html(data);
},
error : function(jqXHR, textStatus) {
alert("error" + textStatus);
j("#notificationFormDetails").dialog('close');
}
});
}

Categories

Resources