lundi 25 mai 2015

Online shopping web based project using java & mysql

Help me in this code to add "add to cart"option and to add pictures and retrieve from database and remove bugs.!! done though mvc concept.

//LoginController.java

package com.zab.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginController extends HttpServlet {
private static final long serialVersionUID = 1L;
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/shop";
static final String USER = "root";
static final String PASS = "12345" ; 
Connection conn = null;
Statement stmt = null;
RequestDispatcher dispatch = null;
HttpSession session = null;
protected void doGet(HttpServletRequest request, HttpServletResponse     response) throws ServletException, IOException {
System.out.println("get"); 
try {
Class.forName("com.mysql.jdbc.Driver");
} 
catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
} catch (SQLException e) {
e.printStackTrace();
}
try {
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
try {
String UserName = request.getParameter("UserName");
String Password = request.getParameter("Password");
String Email= (request.getParameter("Email"));
String Ccn = (request.getParameter("CreditCardNo"));
String Add = (request.getParameter("Address"));
//String sql = "insert into user where UserName='"+UserName+"' and      Password= '"+Password+"'";
String sql= ("insert into shop.user "+"(UserName,Password,Email,CreditCardNo,Address)"+"Values('"+UserName+"','"+Password+"','"+Email+"','"+Ccn+"','"+Add+"')");
PrintWriter pw = response.getWriter();
response.setContentType("text/html");
ResultSet rs = stmt.executeQuery(sql);
dispatch = request.getRequestDispatcher("Login.jsp");
} catch (SQLException e) {
e.printStackTrace();
}   
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse       response) throws ServletException, IOException {
System.out.println("Post");
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String UserName = request.getParameter("UserName");
String Password = request.getParameter("Password");
String sql = "SELECT UserId from user where UserName='"+UserName+"'    and  Password= '"+Password+"'";
PrintWriter pw = response.getWriter();
response.setContentType("text/html");
ResultSet rs = stmt.executeQuery(sql);
(rs.next()) {
int id = rs.getInt("UserId");
session = (HttpSession)request.getSession();
session.setAttribute("uname", UserName);
session.setAttribute("id", String.valueOf(id));
dispatch = request.getRequestDispatcher("Home.jsp");
pw.println("Login Success...!");
}
else {
session = request.getSession();
session.setAttribute("error", "username or password is incorrect!");
dispatch = request.getRequestDispatcher("Login.jsp");
pw.println("Login Failed...!");

        }
pw.print("<font face='verdana'>");
pw.println("Login Failed...!");
*/
pw.print("</font>");
dispatch.forward(request, response);

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}

}

//PageController.java

package com.zab.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zab.dao.MyShoppingDao;
import com.zab.modal.MyShopping;

public class PageController extends HttpServlet {
private static final long serialVersionUID = 1L;


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
String id = request.getParameter("id");

RequestDispatcher dispatch = null;
MyShoppingDao ms = new MyShoppingDao();

if(action.equalsIgnoreCase("Shopping")){
request.setAttribute("list",   ms.getMyShoppingById(Integer.parseInt(id)));
request.setAttribute("TotalAmount", ms.getAmountInAccountById(Integer.parseInt(id)));
dispatch = request.getRequestDispatcher("MyShopping.jsp");
}
if(action.equalsIgnoreCase("add")){
String desc = request.getParameter("desc");
String TotalAmount = request.getParameter("TotalAmount");
String Credit_Debit = request.getParameter("c_or_d");

Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String currentDate = dateFormat.format(date);
MyShopping my = new MyShopping();

MyShoppingDao mss=new MyShoppingDao();

my.setCreditDebit(Credit_Debit);
my.setDateTime(currentDate);
my.setUserId(Integer.parseInt(id));
mss.addToShopping(my);
request.setAttribute("list", ms.getMyShoppingById(Integer.parseInt(id)));
dispatch = request.getRequestDispatcher("MyShopping.jsp");
}
dispatch.forward(request, response);

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

}

//MyShoppingDao.java

package com.zab.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.zab.modal.MyShopping;
import com.zab.util.DbUtil;

public class MyShoppingDao {
private Connection con;

public MyShoppingDao(){
con = DbUtil.getConnection();
}

public List<MyShopping> getMyShoppingById(int id){
List<MyShopping> Shopping = new ArrayList<MyShopping>();
Statement st;
try {
st = con.createStatement();
ResultSet rs = st.executeQuery("select * from sales where UserId="+id);
while(rs.next()){
MyShopping ms = new MyShopping();
ms.setUserId(rs.getInt("id"));
ms.setProductId(rs.getInt("ProductId"));
ms.setDateTime(rs.getString("Datetime"));
ms.setCreditDebit(rs.getString("CreditDebit"));
ms.setTotalAmount(rs.getFloat("TotalAmount"));
Shopping.add(ms);
}
} catch (SQLException e) {
e.printStackTrace();
}
return  Shopping;
}

public void addToShopping( MyShopping ms) {
try {
PreparedStatement ps = con.prepareStatement("insert into sales(CreditDebit, DateTime, UserId, ProductId) values(?,?,?,?)");
ps.setString(1, ms.getCreditDebit());
ps.setString(2, ms.getDateTime());
ps.setInt(3, ms.getUserId());
ps.setInt(4, ms.getProductId());
ps.setFloat(2, ms.getTotalAmount());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}

public String getAmountInAccountById(int id) {
String result = "";
try {
float credit = 0;
float debit = 0;
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select sum(TotalAmount) as total from sales where UserId="+id+" and CreditDebit = 'credit'");
if(rs.next()){
if(rs.getString("total")!=null){
credit = Float.parseFloat(rs.getString("total"));
}
}
rs.close();
rs = st.executeQuery("select sum(TotalAmount) as total from sales where idusers="+id+" and CreditDebit = 'debit'");
if(rs.next()){
if(rs.getString("total")!=null){
debit = Float.parseFloat(rs.getString("total"));
}
}
result = String.valueOf(debit - credit);
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}

}

//ProductDao package com.zab.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.zab.modal.Products;
import com.zab.util.DbUtil;

public class ProductDao {
private Connection con;

public ProductDao(){
con = DbUtil.getConnection();
}

public List<Products> getProductsById(int id){
List<Products> Products = new ArrayList<Products>();
Statement stmt;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from products where UserId="+id);
while(rs.next()){
Products pr = new Products();
pr.setProductId(rs.getInt("ProductId"));
pr.setDescription(rs.getString("Description"));
pr.setAmount(rs.getInt("Amount"));
pr.setPictureId(rs.getInt("PictureId"));
Products.add(pr);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return Products;
}

public void addToProducts(Products pr) {
try {
PreparedStatement ps = con.prepareStatement("insert into    Products(ProductId, Description, Amount, PictureId) values(?,?,?,?)");
ps.setInt(1, pr.getProductId());
ps.setString(2,pr.getDescription());
ps.setInt(3, pr.getAmount());
ps.setInt(4, pr.getPictureId());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}


}

//MyShopping.java //class

package com.zab.modal;
public class MyShopping {
private int SalesId;
private String CreditDebit;
private float TotalAmount;
private String DateTime;
private int UserId;
private int ProductId;

public float getTotalAmount() {
return TotalAmount;
}
public void setTotalAmount(float totalAmount) {
TotalAmount = totalAmount;
}
public int getSalesId() {
return SalesId;
}
public void setSalesId(int salesId) {
SalesId = salesId;
}
public String getCreditDebit() {
return CreditDebit;
}
public void setCreditDebit(String creditDebit) {
CreditDebit = creditDebit;
}
public String getDateTime() {
return DateTime;
}
public void setDateTime(String dateTime) {
DateTime = dateTime;
}
public int getUserId() {
return UserId;
}
public void setUserId(int userId) {
UserId = userId;
}
public int getProductId() {
return ProductId;
}
public void setProductId(int productId) {
ProductId = productId;
}
}

//Products.java //class

package com.zab.modal;
public class Products {
private int ProductId;
private String Description;
private int Amount;
private int PictureId;
public int getPictureId() {
return PictureId;
}
public void setPictureId(int pictureId) {
PictureId = pictureId;
}
public int getProductId() {
return ProductId;
}
public void setProductId(int productId) {
ProductId = productId;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public int getAmount() {
return Amount;
}
public void setAmount(int amount) {
Amount = amount;
}

}




//Credit_Debit.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"           "http://ift.tt/kTyqzh">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Credit_Debit</title>
<%String id = (String)session.getAttribute("id");
String UserName = (String)session.getAttribute("uname"); %>
<% if(UserName !=  null){ %>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-user"></i><%=UserName %></a>
</li>
<li class="dropdown">
<a href="logout.jsp"><i class="glyphicon glyphicon-log-out"></i> Logout</a>
</li>
<ul class="nav navbar-nav side-nav">
<li >
<a href="index.html"><i class="fa fa-fw fa-dashboard"></i> Home</a>
</li>
<li>
<a href="PageController?action=MyShopping&id=<%=id %>"><i class="fa fa-fw fa-bar-chart-o"></i> MyShopping</a>
</li>
<li  class="active">
<a href="Credit_Debit.jsp<%=id %>"><i class="fa fa-fw fa-table"></i> Add Credit/Debit</a>
</li>
<form action="PageController?action=add&id=<%=id%>" method="post">
<table class="table table-bordered table-hover table-striped" style="width:30%">
<thead>
</thead>
<tbody>
<tr>
<td>Description</td>
<td><input type="text" name="Description"></td>
</tr>
<tr>
<td>TotalAmount</td>
<td><input type="text" name="TotalAmount"></td>
</tr>
<tr>
<td>Credit/Debit</td>
<td>
<select name="c_or_d">
<option value="0">Select an option</option>
<option value="Credit">Credit</option>
<option value="Debit">Debit</option>
</select>
</td>
</tr>
<tr colspan="2">
<td></td>
<td><input type="submit" value="OK"><input type="reset" value="Clear"></td>
</tr>
</tbody>
</table></ul>
</form>
<%} %>
</body>
</html>

//MyShopping.jsp
<%@page import="com.zab.util.DbUtil"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://ift.tt/QfKAz6" prefix="c"%>
<%@page import="com.zab.modal.MyShopping"%>
<%@page import="com.zab.dao.MyShoppingDao"%>
<%@page import="java.util.List"%>
<%@ page import = "java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"    "http://ift.tt/kTyqzh">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> title>MyShopping</title>
</head>
<body>
<%  
//String Amount = (String)request.getAttribute("amount");
String id = (String)session.getAttribute("id");
String UserName = (String)session.getAttribute("uname"); %>
<% if(UserName !=  null){ %>
<% DbUtil db = new DbUtil();
Statement statement = db.getConnection().createStatement();
ResultSet rs = st.executeQuery("select sum(TotalAmount) as Total from shop.sales where UserId="+id+" ");
//ResultSet rs = statement.executeQuery("SELECT * FROM shop.sales");
//PreparedStatement ps;
// MyShopping ms;
//ps.setFloat(2,ms.getTotalAmount());   
%>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-user"></i><%=UserName %></a></li>
<li class="dropdown">
<a href="logout.jsp"><i class="glyphicon glyphicon-log-out"></i>Logout</a>
</li>
<li>
<a href="index.jsp"><i class="fa fa-fw fa-dashboard"></i> Dashboard</a>
</li>
<li class="active">
<a href="MyShopping.jsp"><i class="fa fa-fw fa-bar-  chart-o"></i> MyShopping</a></li>
<li><a href="Credit_Debit.jsp"><i class="fa fa-fw fa-table"></i>Add Credit/Debit</a></li>
<div class="table-responsive">
<b>Amount in Account: <%=TotalAmount%></b>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Date&Time</th>
<th>Description</th>
<th>Credit/Debit</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<c:forEach items="${list }" var="an_item">
<tr>
<td><c:out value="${an_item.getCreditDebit() }"/></td>
<td><c:out   value="${an_item.getDateTime() }"/></td>
<td><c:out value="${an_item.getUserId()}"/></td>
<td><c:out value="${an_item.getProductId()}"/></td>
</tr>
</c:forEach></tbody></table></div>
</body>
</html>

//index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>index</title>
</head>
<body>
<h1>Welcome page</h1>
<form action="LoginController">
<a href="Login.jsp">Login</a>
<a href="Registration.jsp">Register</a>

</form>
</body>
</html>

//login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%> Login Page

Login Page




Login:

Password:
//Home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"   "http://ift.tt/kTyqzh">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home</title>
</head>
<body>
I AM HOME
</body>
</html>




Aucun commentaire:

Enregistrer un commentaire