Java Servlet (doGet) 204 Http erorr - java

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**

Related

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

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./

Version control for java restful servlet

We need to apply version control for our API, when the user send a request to our API endpoint i.e."http://mycompany/item?version=1", it will forwarded the request to itemServer_V1.java.
To achieve this goal, we have configured our web.xml as follows.
<servlet>
<servlet-name>item</servlet-name>
<servlet-class>com.mycompany.Servlet.ItemRequestHandler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>item</servlet-name>
<url-pattern>/item</url-pattern>
</servlet-mapping>
We create a table in MySQL database.
database table
ItemRequestHandler is a class which extends HttpServlet, and it supposed to forward the request to ItemServiceV1 or ItemServiceV2 according to the version parameter in the request.
I have finish the ItemService class but I don't know how to forward the request from ItemRequestHandler to ItemService class. Could someone let me know how to do that please?
ItemRequestHandler class is as follows
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException , IOException
{
String version = req.getParameter("version");
String fcd = req.getParameter("fcd");
String client = req.getParameter("client");
//Find the targetClass from database using the above information.
targetClass.doGet(req, res);
}
I find out a solution.
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
System.out.println("LoginRequestHandler doPost");
String className = "";
String version = "";
String fcd = "login";
String compid = "";
RequestWrapper currentReq = new RequestWrapper(req);
version = currentReq.getParameter("Version");
compid = currentReq.getParameter("Compid ");
try {
className = findServletByVersion(compid, version, fcd);
Class<?> serviceClass = Class.forName(className);
Method method = serviceClass.getDeclaredMethod(MethodName.doPost.toString(), HttpServletRequest.class, HttpServletResponse.class);
method.invoke(serviceClass.newInstance(), currentReq, res);
return;
}catch(Exception e) {
System.out.println(e.toString());
} catch (DataNotFound e) {
System.out.println(e.toString());
}
}
}
Code of RequestWrapper
public class RequestWrapper extends HttpServletRequestWrapper {
private String _body;
public RequestWrapper(HttpServletRequest request) throws IOException {
super(request);
_body = "";
BufferedReader bufferedReader = request.getReader();
String line;
while ((line = bufferedReader.readLine()) != null){
_body += line;
}
}
#Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(_body.getBytes());
return new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
}
Code of findServletByVersion
public String findServletByVersion(String compid, String version, String fcd) throws SQLException, ClassNotFoundException, DataNotFound {
String clsName = "";
Connection con = null;
Statement stmt = null;
User user = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://YourIpAddress:PortNum/"+schemaName,"account","password");
String query = "SELECT * FROM "+compid+".restfcd "
+ "WHERE 1=1 "
+ "AND compid = '"+compid+"'"
+ "AND version = '"+version+"'"
+ "AND fcd = '"+fcd+"'"
+ "ORDER BY compid desc";
System.out.println(query);
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs!=null) {
while (rs.next()) {
clsName = rs.getString("fcdcls");
}
}
if(Func.isEmpty(clsName)) {
throw new DataNotFound("findServletByVersion : no match result!");
}
return clsName;
} catch (SQLException e) {
throw new SQLException("findServletByVersion : SQLException!");
} catch (ClassNotFoundException e) {
throw new ClassNotFoundException("findServletByVersion : ClassNotFoundException!");
} finally {
try {
con.close();
stmt.close();
} catch (SQLException sqlee) {
throw new SQLException("Cannot close conection/statement!");
}
}
}

Learn to program in Java Servlet connection to db

I'm learning to program in java and the use of servlet and jsp page.
I have some trouble understanding how I can make the connection with the database.
In particular I have a Java page called Database.java where I create the connection with the database and in which there are all the functions that are performed.
And I created a page called Prenotation.java where I have to do some actions. My problem is that I would not like to leave the database connection on this page (as you can see from the code) but I would like to make the connection via the Database.java page.
I've tried several times but I do not understand how I can do it.
Can you give me some advice? Thank you.
Database.java
package db;
import java.math.BigDecimal;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeUnit;
import entity.*;
public class Database {
private Connection connection = null;
private PreparedStatement statement = null;
private ResultSet rs = null;
private String dbname = "Hotel";
String nomeutente = "root";
String password = "123456789";
private static Database db = null;
public static synchronized Database getDatabase() {
if (db == null) {
db = new Database();
}
return db;
}
private Database() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + dbname
+ "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC",
nomeutente, password);
} catch (Exception exc) {
exc.printStackTrace();
}
}
public Connection getConnection() {
return connection;
}
public boolean checkUser(String email, String password) throws SQLException {
boolean result = false;
String query = "select password from users where email=?";
statement = connection.prepareStatement(query);
statement.setString(1, email);
rs = statement.executeQuery();
if (rs.next() && password.equals(rs.getString("password"))) {
result = true;
}
rs.close();
statement.close();
return result;
}
public boolean existingMail(String email) throws SQLException {
String query = "select * from users where email=?";
boolean result = true;
statement = connection.prepareStatement(query);
statement.setString(1, email);
rs = statement.executeQuery();
if (rs.next()) {
result = true;
} else {
result = false;
}
rs.close();
statement.close();
return result;
}
public boolean insertUtente(Utente u,String password) throws SQLException {
String query = "INSERT INTO users (email,nome,cognome,luogodinascita,datadinascita,indirizzo,password) VALUES (?,?,?,?,?,?,?)";
if(existingMail(u.getEmail())) {
return false;
}
statement = connection.prepareStatement(query);
statement.setString(1, u.getEmail());
statement.setString(2, u.getNome());
statement.setString(3, u.getCognome());
statement.setString(4, u.getLuogodinascita());
statement.setString(5, u.getDatadinascita());
statement.setString(6, u.getIndirizzo());
statement.setString(7, password);
statement.execute();
statement.close();
return true;
}
public Utente getUtente(String email) throws SQLException {
String query= "select * from users where email=?";
statement = connection.prepareStatement(query);
statement.setString(1, email);
rs=statement.executeQuery();
if(!rs.next()) {
return null;
}
Utente u=new Utente(email,rs.getString("nome"),rs.getString("cognome"),rs.getString("datadinascita"),rs.getString("luogodinascita"),rs.getString("indirizzo"));
rs.close();
statement.close();
return u;
}
public boolean modificaPassword(String email, String password) throws SQLException {
String query="UPDATE users SET password='"+password+"' WHERE email='"+email+"'";
Statement statement=connection.createStatement();
statement.executeUpdate(query);
statement.close();
return true;
}
public boolean modificaProfilo(Utente u) throws SQLException {
String query="UPDATE users SET nome = ?, cognome = ?, datadinascita = ?, luogodinascita = ?, indirizzo = ? WHERE email = ?";
statement = connection.prepareStatement(query);
statement.setString(1, u.getNome());
statement.setString(2, u.getCognome());
statement.setString(3, u.getDatadinascita());
statement.setString(4, u.getLuogodinascita());
statement.setString(5, u.getIndirizzo());
statement.setString(6, u.getEmail());
statement.executeUpdate();
statement.close();
return true;
}}
This instead is the page of which I speak
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;
import db.Database;
import entity.Prenotazione;
/**
*
* #author OOPs
*/
public class Prenotation extends HttpServlet {
private static final String ResultSet = null;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession();
String idPrenotazione = request.getParameter("idPrenotazione");
String email = request.getParameter("email");
int typeRoom = Integer.parseInt(request.getParameter("typeRoom"));;
String arrivalDate = request.getParameter("arrivalDate");
String departureDate = request.getParameter("departureDate");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// out.println("driver loaded");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Hotel?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root" ,"123456789");
out.println("Connect");
Statement st = con.createStatement();
// Statement stmt = con.createStatement();
out.println("connection successfull");
int total = 0;
PreparedStatement ps = con.prepareStatement( "SELECT COUNT(*) as total FROM reservation WHERE typeRoom = ? AND (? >= arrivaldate AND ? <= departuredate) OR (? >= arrivaldate AND ? <= departuredate)");
int c = 0;
ps.setInt(++c, typeRoom);
ps.setString(++c, arrivalDate);
ps.setString(++c, departureDate);
ps.setString(++c, arrivalDate);
ps.setString(++c, departureDate);
ResultSet rs = ps.executeQuery();
// ResultSet rs2 = stmt.executeQuery(check);
out.println("<h1> Stringa check eseguito </h1>");
if( total > 0) {
// response.sendRedirect("home.jsp");
response.sendRedirect("PrenotazioneNegata.jsp");
}
else {
st.executeUpdate("insert into reservation (email,typeRoom,arrivalDate,departureDate)values ('"+email+"','"+typeRoom+"','"+arrivalDate+"','"+departureDate+"')");
response.sendRedirect("PrenotazioneAvvenuta.jsp");
}
out.println("<h1> Registrazione Eseguita </h1>");
}catch(Exception e){
out.println("Errore." +e);
}
finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
A web container will typically route requests to the same servlet instance so it needs to be thread safe. Currently, the Database class provides a single connection, which would be used by concurrent requests so it is not thread safe.
Consider creating something like a ConnectionFactory class. For example:
public class ConnectionFactory {
public Connection getConnection() {
// move all the creation code from Database class to here
// create and return a new instance
}
}
Then modify the Database class to use the factory
public class Database {
private final ConnectionFactory connectionFactory;
public Database(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
// change to private and use the factory
private Connection getConnection() {
return connectionFactory.getConnection();
}
// example method to be used by servlet
public int getTotalReservations(int typeRoom, String arrivalDate, departureDate) {
// query related code currently in serlvet goes here...
}
}
And use the servlet lifecycle init() method to create the objects so the servlet can use it. For example:
public class Prenotation extends HttpServlet {
private Database database;
#Override
public void init() throws ServletException {
super.init();
this.database = new Database(new ConnectionFactory()); // no statics needed!
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
String idPrenotazione = request.getParameter("idPrenotazione");
String email = request.getParameter("email");
int typeRoom = Integer.parseInt(request.getParameter("typeRoom"));;
String arrivalDate = request.getParameter("arrivalDate");
String departureDate = request.getParameter("departureDate");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// use the method from `Database` which knows how to query the DB.
int totalReservations = database.getTotalReservations(typeRoom, arrivalDate, departureDate);
// more processing... and forward to the JSP
}
Note that Database now refers to both a USERS table and a RESERVATTIONS table. It would be better to split these into separate classes, such as UsersQuery and ReservationsQuery. They can both share the same ConnectionFactory instance.
See also:
single responsibility principle
inversion of control (injecting ConnectionFactory into Database)
servlet lifecycle
why static variables (or singletons) are/can be evil
DataSource (instead of the low level ConnectionFactory)

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;
}
}

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