Data not getting added to the database using servlet(jsp) - java

I'm pasting my code:
public class FetchData extends HttpServlet {
private static final long serialVersionUID = 1L;
public intern i;
ResultSet rs;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
response.setContentType("text/html");
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/grey_goose","root","Ankit#7231");
PreparedStatement ps=conn.prepareStatement("select * from winter_internship");
rs=ps.executeQuery();
ArrayList<intern> myArr = new ArrayList<intern>();
while(rs.next()) {
i = new intern();
i.setSl_no(rs.getInt("sl_no"));
i.setBusiness_code(rs.getString("Business_code"));
i.setCust_number(rs.getInt("cust_number")) ;
i.setClear_date(rs.getString("clear_date")) ;
i.setBuisness_year(rs.getInt("buisness_year")) ;
i.setDoc_id(rs.getString("doc_id")) ;
i.setPosting_date(rs.getString("posting_date")) ;
i.setDocument_create_date(rs.getString("document_create_date")) ;
i.setDocument_create_date1(rs.getString("document_create_date1")) ;
i.setDue_in_date(rs.getString("due_in_date")) ;
i.setInvoice_currency(rs.getString("invoice_currency")) ;
i.setDocument_type(rs.getString("document_type")) ;
i.setPosting_id(rs.getInt("posting_id")) ;
i.setArea_business(rs.getString("area_business")) ;
i.setTotal_open_amount(rs.getDouble("total_open_amount")) ;
i.setBaseline_create_date(rs.getString("baseline_create_date")) ;
i.setCust_payment_terms(rs.getString("cust_payment_terms")) ;
i.setInvoice_id(rs.getInt("invoice_id")) ;
i.setIsOpen(rs.getInt("isOpen")) ;
i.setAging_bucket(rs.getString("aging_bucket")) ;
i.setIs_deleted(rs.getInt("is_deleted")) ;
myArr.add(i);
}
Gson gson = new Gson();
String final_data = gson.toJson(myArr);
PrintWriter out=response.getWriter();
out.print(final_data);
out.flush();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
//I'm using this file for fetching my data from the server.
/**
* Servlet implementation class addServlet
*/
public class addServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public addServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
//String check = "SET FOREIGN_KEY_CHECK=0";
try
{
HashMap<Object, Object> Response = new HashMap<Object, Object>() ;
String businessCode = request.getParameter("businessCode");
int custNumber = Integer.parseInt(request.getParameter("custNumber"));
String clearDate = request.getParameter("clearDate");
int businessYear = Integer.parseInt(request.getParameter("businessYear"));
long docId = Long.parseLong(request.getParameter("docId"));
String postingDate = request.getParameter("postingDate");
String documentCreateDate = request.getParameter("documentCreateDate");
String dueInDate = request.getParameter("dueInDate");
String invoiceCurrency = request.getParameter("invoiceCurrency");
String documentType = request.getParameter("documentType");
int postingId = Integer.parseInt(request.getParameter("postingId"));
double totalOpenAmount = Double.parseDouble(request.getParameter("totalOpenAmount"));
String baselineCreateDate = request.getParameter("baselineCreateDate");
String customerPaymentTerms = request.getParameter("customerPaymentTerms");
int invoiceId = Integer.parseInt(request.getParameter("invoiceId"));
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/grey_goose","root","Ankit#7231");
String query = "INSERT INTO winter_internship (business_code , customer_number , clear_date , business_year , document_id , posting_date , document_create_date , due_date , invoice_currency , document_type , posting_id , total_open_amount , baseline_create_date , customer_payment_terms , invoice_id) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
// PreparedStatement preparedStatement=conn.prepareStatement(check);
// preparedStatement.executeUpdate();
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, businessCode);
ps.setInt(2, custNumber);
ps.setString(3, clearDate);
ps.setInt(4, businessYear);
ps.setLong(5, docId);
ps.setString(6, postingDate);
ps.setString(7, documentCreateDate);
ps.setString(8, dueInDate);
ps.setString(9, invoiceCurrency);
ps.setString(10, documentType);
ps.setInt(11, postingId);
ps.setDouble(12, totalOpenAmount);
ps.setString(13, baselineCreateDate);
ps.setString(14, customerPaymentTerms);
ps.setInt(15, invoiceId);
if (ps.executeUpdate() > 0)
{
Response.put ("update", true);
}
else
{
Response.put ("update",false);
}
Gson gson= new Gson ();
String Responsejson=gson.toJson (Response);
response.setHeader ("Access-control-Allow-Origin", "*");
response.getWriter().append (Responsejson);
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
/I'm using this code to upload data to the server on click a button(Add) which is calling the method doGet, also tried postman still data not getting added./

Related

how to return value from java class to Servlet in java

I have java class LoginValidation and Servlet Login ,am passing values from servlet to java class,but am not getting return values..from servlet to java class...
//normal java class LoginValidation
public class LoginValidation {
String userid="";
String password="";
String que="";
Connection dbConnection = null;
PreparedStatement pst=null;
ResultSet rs=null;
String userid1="";
String password1="";
int pan1=0;
public long valiDate(String userid ,String password){
long flag = 0l;
this.password=password;
this.userid=userid;
dbConnection = JDBCConnection.getDBConnection();
que="select * from shivu";
try {
pst = dbConnection.prepareStatement(que);
rs=pst.executeQuery();
while(rs.next()){
userid1=rs.getString(3);
password1=rs.getString(2);
pan1=rs.getInt(8);
if ((userid.equals(userid1)) && (password.equals(password1))){
flag = pan1;
}else{
flag = 0;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
}
//Servlet Login
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String userid=request.getParameter("userid");
String password=request.getParameter("password");
LoginValidation lv=new LoginValidation();
System.out.println("control flow");
long i=lv.valiDate(userid,password);
System.out.println(i);
if(i>=1){
System.out.println("control flow inside method call");
HttpSession session = request.getSession();
if (session != null)
session.setAttribute("pan", i);
response.sendRedirect("welcome.jsp");
}
else
{
System.out.println("Username or Password incorrect");
response.sendRedirect("login1.jsp");
}
}
}
you can print and see the values inside valiDate method.
while(rs.next()){
userid1=rs.getString(3);
password1=rs.getString(2);
pan1=rs.getInt(8);
// print userid, userid1, password, password1, pan1
if ((userid.equals(userid1)) && (password.equals(password1))){
flag = pan1;
}else{
flag = 0;
}
}

Java Servlet (doGet) 204 Http erorr

Hello all i have write this servlet to doGet data and Client-side can get some information from database after query and
pointer but when i send a pointer to servlet from client-side there
are no response and http code is 204 can any one help me with that?
thanks
//This Servlet Make User To Get Data from Database (data) Table (replay) Fileds (Callreplay,State)
package server;
import java.io.IOException;
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 = "GetStatus", urlPatterns = {"/GetStatus"})
public class GetStatus extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public GetStatus()
{
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// getting id as parameter
String strID;
strID = request.getParameter("newid");
System.out.println("* Pointer is "+strID);
// connecting to the database
GetStatusFromDB dbManager = new GetStatusFromDB();
dbManager.iniDBManagementLayer("jdbc:mysql://127.0.0.1:3306/data",
"root",
""
);
//System.out.println("** Connection with database OK!");
// getting data from the database
String sql = "SELECT * FROM replay WHERE S_id = " + strID + ";";
dbManager.setFields("status", "comment");
dbManager.sendQuery(sql);
String resp = dbManager.getJSON();
System.out.println("*** Mutaz Method Ok!");
if(resp != null)
{
System.out.println(resp);
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json; charset=utf-8");
response.getWriter().print(resp);
// System.out.println("Get Ok !");
}
else
{
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
public void sendQuery(String query) {
// Connection, statement, and ResultSet should not defined as instances
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
InitialContext ctx = new InitialContext();
DataSource ds =
(DataSource)ctx.lookup("java:comp/env/jdbc/jndipool");
conn = ds.getConnection();
st = conn.prepareStatement(query);
rs = st.executeQuery();
processResults(rs);
} catch (NamingException ex) {
// Logger.getLogger(DBManagementLayer.class.getName()).log(Level.SEVERE, null, ex);
this.errorFlag = true;
this.lastError = ex.toString();
} catch (SQLException ex) {
this.errorFlag = true;
this.lastError = ex.toString();
}
finally{
if ( rs != null ) {
try { rs.close(); rs = null;}
catch (SQLException e) {
errorFlag = true; lastError = e.toString(); }
}
Http response code 204 is what is being set by this line
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
So it's likely that dbManager.getJSON() is returning null.
**in this line i most add
try
{
////here most add rs.first();
Gson conv = new Gson();
String status = rs.getString(fieldOne);
String comment = rs.getString(fieldTwo);
String rep = conv.toJson(new StatusForm(status, comment ));
this.statusAsJSON = rep;
} catch (SQLException ex) {
Logger.getLogger(GetStatusFromDB.class.getName()).log(Level.SEVERE, null, ex);
}
this must add
boolean first = rs.first();
and it will be fixed
thanks for evrey body here help me thanks for all programmers here thank you stackoberflow.com Max**

get input value in a java class

I have my servlet:
public class Authentification extends HttpServlet {
public int id1;
private static final long serialVersionUID = 1L;
public HttpSession session;
Authentification_link auth=new Authentification_link();
public Integer IdUser;
public Authentification() {
super();
}
public void init() {
Codb co= new Codb();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
int IdUser = Integer.valueOf(request.getParameter("id"));
session.setAttribute("ide", IdUser);
try {
if(auth.authen(IdUser)){
session.setAttribute("id", IdUser);
request.getRequestDispatcher("acceuil.jsp").forward(request, response);
System.out.println("found");}
else{
request.getRequestDispatcher("index.jsp").forward(request, response);
System.out.println("not found");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void doInteret (HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {
IdUser = (Integer) session.getAttribute("IdUser");
Interets inte= new Interets (IdUser);
}
}
The user login to through an id, the authentification works fine, but now I want to get the same user's id so I can include it in this java classe when the user click on a link. For that I added the method doInteret in the servlet and the class Interet.java is like this:
public class Interets {
static Statement St ;
public ResultSet rs;
public Interets(Integer IdUser) throws SQLException, ServletException, IOException{
String res=" ";
try{
ResultSet result = St.executeQuery("SELECT description FROM interets, avoir, consomateur WHERE avoir.id_interet=interets.id_interets AND avoir.id_user=consomateur.code_bar AND consomateur.code_bar="+IdUser+"");
ResultSetMetaData resultMeta = (ResultSetMetaData) result.getMetaData();
while(result.next()){
String Newligne=System.getProperty("line.separator");
for(int i = 1; i <= resultMeta.getColumnCount(); i++){
res=res+Newligne+result.getObject(i).toString();
System.out.println(res);
}
}
}
catch (Exception e) {
System.out.println("Error in Select ");
}
}
}
but I am getting this error:
org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.NoSuchMethodError: pack1.Interets.AfficheInteret()Ljava/lang/String;
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:412)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
try changing your query and print it may be your query is not working
SELECT description FROM interets, avoir, consomateur WHERE avoir.id_interet=interets.id_interets AND avoir.id_user=consomateur.code_bar AND consomateur.code_bar='"+IdUser+"'");

RequestDispatcher.forward() to resource under “/WebContent” doesn't work

I am dispatching a request to html resource in Webcontent folder in servlet. But its not dispatching it. Even its not giving any exception. AboutUs is an html page placed in WebContent folder of project. The IDE i am using is eclipse. I am very new to web development. any help will be appreciated.
Thanks in advance.
Servlet Code:
#WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Login() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name="";
String pass="";
name=request.getParameter("param1");
pass=request.getParameter("param2");
System.out.println("Name :" +name+"PAss :"+pass);
if (name!=null && pass!=null){
List<User> please = DataAccessUtil.getByEmail(name, pass);
if (please!=null)
{
int count = please.size();
System.out.println("Record Found : " + count);
if(!(count==0))
{
Iterator<User> iterator = please.iterator();
while(iterator.hasNext())
{
User object = (User) iterator.next();
String email = object.getEmail();
HttpSession session = request.getSession();
session.setMaxInactiveInterval(60);
session.setAttribute("email", email);
}
RequestDispatcher r= request.getRequestDispatcher("/AboutUs.html");
r.forward(request, response);
log("please");
}
else{
RequestDispatcher rd= request.getRequestDispatcher("/DR.html");
rd.forward(request, response);
log("please2");
}
}
}
else{
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}

Unexpected Token L when printing a json object Using advanced rest chrome

Im using a servlet that connects to a database and prints out whether or not you are logged in or not, When using printWriter.write(JsonObject) i get the error in rest Unexpected Token L. I am using a tomcat server to host the data.
public class Login extends HttpServlet {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/employeedatabase";
// Database credentials
static final String USER = "root";
static final String PASS = "admin";
static Connection conn = null;
static Statement stmt = null;
static ResultSet rs;
static PrintWriter out;
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Login() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json; charset=UTF-8");
out = response.getWriter();
String email = request.getParameter("username");
String password = request.getParameter("password");
String result = "";
if(Validation.validateNull(email) && Validation.validateNull(password)){
if(!Validation.validateEmail(email))
{
result = "Invalid email";
}
if(databaseFuctions.Login(email,password))
{
result = "Login accepted";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
getFromDatabase("manager",email,request,response);
// getFromDatabase("qa",email,request,response);
// getFromDatabase("developer",email,request,response);
} catch (Exception e1) {
// TODO Auto-generated catch block
System.out.println(e1.getMessage());
}
}
else if(!databaseFuctions.Login(email, password))
{
result = "Login invalid";
}}
else{
result = "No login/password entered";
}
out.write(result);
}
public static void getFromDatabase(String table,String email,HttpServletRequest request, HttpServletResponse response){
JSONObject JObject = new JSONObject();
ResultSet ds;
try {
ds = stmt.executeQuery("SELECT * from "+table+" where email = '"+email+"'");
while(ds.next())
{
int id = ds.getInt("id");
int salary = ds.getInt("salary");
String name = ds.getString("name");
String role = ds.getString("role");
String emailAddress = ds.getString("email");
String phone = ds.getString("phone");
JObject.put("id", id);
JObject.put("salary", salary);
JObject.put("name", name);
JObject.put("role", role);
JObject.put("email", emailAddress);
JObject.put("phone", phone);
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
out.print(JObject.toString());
out.flush();
System.out.println(JObject.toString());
}
When printing in the system i get all the correct data, or checking the raw data from rest i get the correct data. But i dont quite understand why the printer is throwing the exception any help is amazing
Ok If the error is in the client is beacuse you are returning a mal formed JSON value, so you are returning something like that: { id: 13, name: "Name"}Login invalid then the first character the L is not valid for the JSON Syntax.
This is becuase you are writing in the response the json string from the method getFromDatabase out.print(JObject.toString()); and after the method call you add to the response the string result = "Login invalid"; out.write(result); that cause you have a invalid JSON.
One way to solve this is return the JSONObject from the method getFromDatabase, and add the put the result method in this object JObject.put("result", result) and the write the object to the response.

Categories