How to update value on click in servlets? [duplicate] - java

This question already has answers here:
How can I share a variable or object between two or more Servlets?
(6 answers)
Closed 2 years ago.
I just want with each button click to add price value. This is my jsp:
<body>
<h1>Welcome ${user.name}</h1>
<c:forEach var="artical" items="${articals}">
<ul>
<li>${artical.name} </li>
<li>${artical.price}</li>
<li>${priceSum}</li> // i want to show value here just to test it.
</ul>
<form action="addtocart" method="POST">
<input type="hidden" name="names" value="${artical.name}"/>
<input type="hidden" name="price" value="${artical.price}"/>
<button type="submit" name="button">Add to cart</button>
</form>
</c:forEach>
And this is my servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
String name = request.getParameter("names");
double price = Double.parseDouble(request.getParameter("price"));
double priceSum = 0;
priceSum += price;
session.setAttribute("names", name);
session.setAttribute("price", price);
session.setAttribute("priceSum", priceSum);
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}
Now when i put priceSum outside doPost method as an attribute, it works, but i heard it shouldn't be solved like that. So how can i solve this properly and why is bad to put variable outside methods in servlets? Thanks!

I solve problem like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
String name = request.getParameter("names");
double price = Double.parseDouble(request.getParameter("price"));
Double priceSum = (Double) session.getAttribute("priceSum");
if (priceSum == null) {
priceSum = 0.0;
}
priceSum+=price;
session.setAttribute("names", name);
session.setAttribute("price", price);
session.setAttribute("priceSum", priceSum);
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}
Is this proper way to do it?

Related

How to create new object on each button click in Java ee?

I'm practising Java ee and I made a two input fields and button in jsp. When clicked on button "add" I want to add those two fields in a list and just show them on my jsp page. For now it's showing me only one result each time I click on button. What am I doing wrong?
This is my jsp:
<body>
<form action="addtocart" method="GET">
Title: <input type="text" name="title"> <br>
Price: <input type="text" name="price"> <br>
<button type="subtmit">Add</button>
</form>
<c:forEach var="bookList" items="${book}">
<ul>
<li>${bookList.name}</li>
<li>${bookList.price}</li>
</ul>
</c:forEach>
</body>
And this is my servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
String title = request.getParameter("title");
double price = Double.parseDouble(request.getParameter("price"));
ArrayList<Book> list = new ArrayList<>();
list.add(new Book(title,price));
session.setAttribute("book", list);
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}
Problem
You are creating a new ArrayList<Book> on every call of doGet and setting the same into the session. Thus, on every call of doGet the list is getting reset.
Solution
Get the existing list from the session and add a book to it. Create a new list only when it is not present in the session.
#WebServlet("/addtocart")
public class BooklistServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
String title = request.getParameter("title");
double price = Double.parseDouble(request.getParameter("price"));
ArrayList<Book> list = (ArrayList<Book>) session.getAttribute("book");
if (list == null) {
list = new ArrayList<Book>();
}
list.add(new Book(title, price));
session.setAttribute("book", list);
RequestDispatcher view = request.getRequestDispatcher("home.jsp");
view.forward(request, response);
}
}
Additionally, I recommend you display the list only when it is not empty as shown below:
<body>
<form action="addtocart" method="GET">
Title: <input type="text" name="title"> <br> Price: <input
type="text" name="price"> <br>
<button type="submit">Add</button>
</form>
<c:forEach var="bookList" items="${book}">
<c:if test="${not empty book}">
<ul>
<li>${bookList.title}</li>
<li>${bookList.price}</li>
</ul>
</c:if>
</c:forEach>
</body>
As you can see, I've added the check <c:if test="${not empty book}"> as a condition for the visibility of the list.
Every time the statement session.setAttribute("book", list); runs, it replaces the previous list in the session with the new one.
You should first try to fetch the existing list and then add your current book object to it.
ArrayList<Book> list =(ArrayList<Book>)session.getAttribute("book"); // get the current list from the session
list.add(new Book(...));
session.setAttribute("book", list); // store list in session
This should give you the output you are asking for.. Make sure you handle the NullPointerException that may be thrown when you add the element in the list.

ModelAndView not working properly [duplicate]

This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 6 years ago.
I have written the code in java. All the things are working properly. I just want to return the value of modelandview that is not returning correct web page. It is throwing blank page. The code of my controller is:
public class Part3 extends HttpServlet {
Num num = new Num();
String name[];
Record record = null;
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ModelAndView mv = new ModelAndView();
String number = request.getParameter("number");
num.setNumber((number));
Driver driver = GraphDatabase.driver("bolt://localhost", AuthTokens.basic("neo4j", "neo4j"));
Session session = driver.session();
StatementResult result = session.run("MATCH (tom {name: '" + number + "'}) RETURN tom.name, tom.born, tom.roles;");
while (result.hasNext()) {
record = result.next();
}
session.close();
driver.close();
request.setAttribute("selectObject", record);
mv.setViewName("index");
return mv;
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
try {
handleRequest(request, response);
} catch (IOException ex) {
Logger.getLogger(Part3.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
My HTML page is index.html and its code is:
<form action ="number" name ="number">
<b>Enter Song ID:</b>
<input type="text" name='number' required placeholder="Enter SongID"><br /><br /><br />
<input type="submit" value="Submit" class="btn btn-primary" style="background-color: orangered"/>
</form>
${selectObject}
</div>
ModelAndView is a spring mvc object. You cannot use it in a servlet.
Your servlet is doing nothing, in a servlet you need to write to the object HttpServletResponse.
What do you try to do with this code handleRequest(request, response); ?
update :
First, In your object reponse, you can get a PrintWriter : response.getWriter(). Write response in this writer.
Second, delete ModelAndView, you don't need it. Try to understand what is a servlet before using Spring MVC.
Here is a simple example : http://www.tutorialspoint.com/servlets/servlets-first-example.htm

Unable to include servlet response by using requestDispathser

Index.jsp
<form method="post" action="serv">
Enter Latest Reading <input type="text" name="t1"> <br>
Enter Previous Reading <input type="text" name="t2"> <br>
<input type="submit" value="SEND">
</form>
LoginServlet.java
#WebServlet("/serv")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("<u>Following are your Bill Particulars</u><br><br>");
req.setAttribute("unitRate", new Double(8.75));
req.getRequestDispatcher("/Test").include(req, res);
out.println("<br><br>Please pay the bill amount before 5th of every month to avoid penalty and disconnection");
out.close();
}
}
IncludeServlet.java
#WebServlet("/Test")
public class IncludeServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter out = res.getWriter();
int latestReading = Integer.parseInt(req.getParameter("t1"));
int previousReading = Integer.parseInt(req.getParameter("t2"));
Object obj = req.getAttribute("unitRate");
Double d1 = (Double) obj;
double rate = d1.doubleValue();
int noOfUnits = latestReading-previousReading;
double amountPayable = noOfUnits * rate;
out.println("Previous reading: " + previousReading); out.println("<br>Current reading: " + latestReading);
out.println("<br>Bill Amount Rs." + amountPayable);
}
}
When I run the above project, only the response of LoginServlet is displayed in a browser, I'm unable to include the response of IncludeServlet.java.
All System.out.println("") of LoginServlet is being display is console only, non from IncludeServlet.
I also use debugger, but this is not going into IncludeServlet.java page.
In your IncludeServlet instead of overriding doGet method override doPost , Since Post request is coming from HTML
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// do Whatever you want to do .
}
Update: Also write res.setContentType("text/html"); in both servlet so that your html written in out.print executes otherwise your output will look like <br><br>Please pay the bill amount before 5th of every month to avoid penalty and disconnection.

Print checked values in JSP page

I am trying to print checked values of checkbox list from a JSP page but nothing appears even if some selections are there.
<form action="process" method="POST">
<c:forEach var="item" items="${list.items}">
<input type="checkbox" name="chkSkills" value="${$item.Id}">${item.name}
</c:forEach>
<input type="submit" name="Getvalue" value="Get value" />
</form>
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String[] Answers = request.getParameterValues("chkSkills");
PrintWriter out = response.getWriter();
String ButClicked = request.getParameter("Getvalue");
if (ButClicked != null) {
for (String Answer : Answers) {
out.print(Answer + "<br>");
}
}
//processRequest(request, response);
}
Correct your value attribute to
value="${item.Id}"
Notice, there's no need to put a $ inside the {} again.

Compare session value whether it matches with the textbox value [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi I could get my session values in my jsp, now I want to compare the session value whether it matches the textbox, if it matches, it will redirect the user to another page else it will remain the same page, I am not sure how to proceed, please help . Much thanks!
JSP
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Factorial</title>
</head>
<body>
<form action="fact" method="POST">
Enter a number: <input type="text" name="num">
<input type="submit"/>
<%= session.getAttribute( "money" ) %>,
</form>
</body>
</html>
Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
String text = request.getParameter("money");
int money = (Integer)session.getAttribute("money");
String testing = String.valueOf(money);
if(text == testing)
{
RequestDispatcher rd = request.getRequestDispatcher("MainPage");
rd.forward(request, response);
}
else
{
response.redirect("Errorpage.jsp");
}
Assuming that you have already got a Session attribute called "money", you would not need to access it from JSP
<body>
<form action="fact" method="POST">
Enter a number: <input type="text" name="num">
<input type="submit"/>
</form>
</body>
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String text = request.getParameter("num");
int money = (Integer)session.getAttribute("money");
String testing = String.valueOf(money);
if(testing.equalsIgnoreCase(text))
{
RequestDispatcher rd = request.getRequestDispatcher("MainPage");
rd.forward(request, response);
}
else
{
response.sendRedirect("Errorpage.jsp");
}
}
If you have not created a Session attribute called "money" yet and want to create it in jsp, you have to use Scriptlet.
<body>
<form action="abc.do" method="POST">
Enter a number: <input type="text" name="num">
<input type="submit"/>
<% session.setAttribute("money",1000); %>,
</form>
</body>

Categories