Question

In: Computer Science

This is for my Advanced Java Programming class. The book we use is Murach's Java Servlet's...

This is for my Advanced Java Programming class. The book we use is Murach's Java Servlet's and JSP 3rd Edition. I need help modifying some code. I will post the code I was told to open that needs to be modified below.

In this exercise, you'll enhance the Future Value application to store the amount and interest rate in the user's session. That way, the user can experiment with different numbers of years to see the value of his or her investment without having to enter the amount and interest rate each time.

Review the project.

  • Start NetBeans and open the project named ch07_ex3_futureValue that's in the more_ex_starts directory.
  • Open the index.jsp file. Note the JSTL if tags that display the values of the amount and interest attributes if they are available.
  • Open the result.jsp file. Note that a link has been added to take you back to the Calculator page.
  • Run the application, enter some values, click the Calculate button, and click the "Return to Calculator" link. On the Calculator page, all of the text boxes should be empty.

Modify the code

  • Open the FutureValueServlet class.
  • Add code to store the investment amount and interest rate in the user's session. For example, store the investment amount as an attribute named "amount" and the interest rate as an attribute named "interest".
  • Run the application again, enter some values, click the Calculate button, and click the "Return to Calculator" link. On the Calculator page, the Investment Amount and Yearly Interest Rate boxes should contain the values you entered.
  • Navigate to a different website. Then, return to the Future Value application by entering the following URL in your browser's URL box:

http://localhost:8080/ch07_ex3_futureValue (Links to an external site.)Links to an external site.

Since the values are stored in the session, the application should remember them even though you left the Future Value application and went to a different site.

  • Close your browser and restart it. Then, enter the above URL in your browser's URL box again. This time, the application should not remember your values. That's because closing your browser ended your previous session.

Here's the code I was told to open. I think only the FutureValueServlet class needs to be modified. I just need it to meet the requirements above. This is all in Java. Thank you very much.

index.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@include file="header.jsp" %>
<section>
<h1>Future Value Calculator</h1>
<p><i>${message}</i></p>
<form action="calculate" method="post">
<label>Investment Amount:</label>
<c:if test="${investmentAmount != null}">
<input type="text" name="investment"
value="${investmentAmount}"/><br>
</c:if>
<c:if test="${investmentAmount == null}">
<input type="text" name="investment"
value="${calculation.monthlyInvestmentAmount}"/><br>
</c:if>
<label>Yearly Interest Rate:</label>
<c:if test="${interestRate != null}">
<input type="text" name="interest_rate"
value="${interestRate}"/><br>
</c:if>
<c:if test="${interestRate == null}">
<input type="text" name="interest_rate"
value="${calculation.yearlyInterestRate}"/><br>
</c:if>
<label>Number of Years:</label>
<input type="text" name="years"
value="${calculation.years}"/><br>

<label>&nbsp;</label>
<input type="submit" value="Calculate"/><br>
</form>
</section>
<%@include file="footer.jsp" %>

result.jsp

<%@include file="header.jsp" %>
<section>
<h1>Future Value Calculator</h1>

<label>Investment Amount:</label>
<span>${calculation.monthlyInvestmentAmountCurrencyFormat}</span><br />

<label>Yearly Interest Rate:</label>
<span>${calculation.yearlyInterestRate}</span><br />

<label>Number of Years:</label>
<span>${calculation.years}</span><br />

<label>Future Value:</label>
<span>${calculation.futureValueCurrencyFormat}</span><br />
<label>&nbsp;</label>
<br>
<span><a href="index.jsp">Return to Calculator</a></span>
</section>
<%@include file="footer.jsp" %>

FutureValueServlet.java

package murach.fv;

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import murach.business.Calculation;

@WebServlet("/calculate")
public class FutureValueServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

// get parameters from the request
String investmentString = request.getParameter("investment");
String interestRateString = request.getParameter("interest_rate");
String yearsString = request.getParameter("years");

// validate the parameters
String url;
String message;
double investment = 0;
double interestRate = 0;
int years = 0;
try {
investment = Double.parseDouble(investmentString);
interestRate = Double.parseDouble(interestRateString);
years = Integer.parseInt(yearsString);
message = "";
url = "/result.jsp";
}
catch (NumberFormatException e) {
message = "Please enter a valid number in all three text boxes.";
url = "/index.jsp";
}

// store data in Calculation object
Calculation calculation = new Calculation();
calculation.setMonthlyInvestmentAmount(investment);
calculation.setYearlyInterestRate(interestRate);
calculation.setYears(years);
  
request.setAttribute("calculation", calculation);
request.setAttribute("message", message);
  
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);
}
  
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}

Solutions

Expert Solution

There are two options you can try:

1. Clear up the memory of the current session
// store data in Calculation object
Calculation calculation = new Calculation();
calculation.setMonthlyInvestmentAmount(investment);
calculation.setYearlyInterestRate(interestRate);
calculation.setYears(years);
  
request.setAttribute("calculation", calculation);
request.setAttribute("message", message);
  
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);

HttpSession session = request.getSession(false);
if(session != null) {
//This will clear up the memory of the current session
session.invalidate();
}

2. Delete each attribute of the request

// store data in Calculation object
Calculation calculation = new Calculation();
calculation.setMonthlyInvestmentAmount(investment);
calculation.setYearlyInterestRate(interestRate);
calculation.setYears(years);
  
request.setAttribute("calculation", calculation);
request.setAttribute("message", message);
  
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);

HttpSession session = request.getSession(false);
if(session != null) {
//This will clear up the memory of the current session
session.removeAttribute("calculation");
  session.removeAttribute("message");

}


Related Solutions

For My Programming Lab - Java: Write a Temperature class that will hold a temperature in...
For My Programming Lab - Java: Write a Temperature class that will hold a temperature in Fahrenheit and provide methods to get the temperature in Fahrenheit, Celsius, and Kelvin. The class should have the following field: • ftemp: a double that holds a Fahrenheit temperature. The class should have the following methods : • Constructor : The constructor accepts a Fahrenheit temperature (as a double ) and stores it in the ftemp field. • setFahrenheit: The set Fahrenheit method accepts...
JAVA Programming ECLIPSE IDE 1. Create an abstract class called Book. The class should declare the...
JAVA Programming ECLIPSE IDE 1. Create an abstract class called Book. The class should declare the following variables: an instance variable that describes the title - String an instance variable that describes the ISBN - String an instance variable that describes the publisher - String an instance variable that describes the price - double an instance variable that describes the year – integer Provide a toString() method that returns the information stored in the above variables. Create the getter and...
JAVA Programming ECLIPSE IDE 1. Create an abstract class called Book. The class should declare the...
JAVA Programming ECLIPSE IDE 1. Create an abstract class called Book. The class should declare the following variables: an instance variable that describes the title - String an instance variable that describes the ISBN - String an instance variable that describes the publisher - String an instance variable that describes the price - double an instance variable that describes the year – integer Provide a toString() method that returns the information stored in the above variables. Create the getter and...
JAVA PROGRAMMING Implement a class Purse. A purse contains a collection of coins. For simplicity, we...
JAVA PROGRAMMING Implement a class Purse. A purse contains a collection of coins. For simplicity, we will only store the coin names in an ArrayList<String>. Supply a method void addCoin(String coinName). Add a method toString to the Purse class that prints the coins in the purse in the format Purse[Quarter,Dime,Nickel,Dime]. Write a method reverse that reverses the sequence of coins in a purse. Implement a TestPurse class with a main method in it. It will use the toString method to...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class,...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class, you are to have the following data members: name: String (5 pts) id: String   (5 pts) hours: int   (5 pts) rate: double (5 pts) private members (5 pts) You are to create no-arg and parameterized constructors and the appropriate setters(accessors) and getters (mutators). (20 pts) The class definition should also handle the following exceptions: An employee name should not be empty, otherwise an exception...
Put In Java Programming The TicketMachine class: Design a class named TicketMachine that contains: • A...
Put In Java Programming The TicketMachine class: Design a class named TicketMachine that contains: • A double data field named price (for the price of a ticket from this machine). • A double data field named balance (for the amount of money entered by a customer). • A double data field named total (for total amount of money collected by the machine). • A constructor that creates a TicketMachine with all the three fields initialized to some values. • A...
PUT IN JAVA PROGRAMMING The Stock class: Design a class named Stock that contains: • A...
PUT IN JAVA PROGRAMMING The Stock class: Design a class named Stock that contains: • A string data field named symbol1 for the stock’s symbol. • A string data field named name for the stock’s name. • A double data field named previousClosingPrice that stores the stock price for the previous day. • A double data field named currentPrice that stores the stock price for the current time. • A constructor that creates a stock with the specified symbol and...
PUT IN JAVA PROGRAMMING The StockB class: Design a class named StockB that contains the following...
PUT IN JAVA PROGRAMMING The StockB class: Design a class named StockB that contains the following properties: • Name of company • Number of shares owned • Value of each share • Total value of all shares and the following operations: • Acquire stock in a company • Buy more shares of the same stock • Sell stock • Update the per-share value of a stock • Display information about the holdings • The StockB class should have the proper...
PUT IN JAVA PROGRAMMING The Rectangle class: Design a class named Rectangle to represent a rectangle....
PUT IN JAVA PROGRAMMING The Rectangle class: Design a class named Rectangle to represent a rectangle. The class contains: • Two double data fields named width and height that specify the width and height of a rectangle. The default values are 1 for both width and height. • A no-arg (default) constructor that creates a default rectangle. • A constructor that creates a rectangle with the specified width and height. • A method named findArea() that finds the area of...
this is for my advanced corporate finance class.. please give a broad and clear explanation on...
this is for my advanced corporate finance class.. please give a broad and clear explanation on this question. Describe the clientele effectin demand for dividend paying stocks. What sort of investors should wish to hold dividend paying stocks and which should not? Why? Describe Modigliani & Miller's irrelevance Propositionon dividend policy. Provide a plausible argument to explain why this proposition should hold. Explain the possible advantages and disadvantages of paying out funds through dividends or share repurchase. Describe the evolution...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT