i've created this servlet to connect to database and retrieve data then output them in JSON format.
this is the servlet :
public class ConnectServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("application/json");
PrintWriter out=res.getWriter();
JSONArray relatedWorkordersArray = new JSONArray();
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/users","root","");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from user");
JSONObject jObj=new JSONObject();
st = (Statement) con.createStatement();
rs = (ResultSet) st.executeQuery("select * from user");
while (rs.next()) {
String nom = rs.getString("nom");
String prenom = rs.getString("prenom");
int age = rs.getInt("age");
JSONObject Object = new JSONObject();
Object.put("nom", nom);
Object.put("prenom", prenom);
Object.put("age", age);
relatedWorkordersArray.put(Object);
}
jObj.put("data",relatedWorkordersArray.toString());
jObj.put("Success", true);
rs.close ();
st.close ();
con.close();
//print JSON object
out.print(jObj);
Now, In my sencha touch project i've created a JSON-P STORE and i've putted in his url the name of this servlet : ConnectServlet.java but i have an error: unable to load data using the supplied configuration. open in browser : ConnectServlet.java
how can I do to make this proxy using the servlet to get data from database?
you may find your solution here.click here
Related
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).
I use an MYSQL Blob to store an Image inside a Database. Now I want to show the image in my IONIC application in which I also uploaded it.
How it works and how can I store it inside an Object?
You can find my code here:
Java Class
public JSONObject getItems(String email) throws SQLException, ClassNotFoundException, IOException {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
Connection conn = new MYSQLAccess().getConnection();
String sql = "SQL String";
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setString(1, email);
ResultSet rs = pstm.executeQuery();
while (rs.next()) {
jsonObject.put("1", rs.getBlob("1"));
jsonObject.put("2",rs.getInt("2"));
jsonObject.put("3", rs.getString("3"));
jsonObject.put("4", rs.getString("4"));
jsonArray.add(performanceCarsJsonObject);
}
jsonObject = new JSONObject();
jsonObject.put("array", jsonArray);
conn.close();
return jsonObject;
}
TypeScript Ionic/ Angualar
getPerformanceCars() {
let params = {"email": this.user.getEmail()};
this.cars.performanceCars(params).then(data => {
this._List = data;
this._List = this._List.value.icons;
this.itemList = this._List;
});
}
Ionic HTML
<ion-list>
<ion-item-sliding *ngFor="let items of itemList">
<button ion-item (click)="openItem(item)">
<ion-avatar item-start>
<img [src]="items.img" />
</ion-avatar>
<h2>{{ items.email }}</h2>
<p>{{ items.values }}</p>
<ion-note item-end *ngIf="items.note">{{ cars.note }}</ion-note>
</button>
</ion-item-sliding>
</ion-list>
The preview of the photo within the IONIC Input Uploader uses the following HTML code.
<div class="profile-image" style="background-image: url("data:image/jpeg;base64,DATA;);"></div>
I hope you can help me, to fix my problem.
Solution
I fixed the problems by creating two new methods. In the first step, I create the getItemBlob Method to extract the Blob outside the database. In the next step, I create the method getItemImage in the controller class. These methods search the correct blob inside the database by the itemID convert the Blob in an InputStream and in the last step inside a ServletOutputStream.
In the HTML part, I used a normal img Tag and mapped the server hostname, port and the getItemImage method together to display the image.
Java Class (Item Services)
public Blob getItemBlob(String id) throws SQLException{
Blob image = null;
Connection conn = new MYSQLAccess().getConnection();
String sql = "SELECT ITEMDATA FROM OWNITEM WHERE OWNITEMID = ? AND ACTIVE = 1";
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setString(1, id);
ResultSet rs = pstm.executeQuery();
while (rs.next()) {
image = rs.getBlob("ITEMDATA");
}
conn.close();
return image;
}
Java Class (Item Controller)
#ResponseBody
#CrossOrigin(origins = "http://localhost:8100")
#RequestMapping(value = "/getItemImage")
public void getItemImage(#RequestParam("id") String id, HttpServletResponse response) throws IOException, SQLException {
ServletOutputStream out = response.getOutputStream();
ItemServices myItemServices = new ItemServices();
Blob image = myItemServices.getItemBlob(id);
response.setContentType("image/jpg");
InputStream in = image.getBinaryStream();
int length = (int)image.length();
int bufferSize = 1920;
byte[] buffer = new byte[bufferSize];
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.flush();
}
Java Class (Subscriber Controller)
#SuppressWarnings("unchecked")
public JSONObject getSubscribersItems(String email) throws SQLException, ClassNotFoundException {
JSONObject subscribersItemsJsonObject = new JSONObject();
JSONArray subscribersItemsJsonArray = new JSONArray();
ArrayList<String> subscribersArrayList = this.getSubscriber(email);
Connection conn = new MYSQLAccess().getConnection();
String sql = "SELECT T1.OWNITEMID,T1.ITEMNAME,T2.USERNAME,T2.COUNTRY FROM OWNITEM T1,CUSTOMER T2 WHERE T1.EMAIL = T2.EMAIL AND T1.EMAIL = ? AND T1.ITEMDATA != 'NULL' AND T2.ACTIVE = 1";
PreparedStatement pstm = conn.prepareStatement(sql);
for (int i = 0; i < subscribersArrayList.size(); i++) {
pstm.setString(1, subscribersArrayList.get(i));
ResultSet rs = pstm.executeQuery();
while (rs.next()) {
subscribersItemsJsonObject = new JSONObject();
subscribersItemsJsonObject.put("itemID", rs.getInt("OWNITEMID"));
subscribersItemsJsonObject.put("itemName", rs.getString("ITEMNAME"));
subscribersItemsJsonObject.put("username", rs.getString("USERNAME"));
subscribersItemsJsonObject.put("country", rs.getString("COUNTRY"));
subscribersItemsJsonArray.add(subscribersItemsJsonObject);
}
}
subscribersItemsJsonObject = new JSONObject();
subscribersItemsJsonObject.put("items", subscribersItemsJsonArray);
conn.close();
return subscribersItemsJsonObject;
}
IONIC HTML
<ion-list>
<ion-item-sliding *ngFor="let items of subscriberItemsItemList">
<button ion-item (click)="openItems(items)">
<ion-avatar item-start>
<img src="{{ itemImageUrl }}/getItemImage?id={{ cars.itemID }}" />
</ion-avatar>
<h2>{{ items.username }}</h2>
<p>{{ items.country }}</p>
<ion-note item-end *ngIf="items.note">{{ items.note }}</ion-note>
</button>
</ion-item-sliding>
</ion-list>
IONIC TypeScript/ Angular
getDesignCars() {
let params = {"email": this.user.getEmail()};
this.cars.homeCars(params).then(data => {
this._subscriberCarsList = data;
this._subscriberCarsList = this._subscriberCarsList.value.cars;
this.subscriberCarsItemList = this._subscriberCarsList;
});
}
i'm trying to use jdbc connection pool, for that i create IntialContext obj and datasource obj, and give "dsjndi" as parameter of lookup method of initialcontext, but when i run my project project it shows ""Name [dsjndi] is not bound in this Context. Unable to find [dsjndi].""
What is the problem can anyone guide me?
Connection con = null;
Statement st = null;
ResultSet rs = null;
ResultSetMetaData rsmd = null;
public void process(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
//general settings
//get print Writer obj
PrintWriter pw = res.getWriter();
//set content type
res.setContentType("text/html");
//read form data
String tableName = req.getParameter("table");
try
{
//get con obj from jdbc con pool
con = makeConnection();
//create Statement obj
st = con.createStatement();
//execute query
rs = st.executeQuery("select * form" +tableName);
//use metadata obj to get db vlaues along with the col names
rsmd = rs.getMetaData();
int cnt = rsmd.getColumnCount();
pw.println("<hmtl><body bgcolor='#ffffa9'>");
pw.println("<center><h3>the details of the table" +tableName);
pw.println("<br><br><table cellsapcing='1' bgcolor='#00ff00'>");
pw.println("<tr bgcolor='#ffffa9'>");
//pritnt col names
for(int col=1;col<=cnt;col++)
{
pw.println("<th>" +rsmd.getColumnLabel(col)+ "  ");
}
pw.println("</tr>");
//print col values
while(rs.next())
{
pw.println("<tr bgcolor='#ffffa9'>");
for(int i=1;i<=cnt;i++)
{
pw.println("<td>" +rs.getString(i)+ " </td>");
}
pw.println("</td>");
}//while
pw.println("<table><br/>");
pw.println("<b>to view another table</b><ahref='index.html'>click here</a>");
pw.println("</body></html>");
}//try
catch(Exception e)
{
e.printStackTrace();
}
}
private Connection makeConnection()
{
Connection con = null;
try
{
//get IntialConetext
InitialContext ic = new InitialContext();
//get data sourse obj
DataSource ds = (DataSource) ic.lookup("DsJndi");
//get jdbc con obj from con pool
con = ds.getConnection();
}//try
catch(Exception e)
{
e.printStackTrace();
}
return con;
}//make Connection
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
process(req,res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
process(req,res);
}
}
I want to pass "name" form f.jsp to class s.java then inside s.java class i need to retrieve the age of received name from database and send the age to another jsp file..
anyone have idea to write code for that?
f.jsp
String name = (String) request.getAttribute("myname"); //get name from servlet
Student s= new Student();
String grade = s.getStudentGrade(name);
s.java
public String getStudentGrade(String name)
{
Connection con = null;
PreparedStatement s = null;
String g;
try {
con = DBconn.getConnection();
String query = "SELECT grade FROM REGISTRATION where Username="+name;
s = con.prepareStatement(query);
s.setString(1,""+this.getgrade());
ResultSet result = s.executeQuery();
while( result.next())
{
g=result.getString("grade");
}
return g;
}
catch(Exception e) { e.printStackTrace(); return null; }
}
when I run this code always return null..can any one help me
hint: my Db is
Username password grade
Ali 1234 3
I need when getStudentGraed() receive name, then retrieve the grade of that name
For PreparedStatement you have to use wildcard ? instead of concatenating with query..
1:- You have to extend HttpServlet.
2:- You have to define the #WebServlet annotation or you have to declare your servlet in web.xml file.
#WebServlet("/getGrade")
public class getStudentGrade extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Connection con = null;
PreparedStatement s = null;
String g;
try {
con = DBconn.getConnection();
String query = "SELECT grade FROM REGISTRATION where Username=?";
s = con.prepareStatement(query);
s.setString(1, name);
ResultSet result = s.executeQuery();
while( result.next()){
g=result.getString("grade");
}
req.setAttribute("grade",g);
req.getRequestDispatcher(your Jsp Page path).forward(req,resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req,resp);
}
}
In JSP page you can get it like
<p>Grade : ${grade}</p>
To my understand you need to access java class from jsp. I think below example will help you.
public class Student {
private String name;
public String getGrade() {
String grade = null;
con = DBconn.getConnection();
String query = "SELECT grade FROM REGISTRATION where Username=?";
s = con.prepareStatement(query);
s.setString(1,this.name);
ResultSet result = s.executeQuery();
while( result.next()){
grade=result.getString("grade");}
return grade;
}
public void setName(String name) {
this.name = name;
}
}
In your servlet :
<%
package_name.Student c = new package_name.Student();
c.setName("John");
request.setAttribute("attribute", c);
%>
Access inside jsp :
${requestScope["attribute"].grade}
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.