My jsp code doesn't insert data in database - java

I am working on a JSP code and want to connect my page with mysql database and to insert name and email in database but it couldn't , I want to know why
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*, java.util.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP handle Page</title>
</head>
<body>
<%
String first_name = request.getParameter("user");
String email = request.getParameter("email");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","");
Statement st=conn.createStatement();
int i=st.executeUpdate("insert into info (name,email) values ('"+first_name+"','"+email+"')");
if(i!=0)
{
System.out.println("Data inserted");
}
else
{System.out.println("no");}
}
catch (Exception e)
{
e.printStackTrace();
}
%>
</body>
</html>

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:

when I click on logout link once then it doesn't go back but when I click on logout link twice then it goes back or previous page

I am doing code for logout using jsp in netbens8. My database is in mysql. I am trying to do code for logout hyperlink. I have done below code. But my problem is when I click on logout link once then it doesn't go back but when I click on logout link twice then it goes back or previous page.
I have created one link Click here to logout in filelist.jsp page . When i click on this link then it will redircets to logout.jsp page. I want to restrict user to go back. how to do? Am I getting it wrong somewhere in code?
This is my filelist.jsp page
<%--
Document : filelist
Created on : 22 Oct, 2019, 7:48:04 PM
Author : Z0009289
--%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Statement"%>
<%#page import="com.servlet.db.DB"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="bootstrap.css" rel="stylesheet" type="text/css">
<title>file_list Page</title>
</head>
<body>
Click here to logout
</body>
</html>
This is my logout.jsp page
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%
response.setHeader("Cache-Control","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
session = request.getSession();
String userid = "";
if ((session.getAttribute("userid") == null) || (session.getAttribute("userid") == "")) {
response.sendRedirect("login.jsp");
}
else{
userid = session.getAttribute("userid").toString();
}
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Log out Page</title>
</head>
<body>
<h2>Are you sure to logout???</h2>
<%
response.setHeader("Cache-Control","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
%>
<button type="submit">Logout</button>
</body>
</html>
This is my signout.jsp page
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%
response.setHeader("Cache-Control","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
%>
<%
session = request.getSession();
String uname = "";
if ((session.getAttribute("userid") == null) || (session.getAttribute("userid") == "")) {
response.sendRedirect("login.jsp");
}
else{
uname = session.getAttribute("userid").toString();
}
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sign out Page</title>
</head>
<body>
<%
response.setHeader("Cache-Control","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
if(session.getAttribute("userid") != null){
session.removeAttribute("userid");
request.getSession(false);
session.setAttribute("userid", null);
session.invalidate();
response.sendRedirect("login.jsp");
}
%>
</body>
</html>
This code snippets will works for you and will solve your error
Logout.jsp
<%# page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<head>
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
</head>
----//body tags
<%
session.invalidate();
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
%>
<jsp:forward page="index.jsp"></jsp:forward>
a href
<li>Logout</li>

Displaying null page on running my JSP

I'm trying to retrieve data from mysql. Upon giving the right input, data is not getting displayed. Code inside my jsp is not working too, but catch block executes correctly. Can you suggest me how to solve this problem?
Here is my code:
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.PreparedStatement"%>
<%# page import="java.util.*" %>
<%
Connection con=null;
PreparedStatement pst=null;
ResultSet rs=null;
String url = "jdbc:mysql://localhost:3306/check2allowMultiQueries=true";
%>
<html>
<head>
<link href="cprofile.css" rel="stylesheet" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form name="view" method="POST">
<%
String z = request.getParameter("code");
String query="Select * from check2 where CODE='"+z+"';";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/check 2", "root", "");
Statement st=con.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
%>
<table border="1">
<tr>
<td><%=rs.getString("NAME")%></td>>
<td><%=rs.getString("MEDIUM")%></td>
<td><%=rs.getString("CODE")%></td>
<td><%=rs.getString("ADD1")%></td>
<td><%=rs.getString("ADD2")%></td>
<td><%=rs.getString("CK")%></td>
<td><%=rs.getString("FK")%></td>
<td><%=rs.getString("BOARD")%></td>
</tr>
</table>
<%}
} catch(Exception e) {
out.println(e);
}
%>

How parsethrough jsonarray and store each column in textbox

<%# 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>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("JsonCreation.jsp",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>
i am trying to get data from db create jsonarray from resultset and use it to populate text box when a tables row is clicked so far i have displayed the data using alert and i am getting the exact data but i want to access column by column and populate corresponding text
<%#page import="org.json.JSONObject"%>
<%#page import="java.lang.Thread.State"%>
<%#page import="org.json.JSONArray "%>
<%#page import="org.json.JSONObject" %>
<%# page language="java" import="java.io.*,java.sql.*" 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>
<%
try{
Class.forName("com.mysql.jdbc.Driver");
String mySqlUrl = "jdbc:mysql://localhost:3306/permit";
Connection con = DriverManager.getConnection(mySqlUrl ,"root","moodle123");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from enterprisemaster where enterpriseId=1001");
JSONArray respJson = new JSONArray();
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
while (rs.next()) {
JSONObject obj = new JSONObject();
for (int i = 1; i < numColumns + 1; i++) {
String columnName = rsmd.getColumnName(i);
obj.put(columnName, rs.getString(columnName));
}
respJson.put(obj);
}
respJson.toString();
out.println(respJson);
}
catch(Exception e)
{
System.out.println(e);
}
%>
</body>
</html>
the out put from the alert box is this
<!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/json; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
[{"phone":"0471-2318922,0435-6203","fax":"0471- 2315893","website":"www.ksidc.org","enterpriseName":"KERALA STATE INDUSTRIAL DEVELOPMENT CORPORATION LIMITED","enterpriseId":"1001","factoryAddress":"","isActive":"1","category":"Financial Services","chairmanName":"Sri.T.K.A.Nair","administrativeDept":"Industries Department","incorporationDate":"21/07/1961","email":"ksidc#vsnl.com","incorporationAct":"Companies Act,1956","mdName":"Sri.Alkesh Kumar Sharma IAS","officeAddress":"T.C.XI/226,Keston Road,Kowdiar,Thriruvananthapuram-695003","activities":"Providing Promotional and financial assistance for industries in Kerala and acting as nodal/implementing/facilitating agency for mega projects"}]
</body>
</html>
Status:success
![alert output its content[1]
[1]: http://i.stack.imgur.com/EIlJw.png
$(document).ready(function(){
$.getJSON("Test.json",function(data){
$.each(data,function(key,value){
alert(data[key].activities);
alert(data[key].enterpriseName);
$('input').val(data[key].enterpriseName);
activities=data[key].activities;
console.log(value);
});
});
});

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>

Categories

Resources