Trying to check MySQL database with java, jsp - java

I am trying to print some data from my database in Mysql using some classes in java and jsp. It's my first time doing this. I googled a lot but nothing helped me. Here is my code:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<form action="DB_results.jsp">
<input type = "submit" value = "Database">
</form>
</body>
</html>
Draw.java
package DB_draw;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Draw {
ResultSet myRs;
public ResultSet getMyRs() {
return myRs;
}
public void setMyRs() {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tst","root","");
Statement myStmt = myConn.createStatement();
this.myRs = myStmt.executeQuery("select * from tst.people");
while (this.myRs.next())
{
System.out.println(this.myRs.getString("onoma") + " " + this.myRs.getString("epitheto") + " " + this.myRs.getInt("id"));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
DB_results.jsp
<%#page import="java.sql.ResultSet"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.io.*,java.util.*,java.sql.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%# page import="DB_draw.*" %>
<jsp:useBean id="DB_draw" class="DB_draw.Draw" scope="session" />
<jsp:setProperty name="DB_draw" property="*"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Database</title>
</head>
<body style="background-color:black">
<div style = "color:yellow; font-family:fantasy; font-size:30px">
<%
ResultSet myRs = DB_draw.getMyRs();
if(myRs == null) out.println("Problem");
else
while(myRs.next())
{
out.println(myRs.getString("onoma") + " " + myRs.getString("epitheto") + " " + myRs.getInt("id"));
}
%>
</div>
</body>
</html>
The Problem is that when i try to print the results in DB_results.jsp using variable myRs, myRs == NULL. Why is this happening? I'm using Tomcat-Apache 8.0.

You never call setMyRS(). And even if you did, setMyRS() iterates through the resultset, so myRs.next() would always return false in the JSP.

Related

Can not login after register jsp db

I have a problem with a login on my "website" i always have failed login despite this i write good login and password. It gets the value from data base name "register" and check it. And I have values in "register" in database and I normally write it on my login page and something is going wrong cause it redirecting me on "loginfail.jsp"This is my code:
<%# page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<%# page language="java" %>
<%# page import="java.sql.*" %>
<%# page import="java.sql.DriverManager.*" %>
<%
PreparedStatement ps;
Connection conn;
ResultSet rs= null;
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
conn=DriverManager.getConnection("jdbc:derby://localhost:1527/onlineshop","root","root");
Statement st=conn.createStatement();
%>
<%
boolean flag = false;
String LOGIN = request.getParameter ("LOGIN");
String PASSWORD = request.getParameter ("PASSWORD");
%>
<%
String sql = "SELECT LOGIN from REGISTER where LOGIN=? And PASSWORD =?";
try {
ps = conn.prepareStatement(sql);
ps.setString (7,LOGIN);
ps.setString (8,PASSWORD);
rs = ps.executeQuery ();
if (rs.next ()) {
out.println (rs.getString ("LOGIN"));
flag = true;
session.setAttribute("ULOGIN", rs.getString ("LOGIN"));
} else {
request.setAttribute("err", "user name or password error!");
}
rs.close ();
ps.close ();
conn.close ();
} catch (Exception e) {
out.println (e);
}
%>
<%
if (flag) {
%>
<jsp:forward page="loginsucc.jsp" />
<%
}
else {
%>
<jsp:forward page="loginfail.jsp"/>
<%
}
%>
</body>
</html>
The problem in your code is because of using the wrong index in the setString.
Replace
ps.setString (7,LOGIN);
ps.setString (8,PASSWORD);
with
ps.setString (1,LOGIN);
ps.setString (2,PASSWORD);
Check this for an example of using Prepared Statements. Check this for documentation.
[Update]
The rs.next () is returning false in your code. You can validate the following working example:
register.jsp:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<%
boolean flag = true;
if (flag) {
%>
<jsp:forward page="loginsucc.jsp" />
<%
} else {
%>
<jsp:forward page="loginfail.jsp" />
<%
}
%>
</body>
</html>
loginsucc.jsp
<html>
<head>
<title>Insert title here</title>
</head>
<body>
Login successful
</body>
</html>
Output:

SAP BO login using custom.jsp

I'm using custom.jsp in order to avoid the login screen and load the home screen directly, but still it's asking for login credentials after restarting the tomcat. The path of the custom.jsp file is "SAP BusinessObjects\tomcat\webapps\BOE\WEB-INF\eclipse\plugins\webpath.InfoView\web"
I don't know what I'm missing here and I'm new to this. Below is my jsp code. Thanks.
<%# page import="com.crystaldecisions.sdk.exception.SDKException" %>
<%# page import="com.crystaldecisions.sdk.framework.*" %>
<%# page import="com.crystaldecisions.sdk.occa.infostore.*" %>
<%# page import="com.crystaldecisions.sdk.occa.security.*"%>
<%# page import="java.net.*"%>
<%# page import="com.crystaldecisions.enterprise.*"%>
<%# page import="com.crystaldecisions.sdk.plugin.admin.*"%>
<%# page import="java.sql.*"%>
<%# page import="com.businessobjects.webutil.Encoder" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%
IEnterpriseSession enterpriseSession;
final String BO_CMS_NAME = "BI98svr";
final String BO_AUTH_TYPE = "secEnterprise";
final String BO_USERNAME = "user121";
final String BO_PASSWORD = "pass121";
ILogonTokenMgr logonTokenMgr;
String defaultToken = "";
boolean loggedIn = true;
try {
enterpriseSession =
CrystalEnterprise.getSessionMgr().logon(BO_USERNAME,BO_PASSWORD,
BO_CMS_NAME,BO_AUTH_TYPE);
logonTokenMgr = enterpriseSession.getLogonTokenMgr();
defaultToken = logonTokenMgr.createWCAToken("", 20, 1);
response.sendRedirect("http://"+BO_CMS_NAME+":8080/BOE/BI/logon/start.do?ivsLogonToken="+Encoder.encodeURL(defaultToken));
}
catch (Exception error)
{
loggedIn = false;
out.println(error);
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
</body>
</html>

HomeControllers not rendering

I'm using SpringToolSuite with Java and I'm trying to render an index.jsp page onto my localhost:8080, but my Localhost is only going to the Whitelabel error page again & again. I guess it doesn't seem to be recognizing my Homecontroller.java file. The servers are running and have been refreshed. My files are correct. I see no issues anywhere else. What could be wrong that I'm not seeing? How can I render my page?
HomeController.java :
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/your_server")
public class HomeController {
#RequestMapping("")
public String index(HttpSession session) {
if (session.isNew()) {
session.setAttribute("counter", 0);
}
Integer count = (Integer) session.getAttribute("counter");
count += 1;
session.setAttribute("counter", count);
return "index.jsp";
}
#RequestMapping("/counter")
public String showCounter(HttpSession session, Model model) {
if (session.isNew()) {
session.setAttribute("counter", 0);
}
model.addAttribute("counter", session.getAttribute("counter"));
return "counter.jsp";
}
#RequestMapping("/reset")
public String resetCounter(HttpSession session) {
session.invalidate();
return "forward:/";
}
}
CounterApplication.java:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class CounterApplication {
public static void main(String[] args) {
SpringApplication.run(CounterApplication.class, args);
}
}
index.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome! Want to count some stuff?</title>
</head>
<body>
How many times has this page been visited?
<p>Oh, hi.</p>
</body>
</html>
<%# taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<c:out value="${2+2}"/>
counter.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>How many times are we going to go through this?!</title>
</head>
<body>
<c:out value="${ counter }" />
Go back.
Reset the counter.
</body>
</html>

How to retrieve image from mysql db and show it inside <td> and <img> tag in HTML?

How to retrieve image from mysql db and show it inside tag in HTML and that img tag should be placed inside ? Here s my code:
It displays only the image . Its not showing any content other than image.
Thanks in advance.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%# page import="java.io.*"%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%# page import="java.text.*"%>
<%# page import="javax.servlet.*"%>
<%# page import="javax.servlet.http.*"%>
<%# page import="javax.servlet.http.HttpSession"%>
<%# page language="java"%>
<%# page session="true"%>
<%
try{
//PrintWriter out=response.getWriter();
out.println("Retrieve Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "db";
String userName = "root";
String password = "root";
Connection con = null;
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement st = con.createStatement();
%>
<table border='1'>
<tr>
<td>Name:</td><td>
</td>My Name</td>
</tr>
<tr>
<td>Image:</td>
<td width=10px;>
<%
PreparedStatement pre1 = con.prepareStatement("select * from image where id="+8);
ResultSet rs1=pre1.executeQuery();
while(rs1.next())
{byte[] bytearray1 = new byte[4096];
int size1=0;
InputStream sImage1;
sImage1 = rs1.getBinaryStream(2);
response.reset();
response.setContentType("image/jpeg");
response.addHeader("Content-Disposition","filename=logo.jpg");
while((size1=sImage1.read(bytearray1))!= -1 )
{
response.getOutputStream().write(bytearray1,0,size1);
}
response.flushBuffer();
sImage1.close();
rs1.close();
}
out.println("Retrieved Successfully!");
pre.close();
con.close();
}
catch (Exception e){
out.println(e.getMessage());
}
%>
</td></tr>
</table>
</body>
</html>
Images are loaded as separate requests to the request that loaded the html. As such you need to:
establish a URL encoding scheme that you use when specifying the src of the img element.
map a servlet (or similar) to that URL. The servlet loads the image based on the parameters of the URL returning that image in its response.
I found out.
r.jsp:-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table border=2>
<tr><th>DISPLAYING IMAGE</th></tr>
<tr><td>hi</td></tr>
<tr><td>
<img src="retrieve.jsp" width=130 height=130>
</td></tr>
</table>
</body>
</html>
retrieve.jsp:-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<%# page import="java.io.*"%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%# page import="java.text.*"%>
<%# page import="javax.servlet.*"%>
<%# page import="javax.servlet.http.*"%>
<%# page import="javax.servlet.http.HttpSession"%>
<%# page language="java"%>
<%# page session="true"%>
<%
try{
//PrintWriter out=response.getWriter();
out.println("Retrieve Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "db";
String userName = "root";
String password = "root";
Connection con = null;
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement st = con.createStatement();
PreparedStatement pre1 = con.prepareStatement("select * from image where id="+8);
ResultSet rs1=pre1.executeQuery();
while(rs1.next())
{byte[] bytearray1 = new byte[4096];
int size1=0;
InputStream sImage1;
sImage1 = rs1.getBinaryStream(2);
response.reset();
response.setContentType("image/jpeg");
response.addHeader("Content-Disposition","filename=logo.jpg");
while((size1=sImage1.read(bytearray1))!= -1 )
{
response.getOutputStream().write(bytearray1,0,size1);
}
response.flushBuffer();
sImage1.close();
rs1.close();
}
pre.close();
con.close();
}
catch (Exception e){
out.println(e.getMessage());
}
%>
</body>
</html>

Why won't print in jsp?

The code below doesn't print in jsp (the out.println in while{} ) but it works like a charm in Java program. Can you please explain me why won't print in jsp and what should I change in code? Thank you!
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.io.BufferedReader" %>
<%# page import="java.io.IOException" %>
<%# page import="java.io.InputStreamReader" %>
<%# page import="java.io.PrintWriter" %>
<%# page import="javax.servlet.ServletException" %>
<%# page import="javax.servlet.http.HttpServlet" %>
<%# page import="javax.servlet.http.HttpServletRequest" %>
<%# page import="javax.servlet.http.HttpServletResponse" %>
<%# page import="java.net.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Test
<%try{
URL url = new URL("http://gesi-ro-test.banat.enelro:8010/dynamic/gesi/ri/elab/endcallrequest/wind.ser?id=008201dfa306f4a6&es=&is=2011/04/20%2013:09:46.593&rt=RE");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine = "";
while ((inputLine = in.readLine()) != null)
{
out.println(inputLine);
}
in.close();
}catch(Exception e){
out.println(e);
}%>
</body>
</html>
Check your url again. I tried your code with another site and it works:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="java.io.BufferedReader" %>
<%# page import="java.io.IOException" %>
<%# page import="java.io.InputStreamReader" %>
<%# page import="java.io.PrintWriter" %>
<%# page import="javax.servlet.ServletException" %>
<%# page import="javax.servlet.http.HttpServlet" %>
<%# page import="javax.servlet.http.HttpServletRequest" %>
<%# page import="javax.servlet.http.HttpServletResponse" %>
<%# page import="java.net.*" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test</title>
</head>
<body>
<%
URL url;
try {
url = new URL("http://www.w3schools.com/xml/note.xml");
BufferedReader in = new BufferedReader(new InputStreamReader(
url.openStream()));
String inputLine = "";
while ((inputLine = in.readLine()) != null) {
%>
<c:out value="<%=inputLine%>"/>
<%
}
in.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
%>
</body>
</html>
Personally, I dont like to put a lot of "if", "while" command in the jsp file (it will makes your system later become a big mess), so, try to handle eveything in your business logic and then send the result to the jsp as a attribute
This URL returns XML markup and it is not displayed. You have to add <pre> </pre> tag to show XML markup.
out.println("<pre>");
String inputLine = "";
while ((inputLine = in.readLine()) != null)
{
out.println(inputLine);
}
out.println("</pre>");
in.close();
You must have to use JSTL's <import/> instead of Java code in JSPs.
<c:import var="xmlData" url="http://your.url" />
<c:out var="${xmlData}"/>

Categories

Resources