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

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.

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

How to resolve Exception::java.security.AccessControlException: access denied in HttpServlet

I have created one Servlet class and I am trying to retrieve one record from Oracle 11g and also I am trying to use MySQL database but getting this exception: error ouput image
I am using below stuff:
WebServer: Tomcat9
JRE: 1.8
Databases: Oracle 11g,MySQL
Here is my servlet class:
public class EmployeeSearchApp extends HttpServlet{
private static final String EMP_SEARCH_DETAILS = "SELECT EMPMO,ENAME,JOB,SAL,EMPNO FROM EMP WHERE EMPNO=?";
private static final String url="jdbc:oracle:thin:#localhost:1521:orcl";
private static final String userName = "scott";
private static final String password = "tiger";
/*
* private static final String url="jdbc:mysql://localhost:3306/world"; private
* static final String userName = "ram"; private static final String password =
* "padma";
*/
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter pw=null;
int eno=0;
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
//Getting the print Writer Object
pw=res.getWriter();
//Setting the content type
res.setContentType("text/html");
//getting the parameter value
eno=Integer.parseInt(req.getParameter("eno"));
//JDBC code
//Registering JDBC driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//Class.forName("com.mysql.jdbc.Driver");
//Establishing the db connection
con=DriverManager.getConnection(url,userName,password);
//Preparing the Prepared Statement object
ps=con.prepareStatement(EMP_SEARCH_DETAILS);
//set the value into query param
ps.setInt(1, eno);
//execute the sql query
rs=ps.executeQuery();
//process the result set object
if(rs.next()) {
pw.println("<h1>EMPLOYEE DETAILS</h1>");
pw.println("<h1>Employee ID:"+rs.getInt(1)+"</h1>");
pw.println("<h1>Employee Name:"+rs.getString(2)+"</h1>");
pw.println("<h1>Employee Job:"+rs.getString(3)+"</h1>");
pw.println("<h1>Employee Sal:"+rs.getDouble(4)+"</h1>");
pw.println("<h1>Employee Dept NO:"+rs.getInt(5)+"</h1>");
}
}catch (SQLException se) {
se.printStackTrace();
pw.println("<h1 style='color:red;'>Internal Database problem</h1>");
}
catch (ClassNotFoundException cnf) {
cnf.printStackTrace();
pw.println("<h1 style='color:red;'>Internal problem</h1>");
}
catch (Exception e) {
e.printStackTrace();
pw.println("<h1 style='color:red;'>Internal problem</h1>");
}finally {
rs.close();
ps.close();
con.close();
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
doGet(req, res);
}
}
and the exception on console is as follows
Exception::java.security.AccessControlException: access denied
What could be the possible scenarios when one may get this exception?
And how do I resolve this?
Stack-trace shows that a security manager (i.e: java policies) is enabled, and restraining you from accessing system properties.
That means that your JVM/Tomcat has been configured to restrain web application privileges and actions. Only the administrator of the target platform can help you with that (either add sufficient authorizations in running policies, or give you an alternative method for what you aim for).

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 data from db, java servlet

Hi I'm writting java servlet which should get DVDs depends on which user is logged in. I have method
public List<Dvd> getDvdsByUserId(String user_id) throws SQLException {
List<Dvd> dvds = new ArrayList<Dvd>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM sedivyj_dvd where user_id = ?;");
preparedStatement.setString(1, user_id);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Dvd dvd = new Dvd();
dvd.setId(resultSet.getInt("id"));
dvd.setUser_id(resultSet.getString("user_id"));
dvd.setName(resultSet.getString("name"));
dvd.setBorrower(resultSet.getString("borrower"));
dvd.setMail(resultSet.getString("mail"));
dvd.setBorrow_date(resultSet.getString("borrow_date"));
dvd.setBorrow_until(resultSet.getString("borrow_until"));
dvds.add(dvd);
}
} catch (SQLException e) {
throw e;
} finally {
cleanUp(connection, preparedStatement);
}
return dvds;
}
and I don't know how to set up logged user id in servlet's doGet method:
dvds = this.dvdDao.getDvdsByUserId();
loginServlet
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserDao userDao;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
DbSettings dbSettings = new DbSettings();
dbSettings.setServer(config.getServletContext().getInitParameter("dbServer"));
dbSettings.setPort(Integer.valueOf(config.getServletContext().getInitParameter("dbPort")));
dbSettings.setUser(config.getServletContext().getInitParameter("dbUser"));
dbSettings.setPassword(config.getServletContext().getInitParameter("dbPassword"));
dbSettings.setDatabase(config.getServletContext().getInitParameter("dbDatabase"));
try {
this.userDao = new UserDao(dbSettings);
} catch (ClassNotFoundException e) {
throw new ServletException("Unable to initialize DB driver", e);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if (getLoggedUser(request, response) != null) {
response.sendRedirect("/list");
return;
}
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/login.jsp");
dispatcher.forward(request, response);
} catch (Exception e) {
getServletContext().log("error", e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if (getLoggedUser(request, response) != null) {
response.sendRedirect("/list");
return;
}
String nickname = request.getParameter("nickname");
String password = request.getParameter("password");
if (nickname != null && password != null) {
User user = userDao.getByLogin(nickname);
if (user != null && UserUtil.checkLogin(user, password)) {
HttpSession session = request.getSession(true);
Long userId = user.getId();
session.setAttribute("userId", userId);
session.setAttribute("loggedUser", user);
request.getSession().setAttribute("nickname", nickname);
response.sendRedirect("/list");
} else {
request.setAttribute("message", "Login se nepovedl.");
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/login.jsp");
dispatcher.forward(request, response);
}
} else {
response.sendRedirect("/login");
}
} catch (Exception e) {
getServletContext().log("error", e);
}
}
public User getLoggedUser(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession(true);
User user = (User) session.getAttribute("loggedUser");
return user;
}
}
Does anybody have an idea please?
Get Logged User Id In Servlet Using Session.
HttpSession session=request.getSession(true);
session.setAttribute("user", userLoggedId);
Later You can retrieve Session Data :
HttpSession session=request.getSession(true);
String userId=(String)session.getAttribute("user");
According to my understand of your requirement first you validate whether username and password are matching then you pass the control to the servlet so on the request set the userid .Then you can acquire the userid in the doGet() method using the request.getParameter() method.
This can be done in many ways.
I think you are using form because in servlet you are calling doget().So while calling the servlet from the form pass the userid also and in servlet you can use userid=request.getParameter("user");
The other way is to keep the user in session
After the login if you are calling any servlet or jsp page then keep the user there in session like this way
session.setAttribute("username","username");
and in the servlet you can retrieve by using
session.getAttribute("username");

Categories