Cannot pass data from mysql using servlet to jsp/html table - java

I'm trying to create Java web application using tomcat 8 server in eclipse.
I've created servlet which forwards request to jsp page and initialize table inside this page with data from two tables. I've been following several examples on the internet on how to fill html table with recoreds from MySQL DB but failed. I'm using MainServlet's doGet method to get data from my local database into list and set it as attribute in request. But when i'm launching servlet there are no records in jsp table. Servlet connects to db and recieves records from it (i've already debugged app). So what is wrong with my code? I'm new to html and css,servlet and jsp technology. Maybe problem is with css framework i'm using (Materialize CSS).
Here is my MainServlet.java code:
package redirect;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
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 java.sql.Connection;
import util.Book;
#WebServlet(name="Libbook",urlPatterns={"/libbook"})
public class MainServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static String url = "jdbc:mysql://localhost:3306/Test";
private static String user = "user",password = "password";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
List<Book> books = new ArrayList<>();
Connection connection = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url,user,password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(
"SELECT IDBook,Title,AddDate,ISBN,Name,Sirname "
+ "FROM Book INNER JOIN Author "
+ "ON Book.IDAuthor = Author.IDAuthor;");
while (resultSet.next())
{
Book b = new Book();
b.setId(resultSet.getInt(1));
b.setTitle(resultSet.getString(2));
b.setIsbn(resultSet.getLong(4));
b.setDate(resultSet.getDate(3).toString());
b.setName(resultSet.getString(5));
b.setSirname(resultSet.getString(6));
books.add(b);
}
}
catch (SQLException | ClassNotFoundException e)
{
e.printStackTrace();
}
finally {
try {if(connection != null)connection.close();}catch (SQLException e) {e.printStackTrace();}
}
request.setAttribute("books", books);
request.getRequestDispatcher("pages/libbook.jsp").forward(request, response);
}
}
libbook.jsp page:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8"/>
<title>LibBook</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<style type="text/css">
.logo{
color: #444;
text-transform: uppercase;
letter-spacing: 0.3em;
font-size: 2em;
}
.logo img{
width: 5%;
margin: 0.5%;
vertical-align: middle;
margin-right: 0.5em;
}
</style>
</head>
<body>
<nav class="white">
<div class="navbar-wrapper container">
<a id="logo-container" href="#" class="logo">
LIBBOOK
<img src="assets/book.svg" alt="LibBooklogo">
</a>
<ul class="right">
<li><a class="waves-effect waves-light btn" href="pages/new_author.jsp"><i class="material-icons left">perm_identity</i>NEW AUTHOR</a></li>
<li><a class="waves-effect waves-light btn" href="pages/new_book.jsp"><i class="material-icons left">class</i>NEW BOOK</a></li>
</ul>
</div>
</nav>
<div class="container">
<div class="row">
<div class="card-panel">
<form action="test">
<div class="input-field">
<input placeholder="Type here (title,author) and press enter.." id="search_bar" type="text">
<label for="search_bar">Search</label>
</div>
</form>
</div>
</div>
<div class="row">
<div class="card-panel">
<table>
<thead>
<tr>
<th>ISBN</th>
<th>Title</th>
<th>Author</th>
<th>Info/Edit</th>
<th>Remove</th>
</tr>
</thead>
<c:forEach var="book" items="${books}">
<tr>
<td><c:out value="${book.isbn}"/></td>
<td><c:out value="${book.title}"/></td>
<td><c:out value="${book.name}"/></td>
<td>
<i class="material-icons">mode_edit</i>
</td>
<td>
<i class="material-icons">delete</i>
</td>
</tr>
</c:forEach>
</table>
</div>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
</body>
</html>
Book class:
package util;
import java.io.Serializable;
public class Book implements Serializable
{
private Integer id;
private String title;
private String date;
private Long isbn;
private String name;
private String sirname;
public Book(){
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Long getIsbn() {
return isbn;
}
public void setIsbn(Long isbn) {
this.isbn = isbn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSirname() {
return sirname;
}
public void setSirname(String sirname) {
this.sirname = sirname;
}
}

Found solution. Problem was in jsp file, i did not include imports related to c tag scriplet:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%# taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
And didn't add jstl-1.2.jar library to my project

Java looks for a getter method in a bean class to read the data.
As you bean class(Book) getter method names are like getISBN(), getTitle() , getAName() etc. You should use code in jsp like
<td><c:out value="${book.iSBN}"/></td>
<td><c:out value="${book.title}"/></td>
<td><c:out value="${book.aName}"/></td>

Related

Getting form data in a jsp and retrieve that data from servlet with of mvc from sql database and show the result table in another jsp?

Well as I described I have a MVC model implementation using glassfish and NetBeans support. I am fairly new into this area of learning and finding it difficult to understand how to implement a search bar in the web app and retrieve that data using the servlet and model and daos . The coding is as follow:
JSP file where search textbox is placed :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Doctor Dashboard</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://kit.fontawesome.com/0afbc9b86d.js" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/styles.css" />
</head>
<body id="body">
<div class="container">
<nav class="navbar">
<div class="nav_icon" onclick="toggleSidebar()">
<i class="fa fa-bars" aria-hidden="true"></i>
</div>
<div class="navbar__left">
<a class="active_link" href="#">Profile</a>
</div>
<div class="navbar__right">
<a href="#">
<i class="fa fa-search" aria-hidden="true"></i>
</a>
<a href="#">
<i class="fa fa-clock-o" aria-hidden="true"></i>
</a>
<a href="#">
<img width="30" src="assets/avatar.svg" alt="" />
<!-- <i class="fa fa-user-circle-o" aria-hidden="true"></i> -->
</a>
</div>
</nav>
<main>
<div class="main__container">
<form method="POST" action="<%=request.getContextPath()%>/Dreport/patientrecordinfo" style="align-items:center">
<div style="align-items: center;">
<h1>Patient Records</h1>
<p style="margin-top: 2rem; align-items: center">Enter the Patient ID:</p>
//Place where the data to be retrieved from
<input style=" width:20%; height:40px; display: inline-block; background:whitesmoke;"type="text" placeholder="Patient ID..." name="patientid" required><br>
<input style="margin-top:2rem;" required type="checkbox" name="confirm" style="margin-bottom:15px"> Agree to Protect Customer privacy
<br>
<div class="clearfix">
<button style="background-color:blueviolet; color: white; padding: 14px 20px; margin: 8px 0; border: none; cursor: pointer;width: 30%;
opacity: 0.9;" type="submit" class="signupbtn">Search</button>
</div>
</div>
</form>
</main>
<div id="sidebar">
<div class="sidebar__title">
<div class="sidebar__img">
<img src="${pageContext.request.contextPath}/imgs/Doctor.png" style="border-radius: 50%;" alt="logo" />
<h1> Welcome Doctor,<br>
Nimesh Kottawatta
</h1>
</div>
<i
onclick="closeSidebar()"
class="fa fa-times"
id="sidebarIcon"
aria-hidden="true"
></i>
</div>
<!--SIDE_BAR-->
<div class="sidebar__menu">
<div class="sidebar__link ">
<i class="fas fa-tachometer-alt"></i>
Dashboard
</div>
<div class="sidebar__link active_menu_link">
<i class="fa fa-line-chart"></i>
Check Report
</div>
<div class="sidebar__link">
<i class="fa fa-list-alt"></i>
Update Report
</div>
<div class="sidebar__logout">
<i class="fa fa-power-off"></i>
Log out
</div>
</div>
</div>
</div>
<script src="js/script.js"></script>
</body>
</html>
And the Servlet :
package com.primavera.controllers;
import com.primavera.Managers.StaffManager;
import com.primavera.entities.Patient;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
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;
#WebServlet(name = "Dreport", urlPatterns = {"/Dreport","/Dreport/Dashboard","/Dreport/reportupdate","/Dreport/patientrecordinfo"})
public class Dreport extends HttpServlet {
//Default constructor
public Dreport(){}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher=null;
// 1. Get data from the Model
if (request.getServletPath().contains("/Dashboard")) {
dispatcher= request.getRequestDispatcher("/DoctorDashboard.jsp");
} else if (request.getServletPath().contains("/reportupdate")){
dispatcher= request.getRequestDispatcher("/DUpdateReport.jsp");
}else if (request.getServletPath().contains("/patientrecordinfo")){
//1.Get data info from model
int user_Id=Integer.parseInt(request.getParameter("patientid"));//Taking doctor inserting id
List<Patient> list = new ArrayList<Patient>();//Creating a list to hold data
list=StaffManager.getInstance().getPatientInfo(user_Id);//MVC method implementation for Searching patient
request.setAttribute("list", list);
//view
RequestDispatcher rd= request.getRequestDispatcher("records.jsp");
rd.forward(request, response);
}
else {
dispatcher= request.getRequestDispatcher("/DReport.jsp");
}
// 2. Forwarding to View
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
The model: Manager class :
package com.primavera.Managers;
import com.primavera.daos.PatientDao;
import com.primavera.entities.Doctor;
import com.primavera.entities.Nurse;
import com.primavera.entities.Patient;
import java.util.ArrayList;
import java.util.Date;
import java.sql.ResultSet;
import java.util.List;
import java.util.List;
import java.util.ArrayList;
import java.util.List;
public class StaffManager {
//Creating a singletance instance
private static StaffManager instance = new StaffManager();
private static PatientDao dao= new PatientDao();
private StaffManager() {
}
public static StaffManager getInstance() {
return instance;
}
//Method implementations
public List <Patient> getPatientInfo(int user_Id) {
return dao.getPatient(user_Id);
}
}
And the Dao is :
package com.primavera.daos;
import com.primavera.entities.Patient;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class PatientDao {
DatabaseConnection db= new DatabaseConnection();
Patient patient = new Patient();
//Method implemetation for getting Patient records by Doctor
public List <Patient> getPatient(int user_Id) {
List <Patient> list = new ArrayList<Patient>();
ResultSet rs=null;
try{
PreparedStatement pst =db.conn().prepareStatement("SELECT * FROM patient WHERE user_id = ?"); // ? = placeholder
pst.setInt(1, user_Id); // Bind the value to the placeholder
rs = pst.executeQuery();
while(rs.next()){
patient.setName(rs.getString("user_name"));
patient.setGender(rs.getString("user_gender"));
list.add(patient);
}
}
catch(SQLException e){
e.printStackTrace();
}
return list;
}
}
And the another jsp for now i would the data to be visible in :
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Patient Report</title>
</head>
<body>
<c:if test="${list!=null}">
<table>
<c:forEach items="${list}" var="record">
<tr>
<td>${record.patient_Id}</td>
<td>${record.name }</td>
<td>${record.gender }</td>
<td>${record.DOB }</td>
<td>${record.phone }</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
Thank you so much in advance for that supports me to solve it .
Well I discovered my errors there were few first I had tried to retrieve data from the doGet method in servlet and not the doPost which was a huge error since the method that form uses to send data is POST, some basic correction were as below :
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getServletPath().contains("patientrecordinfo")) {
// Calling doPost to retrieve form data
int user_Id=Integer.parseInt(request.getParameter("patientid"));//Taking doctor inserting id
List list = new ArrayList<>();//Creating a list to hold data
list = StaffManager.getInstance().getPatientInfo(user_Id);//MVC method implementation for Searching patient
request.setAttribute("list", list);
request.getRequestDispatcher("/records.jsp").forward(request, response);
}
}
And class implementations were :
Manager class method :
public List getPatientInfo(int user_Id) {
return dao.getPatient(user_Id);
}
And DAO:
public List getPatient(int user_Id) {
List list = new ArrayList();
ResultSet rs = null;
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hms", "root", "");
PreparedStatement pst = conn.prepareStatement("SELECT * FROM patient WHERE user_id = ?"); // ? = placeholder
pst.setInt(1, user_Id); // Bind the value to the placeholder
rs = pst.executeQuery();
if (rs != null) {
while (rs.next()) {
Patient patient = new Patient();
patient.setPatient_Id(rs.getString("user_id"));
patient.setName(rs.getString("user_name"));
patient.setGender(rs.getString("user_gender"));
patient.setDOB(rs.getDate("user_DOB"));
patient.setPhone(rs.getInt("phone"));
patient.setSickness(rs.getString("user_sickeness"));
patient.setAllegeries(rs.getString("user_allergies"));
patient.setSymptoms(rs.getString("user_specail_request"));
patient.setAddress(rs.getString("user_address"));
list.add(patient);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
Hope someone would benefit as myself I'm a beginner to java MVC might not be the most elegant way , would love for anyone ideas to improve as well.

I'm trying to build a E-commerce website using Spring. I have added the cart functionality. But when I click on order button the cart is not updated

CartItemController
package com.emusicstore.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
#Controller
#RequestMapping("/cart")
public class CartItemController {
#RequestMapping
public String get(HttpServletRequest request)
{
return "redirect:/cart/"+request.getSession(true).getId(); //Session id is used as cart Id
}
#RequestMapping(value="/{cartId}",method= RequestMethod.GET)
public String getCart(#PathVariable(value="cartId") String cartId, Model model)
{
model.addAttribute("cartId",cartId);
return "cart";
}
}
CartController.java
package com.emusicstore.controller;
import com.emusicstore.dao.CartDao;
import com.emusicstore.dao.ProductDao;
import com.emusicstore.model.Cart;
import com.emusicstore.model.CartItem;
import com.emusicstore.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
#Controller
#RequestMapping("/rest/cart")
//Rest services we need to start,starts with rest in path
public class CartController {
#Autowired
private CartDao cartDao;
#Autowired
private ProductDao productDao;
#RequestMapping(value="/{cartId}",method= RequestMethod.GET)
public #ResponseBody Cart read(#PathVariable(value ="cartId") String cartId)
{
return cartDao.read(cartId);
}
//#Response Body returns a model object in JSON Format
//Cart object which is returned is put into #ResponseBody and because of jackson deendendency The sping converts the object
//to JSON format and puts in #ResponseBody
//Reverse Process
#RequestMapping(value="/{cartId}",method=RequestMethod.PUT)
#ResponseStatus(value= HttpStatus.NO_CONTENT)
public void update(#PathVariable(value="cartId") String cartId, #RequestBody Cart cart)
{
cartDao.update(cartId,cart);
}
//Read something-GET
//Post something in UrL=POST
//Update info-PUT
#RequestMapping(value="/{cartId}",method=RequestMethod.DELETE)
#ResponseStatus(value=HttpStatus.NO_CONTENT)
public void delete(#PathVariable(value="cartId")String cartId)
{
cartDao.delete(cartId);
}
#RequestMapping(value="/add/{productId}",method=RequestMethod.PUT)
#ResponseStatus(value=HttpStatus.NO_CONTENT)
public void addItem(#PathVariable(value="productId")String productId, HttpServletRequest request)
{
String sessionId=request.getSession(true).getId();
Cart cart=cartDao.read(sessionId);
if(cart==null)
{
cart=cartDao.create(new Cart(sessionId));
}
Product product=productDao.getProductById(productId);
if(product==null)
{
throw new IllegalArgumentException(new Exception());
}
cart.addCartItem(new CartItem(product));
cartDao.update(sessionId,cart);
}
#RequestMapping(value="/remove/{productId}",method = RequestMethod.PUT)
#ResponseStatus(value=HttpStatus.NO_CONTENT)
public void removeItem(#PathVariable String productId, HttpServletRequest request)
{
String sessionId=request.getSession(true).getId();
Cart cart=cartDao.read(sessionId);
if(cart==null)
{
cart=cartDao.create(new Cart(sessionId));
}
Product product=productDao.getProductById(productId);
if(product==null)
{
throw new IllegalArgumentException(new Exception());
}
cart.removeCartItem(new CartItem(product));
cartDao.update(sessionId,cart);
}
#ExceptionHandler(IllegalArgumentException.class)
#ResponseStatus(value= HttpStatus.BAD_REQUEST,reason="Illegal request, Please your verify your payload")
public void handleClientErrors(Exception e)
{
}
#ExceptionHandler(Exception.class)
#ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR,reason="Internal Server Error")
public void handleServerErrors(Exception e)
{
}
}
CartDaoImpl.java
package com.emusicstore.dao.impl;
import com.emusicstore.dao.CartDao;
import com.emusicstore.model.Cart;
import org.springframework.stereotype.Repository;
import java.util.HashMap;
import java.util.Map;
#Repository
public class CartDaoImpl implements CartDao {
private Map<String, Cart> listOfCarts;
public CartDaoImpl()
{
listOfCarts=new HashMap<String, Cart>();
}
#Override
public Cart create(Cart cart) {
if(listOfCarts.keySet().contains(cart.getCartId())){
throw new IllegalArgumentException(String.format("Cannot create a cart. A cart " +
"with given id(%)"+"already"+"exists",cart.getCartId()));
}
listOfCarts.put(cart.getCartId(),cart);
return cart;
}
#Override
public Cart read(String cartId) {
return listOfCarts.get(cartId);
}
#Override
public void update(String cartId, Cart cart) {
if(!listOfCarts.keySet().contains(cartId))
{
throw new IllegalArgumentException(String.format("Cannot update cart. The cart with the given id(%)" +
"does not"+"exists.",cart.getCartId()));
}
listOfCarts.put(cartId,cart);
}
#Override
public void delete(String cartId) {
if(!listOfCarts.keySet().contains(cartId))
{
throw new IllegalArgumentException(String.format("Cannot delete cart. A cart with the given id(%)"
+"does not exists",cartId));
}
listOfCarts.remove(cartId);
}
}
viewProduct.jsp
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#include file="/WEB-INF/views/template/header.jsp" %>
<div class="container-wrapper">
<div class="container">
<div class="page-header">
<h1>Product Detail</h1>
<p class="lead">Here is the detailed information of the products</p>
</div>
<div class="container-fluid" ng-app="cartApp">
<div class="row">
<div class="col-md-5">
<img src="<c:url value="/resources/images/${product.productId}.png"/>" alt="image" style="width:100%"/>
<!-- ;height:300px-->
</div>
<div class="col-md-5">
<h3>${product.productName}</h3>
<p>${product.productDescription}</p>
<p>
<strong>Manufacturer</strong>:${product.productManufacturer}
</p>
<p>
<strong>Category</strong>:${product.productCategory}
</p>
<p>
<strong>Condition</strong>:${product.productCondition}
</p>
<p>
<h4>${product.productPrice} USD</h4>
</p>
<br/>
<c:set var="role" scope="page" value="${param.role}"/>
<c:set var="url" scope="page" value="/productList"/>
<c:if test="${role='admin'}">
<c:set var="url" scope="page" value="/admin/productInventory"/>
</c:if>
<p ng-controller="cartCtrl">
Back
<a href="#" class="btn btn-warning btn-large"
ng-click="addToCart('${product.productId}')"><span class="glyphicon glyphicon-shopping-cart"></span>Order Now</a>
<span class="glyphicon glyphicon-hand-right"></span>View Cart
</p>
</div>
</div>
</div>
</div>
</div>
<script scr="<c:url value="/resources/js/controller.js"/>"></script>
<%#include file="/WEB-INF/views/template/footer.jsp" %>
cart.jsp
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#include file="/WEB-INF/views/template/header.jsp" %>
<div class="container-wrapper">
<div class="container">
<section>
<div class="jumbotron">
<div class="container">
<h1>Cart</h1>
<p>All the selected products in your shopping cart</p>
</div>
</div>
</section>
<section class="container" ng-app="cartApp">
<div ng-controller="cartCtrl" ng-init="initCartId('${cartId}')">
<div>
<a class="bnt btn-danger pull-left" ng-click="clearCart()"><span class="glyphicon glyphicon-remove-sign"></span>Clear Cart</a>
</div>
<table class="table table-hover">
<tr>
<th>Product</th>
<th>Unit Price</th>
<th>Quantity</th>
<th>Price</th>
<th>Action</th>
</tr>
<tr ng-repeat="item in cart.cartItems">
<td>{{item.product.ProductName}}</td>
<td>{{item.product.ProductPrice}}</td>
<td>{{item.quantity}}</td>
<td>{{item.totalPrice}}</td>
<td><a href="#" class="label label-danger" ng-click="removeFromCart(item.product.productId)">
<span class="glyphicon glyphicon-remove"></span>remove</a></td>
</tr>
<tr>
<th></th>
<th></th>
<th>Grand Total</th>
<th>grandTotal</th>
</tr>
</table>
Continue Shopping
</div>
</section>
</div>
</div>
<script src="<c:url value="/resources/js/controller.js"/>"></script>
<%#include file="/WEB-INF/views/template/footer.jsp" %>
controller.js
var cartApp=angular.module("cartApp",[]);
cartApp.controller("cartCtrl",function($scope,$http){
$scope.refreshCart=function(cartId){
$http.get('/eMusicStore_war_exploded/rest/cart/'+$scope.cartId).success(function (data){
$scope.cart=data;
});
};
$scope.clearCart=function(){
$http.delete('/eMusicStore_war_exploded/rest/cart/'+$scope.cartId).success($scope.refreshCart($scope.cartId));
};
$scope.initCartId=function(cartId){
$scope.cartId=cartId;
$scope.refreshCart(cartId);
};
$scope.addToCart=function(productId)
{
$http.put('/eMusicStore_war_exploded/rest/cart/add/'+productId).success(function (data){
$scope.refreshCart($http.get('/eMusicStore_war_exploded/rest/cart/cartId'));
alert('Product successfully added to cart!')
});
};
$scope.removeFromCart=function(productId){
$http.put('/eMusicStore_war_exploded/rest/cart/remove/'+productId).success(function(data){
$scope.refreshCart($http.get('eMusicStore_war_exploded/rest/cart/cartId'));
});
};
});
When I try to execute it, I'm getting the product page but after presssing the order now button the url changes to http://localhost:8004/eMusicStore_war_exploded/productList/viewProduct/1#
where 1 is productId but after that there isn't any popup stating that order has been placed and when I view the cart I'm getting only the varibale name which I used in jsp script and not the value. When I tried to debug I found that the ng-click from viewProduct.jsp is not performing any action. Please help me fix this...

Successful login with Custom login page in spring boot starter security not getting to next page

I have been studying spring boot. When using spring-boot-starter-security for a todo application,I tried to login with custom user id and password and custom login page.When I tried login , it is not taking me to next page. Note : user name is required parameter for next page.
I tried using below but after login it again takes me to login page as error
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers("/", "/*Todo*/**").access("hasRole('USER')").and()
.formLogin().loginPage("/login").permitAll();
}
This is my securityConfig code
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers("/listTodo").hasAnyRole("USER","ADMIN")
.anyRequest().authenticated()
.and().formLogin().loginPage("/login").permitAll().and()
.logout().permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("Sudhakar").password("qwe123").roles("USER","ADMIN");
}
}
I would need to login with user name and get the todo details of the user who logged in. But I am not able to get to next page, after trying many times I am getting below error
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
Below is my controller
package com.example.SpringLogin.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.example.SpringLogin.service.loginService;
#Controller
#SessionAttributes("name")
public class LoginController {
#Autowired
loginService service;
#RequestMapping(value="/login",method = RequestMethod.POST)
public String loginMessage(ModelMap model,#RequestParam String name,#RequestParam String password) {
boolean isValidUser=service.validateUser(name, password);
if(!isValidUser) {
model.put("message", "Invalid Credentials");
return"Room";
}
model.put("name", name);
model.put("password",password);
return "redirect:/todoList";
}
#RequestMapping(value="/login",method = RequestMethod.GET)
public String roomLogin(ModelMap model, String error) {
//model.put("name", name);
if(error!=null) {
model.addAttribute("errorMsg","UserName or Password is invalid");
}
return "Room";
}
/*#RequestMapping(value="/login",method = RequestMethod.GET)
public String showLogin(ModelMap model) {
//model.put("name", name);
return "Welcome";
}*/
#RequestMapping(value = "/welcome")
public String showWelcome(ModelMap model) {
return "login";
}
}
My login page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<c:set var="contextPath" value=""/>
<!DOCTYPE html>
<html>
<head>
<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css"
rel="stylesheet">
<title>Todo Application</title>
</head>
<body>
<div class="container">
<font color="red">${message}</font>
<form:form method="post" action="/login">
<fieldset class="form-group">
Name : <input type="text" name="username" class="form-control" placeholder="Username"
autofocus="true"/>
Password: <input type="password" name="password"
class="form-control" placeholder="Password" />
</fieldset>
<button type="submit" class="btn btn-success">Submit</button>
</form:form>
</div>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
After successful login it should go to below page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<c:set var="contextPath" value=""/>
<!DOCTYPE html>
<html>
<head>
<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css"
rel="stylesheet">
<title>Todo Application</title>
</head>
<body>
<div class="container">
<table class="table table-striped">
<H1>Name : ${pageContext.request.userPrincipal.name}</H1>
<thead>
<tr>
<th>Id</th>
<th>Course</th>
<th>End Date</th>
<th>Is it Done</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<c:forEach items="${todo}" var="item">
<tr>
<td>${item.id}</td>
<td>${item.course}</td>
<td><fmt:formatDate value="${item.date}" pattern="MM/dd/yyyy" /></td>
<td>${item.isdone?'Yes':'No'}</td>
<td><a type="button" class="btn btn-success"
href="/update-Todo?id=${item.id}">Update</a></td>
<td><a type="button" class="btn btn-warning"
href="/delete-Todo?id=${item.id}">Delete</a></td>
</tr>
</c:forEach>
</tbody>
</table>
<div>
<a type="button" href="/add-Todo" class="btn btn-success">Add a
Todo</a>
</div>
</div>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
Service class
package com.example.SpringLogin.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.springframework.stereotype.Service;
import com.example.SpringLogin.model.todoList;
#Service
public class TodoService {
public static List<todoList> todos=new ArrayList<todoList>();
public static int todoCount=5;
static {
todos.add(new todoList(1, "Sudhakar", "Study history", new Date(), false));
todos.add(new todoList(2,"Sudhakar","Study geography",new Date(),false));
todos.add(new todoList(3,"Sudhakar","Study GK",new Date(),false));
todos.add(new todoList(4,"Mani","Study Java",new Date(),false));
todos.add(new todoList(5,"Mani","Study script",new Date(),false));
}
public List<todoList> retrievetodos(String name){
List<todoList> retrieved=new ArrayList<todoList>();
for (todoList todo : todos) {
if(todo.getName().equalsIgnoreCase(name)) {
retrieved.add(todo);
}
}
return retrieved;
}
public void addTodo(String name,String Course,Date date,boolean isDone) {
todos.add(new todoList(++todoCount,name,Course,date,isDone));
}
public todoList retrieveTodo(int id){
for (todoList todo : todos) {
if(todo.getId()==id) {
return todo;
}
}
return null;
}
public List<todoList> UpdateTodo(todoList todo){
/*for (todoList td : todos) {
if(td.getId()==todo.getId()) {
td.setCourse(todo.getCourse());
td.setDate(todo.getDate());
}
}*/
todos.remove(todo);
todos.add(todo);
return todos;
}
//it will delete the todo
public void deleteTodo(int id) {
Iterator<todoList> it = todos.iterator();
while(it.hasNext()){
todoList td=it.next();
if(td.getId()==id) {
it.remove();
}
}
}
}
my expectation is to login application using user name and get the todolist of the user
Try adding a loginProcessUrl and a defaultSuccessUrl. Something like this:
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/do_login")
.defaultSuccessUrl("/index")
index in this example is the page you want to be taken to upon successful login.
Use this one
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/perform_login")
.defaultSuccessUrl("/homepage.html", true)

completing read CRUD sql in jsp servlet

I asked this questions last night, and was kind of foolish not to ask how to complete the coding on it. I now have a dropdown box in a JSP populated with some data from an SQL database. I am trying to get the selected data to direct to the final viewing page, but again am running into some difficulty with this.
When I run the program, it either populates the page with all the data from the list database, or will give me an unfriendly error.
My current coding is as such:
the Bean:
package com.login.read;
public class ReadBean {
protected int id;
protected String title;
protected String author;
protected String text;
public int getId(){
return id;
}
public void setId(int newID){
id = newID;
}
public String getTitle(){
return title;
}
public void setTitle(String newTitle){
title = newTitle;
}
public String getAuthor(){
return author;
}
public void setAuthor(String newAuthor){
author = newAuthor;
}
public String getText(){
return text;
}
public void setText(String newText){
text = newText;
}
}
The Controller:
package com.login.read;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
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;
#WebServlet (urlPatterns={"/com/defaultValidate/ReadController"})
public class ReadController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String address;
List<ReadBean> myList = new ArrayList<ReadBean>();
if(request.getParameter("ReadConfirm") != null){
try {
Connection connect = ConnectionManager.getConnection();
String SQL = "SELECT * FROM prayers ORDER BY prayerTitle DESC";
PreparedStatement ps = connect.prepareStatement(SQL);
ResultSet rs = ps.executeQuery();
while(rs.next()){
ReadBean reader = new ReadBean();
reader.setTitle(rs.getString("prayerTitle"));
reader.setAuthor(rs.getString("author"));
reader.setText(rs.getString("text"));
myList.add(reader);
}
request.getSession().setAttribute("ref", myList);
rs.close();
ps.close();
connect.close();
} catch (Exception e) {
}
address = "ReadConfirm.jsp";
} else if(request.getParameter("ReadView") != null){
address = "ReadView.jsp";
} else{
address = null;
}
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}
}
And my jsp pages that link the drop-down box to the selected material:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
%#include file="MenuHeader.jsp"%>
</div>
<div id="mainBorder"> </div>
<div id="mainBody">
<table id="mainTable">
<tr>
<td id="sidebar">
<h2>Options</h2>
<ul>
</ul>
</td>
<td id="mainContent">
<h2 id="contentHeader">Select a prayer</h2>
<form action="ReadController">
<table border="1" width="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><select name="prayer_id">
<c:forEach var="view" items="${ref}">
<h2>${view.title}</h2>
<h3>${view.author}</h3>
<p>${view.text}</p>
</c:forEach>
</select>
</td>
</tr>
<tr>
<td><input type="submit" name="ReadView" value="View"> </td>
</tr>
</tbody>
</table>
</form>
<td id="imageBar">
</td>
</table>
<%# include file="../menuHeaderAndFooter/MenuFooter.jsp" %>
and the final viewing page:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
%#include file="MenuHeader.jsp"%>
</div>
<div id="mainBorder"> </div>
<div id="mainBody">
<table id="mainTable">
<tr>
<td id="sidebar">
<h2>Options</h2>
<ul>
</ul>
</td>
<td id="mainContent">
<c:forEach var="view" items="${res}">
<h2>${view.title}</h2>
<h3>${view.author}</h3>
<p>${view.text}</p>
</c:forEach>
<form action="../Read.jsp">
<p>Click on the return button to return to the main menu</p>
<input type="submit" name="return" value="Return">
</form>
<td id="imageBar">
</td>
</table>
<%# include file="../menuHeaderAndFooter/MenuFooter.jsp" %>
As always, any and all assistance in this regard is incredibly helpful. I am a relative newbie to the world of jsp and servlets.
If one needs any reference as to the continuation of this sequence, kindly view the previous question I posted regarding dynamically displaying data in a jsp combo-box.
Thank you for your time and help.
By reading above code, I can just ask you that where you have stored your session attribute in variable "var", which is being used in c:foreach loop ?

Page redirection on submit... Netbeans

I created a web application that edit a database...
I would like to know how I add or redirect the page after clicking on submit.
Sorry i'm still learning...
Currently Im using "usebean" to insert the content of the form to the database. I would like to know if how to redirect the page after the enter all info in the fields then click submit..
Thanks
here's the code:
<%# page language="Java" import="java.sql.*" %>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<html>
<head><title>CSN Survey</title></head>
<body bgcolor="#ffffff">
<div>
<img id="title" src="images/CSN.gif" width="243" height="27" alt="CSN"/>
<img id="logo" src="images/tr_logo_40.gif" width="178" height="40" alt="tr_logo_40"/>
</div>
<hr>
<h1> insert comment </h1>
<div id="container">
<form action="" name="form1" method="POST">
<br>
<br>
<br>
<td><br>Write your comment here:</td>
<div id="q1"
<td>id:<%=request.getParameter("id")%></td>
<td>First name:<textarea name="first_name" rows="1" cols="10"></textarea></td>
<td>Last name:<textarea name="last_name" rows="1" cols="10"></textarea></td>
<br>
<br>
</div>
<td>
<input type = "submit" value="Submit">
</td>
</form>
</div>
<jsp:useBean id="survey" class="csnsurveysource.csnsurveyclass" scope="page">
<jsp:setProperty name="survey" property="*"/>
</jsp:useBean>
<% survey.insert();%>
</body>
</html>
csnsurveyclass.java:
package csnsurveysource;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
public class csnsurveyclass
{
private int id;
private String first_name;
private String last_name;
private Connection connection=null;
private ResultSet rs = null;
private Statement st = null;
String connectionURL = "jdbc:postgresql://localhost:5432/test";
public csnsurveyclass()
{
try {
// Load the database driver
Class.forName("org.postgresql.Driver");
// Get a Connection to the database
connection = DriverManager.getConnection(connectionURL, "postgres", "qqQQ11!!");
}catch(Exception e){
System.out.println("Exception is ;"+e);
}
}
public void setid(int id)
{
this.id = id;
}
public int getid()
{
return (this.id);
}
public void setfirst_name(String first_name)
{
this.first_name = first_name;
}
public String getfirst_name()
{
return (this.first_name);
}
public void setlast_name(String last_name)
{
this.last_name = last_name;
}
public String getlast_name()
{
return (this.last_name);
}
public void insert()
{
try
{
String sql = "update testing set fname = '"+first_name+"',lname = '"+last_name+"' where id = "+id+"";
Statement s = connection.createStatement();
s.executeUpdate (sql);
s.close ();
}
catch(Exception e){
System.out.println("Exception is ;"+e);
}
}
}
It will be good to use MVC pattern, you can move business logic
survey.insert();
into controller and then send redirect
response.sendRedirect("...");
put where you want to redirect in the action inside your form tag
<form action="put here ur action/url" name="form1" method="POST">

Categories

Resources