I'm new to Java and I'm trying to create a project in myEclipse latest version and I'm using the following code:
<%# page language="java" import="java.util.*,java.sql.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'blockmails.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<%
try
{
String flag="false";
String ctr="false";
String mailto=session.getAttribute("mailto").toString();
String sub=session.getAttribute("subject").toString();
String mess=session.getAttribute("message").toString();
String user=request.getParameter("user");
System.out.println(mailto+" "+sub+" "+mess+" "+user);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","email","email");
Statement pst=con.createStatement();
Statement pst1=con.createStatement();
//System.out.println("pst1:"+pst1);
//System.out.println("pst2:"+pst2);
Statement st=con.createStatement();
Statement srs=con.createStatement();
Statement st3=con.createStatement();
//out.println("connection estblished");
ResultSet rs=pst.executeQuery("select * from Encryptedwords");
ResultSet rs2=st3.executeQuery("select * from swords");
while(rs.next()&& rs2.next())
{
String query="select * from MAILS where subject like '%"+rs.getString(1)+"%' or subject like '%"+rs2.getString(1)+"%' or message like '%"+rs.getString(1)+"%' or message like '%"+rs2.getString(1)+"%' and mailfrom='"+user+"'";
ResultSet rs1=st.executeQuery(query);
ResultSet rsr1=srs.executeQuery("select * from MAILS where subject like '%"+rs.getString(2)+"%' or message like '%"+rs.getString(2)+"%' and mailfrom='"+user+"'");
if(rs1.next()||rsr1.next())
{
flag="true";
break;
}
else
flag="false";
}
if(flag.equals("true"))
{
//out.println("suspicious");
String to=user;
String mailfrom="GNITS#suspicious mail.com";
String subject="mail-daemon";
String message="The mail you had sent consists of suspicious information";
PreparedStatement pst2=con.prepareStatement("insert into inbox values(?,?,?,?)");
pst2.setString(1,to);
pst2.setString(2,mailfrom);
pst2.setString(3,subject);
pst2.setString(4,message);
int d=pst2.executeUpdate();
PreparedStatement pst3=con.prepareStatement("insert into blocklist values(?,?,?,?)");
pst3.setString(1,mailto);
pst3.setString(2,user);
pst3.setString(3,sub);
pst3.setString(4,mess);
int r=pst3.executeUpdate();
System.out.println("r is:"+d);
if(d>0)
{
Statement st2=con.createStatement();
st2.executeUpdate("delete from mails");
response.sendRedirect("inbox.jsp?user="+to);
}
}
else
{
Statement pss=con.createStatement();
ResultSet sr=pss.executeQuery("select * from alertwords");
//out.println(sr);
while(sr.next())
{
Statement ss=con.createStatement();
String query2="select * from MAILS where subject like '%"+sr.getString(1)+"%' or message like '%"+sr.getString(1)+"%' and mailfrom='"+user+"'";
out.println("hello");
out.println("query:"+query2);
ResultSet sr1=ss.executeQuery(query2);
out.println(sr1);
if(sr1.next())
{
ctr="true";
break;
}
else
ctr="false";
}
if(ctr.equals("true"))
{
/*System.out.println("suspicious");
String to=user;
String mailfrom="krest#gmail.com";
String subject="mail-daemon";
String message="The mail you had sent consists of suspicious information";*/
/*PreparedStatement pss1=con.prepareStatement("insert into inbox values(?,?,?,?)");
pss1.setString(1,mailto);
pss1.setString(2,mailfrom);
pss1.setString(3,subject);
pss1.setString(4,message);
int d1=pss1.executeUpdate();*/
PreparedStatement pss4=con.prepareStatement("insert into inbox values(?,?,?,?)");
pss4.setString(1,mailto);
pss4.setString(2,user);
pss4.setString(3,sub);
pss4.setString(4,mess);
int rk=pss4.executeUpdate();
System.out.println("r is:"+rk);
PreparedStatement pss3=con.prepareStatement("insert into alertlist values(?,?,?,?)");
pss3.setString(1,mailto);
pss3.setString(2,user);
pss3.setString(3,sub);
pss3.setString(4,mess);
int r1=pss3.executeUpdate();
/*System.out.println("r is:"+d1);
if(d1>0)
{
Statement st3=con.createStatement();
st3.executeUpdate("delete from mails");
response.sendRedirect("inbox.jsp?user="+to);
}*/
}
else
System.out.println("not suspicious");
PreparedStatement pss2=con.prepareStatement("insert into inbox values(?,?,?,?)");
pss2.setString(1,mailto);
pss2.setString(2,user);
pss2.setString(3,sub);
pss2.setString(4,mess);
int r=pss2.executeUpdate();
System.out.println("r is:"+r);
if(r>0)
{
Statement st4=con.createStatement();
st4.executeUpdate("delete from mails");
response.sendRedirect("user.jsp?user="+user);
//out.println("mail sent successfully");
}
}
}
catch(Exception e){}
%>
</html>
I'm trying to create a JSP page. But the problem is, when I try to run the code, it gives a blank page. No errors or anything. Just blank. I'm very confused and I have been at this for weeks now, with no progress at all. Any help would be greatly appreciated.
Related
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>
I am unable to get a piece of code in the following JSP code ( commented as d1, d2, d3, d4):
<%#page import="java.sql.*" errorPage="/MyError.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LoginProcess</title>
</head>
<body>
<%
Connection conn = null;
String uname = request.getParameter("uname");
String pass = request.getParameter("pass");
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e)
{
out.println("Error(class):"+e);
}
try
{
conn = DriverManager.getConnection("jdbc:mysql://localhost/studentdb","root","mysql");
PreparedStatement stmt = conn.prepareStatement("select * from studentdb.userdetails where uname=? and pass=?");
stmt.setString(1, uname);
stmt.setString(2, pass);
ResultSet rs = stmt.executeQuery();
if(!rs.next())
{
out.println("username or password is incorrect");
%> <%--d1--%>
Try Again:<%#include file="Login.html" %> <%--d2--%>
</body> <%--d3--%>
</html> <%--d4--%>
<%
return;
} //if
} //try-sql
catch(SQLException e)
{
out.println("Error(SQL):" + e);
}
finally
{
conn.close();
}
%>
This is Home Page<br>
Welcome,<b> <%= uname%></b>
</body>
the following are appearing in an if block which I am not getting why and how do they work , I know the meaning of <%#include file="Login.jsp"> and selective tags but not I am getting how are they workign here.
%> <%--d1--%>
Try Again:<%#include file="Login.html" %> <%--d2--%>
</body> <%--d3--%>
</html> <%--d4--%>
<%
(the body and html tags are not appearing in the above piece of code).
Instead of if(!rs.next()), try using if(rs.isBeforeFirst()). If rs.isBeforeFirst() is false, then you have no records.
I have a problem when I try to enter duplicate entries as you can see in the servlet below. The problem is that tomcat shows the duplicate error but the servlet doesn't redirect to the desired error page (dup_organism.jsp). However I have no problem when I enter a new record and redirect to another page, while the code is pretty much the same.
I have this servlet:
package package_ergasia;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddOrganism extends HttpServlet
{
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
Connection connection= null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "ergasia";
String user = "root";
String password = "password";
String org_id = request.getParameter("id");
String oname = request.getParameter("oname");
try {
connection = DriverManager.getConnection(url + dbName, user, password);
Statement statement = connection.createStatement() ;
ResultSet resultset = statement.executeQuery("SELECT * FROM organism") ;
while(resultset.next()){
if(resultset.getString("org_id").equalsIgnoreCase(org_id)){
String contextPath= "http://localhost:8084/secured";
response.sendRedirect(response.encodeRedirectURL(contextPath + "/dup_organism.jsp"));
}
else{
PreparedStatement ps = connection.prepareStatement("INSERT INTO organism (org_id,organismName) VALUES (?,?)");
ps.setString(1, org_id);
ps.setString(2, oname);
ps.executeUpdate();
String contextPath= "http://localhost:8084/secured";
response.sendRedirect(response.encodeRedirectURL(contextPath + "/all_organisms.jsp"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public String getServletInfo() {
return "info";
}
}
this is the error page dup_organism.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="../CSS/mystyle.css">
<title>Duplicate entry</title>
</head>
<body>
<h1>Error</h1>
<% String org_id = request.getParameter("org_id"); %>
<h2><div align="center">
<br><br><br>
Duplicate data <br> #Organism Id:
<% out.println(org_id); %>
</div></h2>
</body>
</html>
browser shows nothing (still on servlet page) and tomcat shows the following error: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry '02' for key 'PRIMARY'
The problem why your getting null is that your using response.sendRedirect which creates a new instance of request and response object. you can do any one of the following:
Replace it with request.getRequestDispatcher(url);
Set the Org_id in the session object and retrieve it in the jsp.
I'm trying to insert my data into database using Textbox, Sometime it inserts the data in only using Internet Explorer but not in Mozilla firefox.
It's strange.....
My data sometime gets uploaded but only using Internet Explorer and sometimes it stops working. Please help what's that mean?
Here is my code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" >
$(function() {
$(".update_button").click(function() {
var boxval = $("#content").val();
var dataString = 'content='+ boxval;
if(boxval=='')
{
alert("Please Enter Some Text");
}
else
{
$.ajax({
type: "POST",
url: "demo.jsp",
data: dataString,
cache: false
});
}
});
});
</script>
</head>
<body>
<div>
<form method="post" name="form" action="">
<h3>What are you doing?</h3>
<textarea name="content" id="content" ></textarea><br />
<input type="submit" value="Update" name="submit" class="update_button" />
</form>
</div>
<%
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/poststatus", "root", "1234");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from messages order by msg_id desc");
while(rs.next()){
String msg=rs.getString("msg");
%>
<ol id="update" class="timeline"><%=msg %></ol>
<%
}
}
catch(Exception e){
e.printStackTrace();
}
%>
</body>
</html>
and here is my demo.jsp:
<%# page import="java.sql.*" errorPage="" %>
<%
String content=request.getParameter("content");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/poststatus", "root", "1234");
Statement st=con.createStatement();
int i=st.executeUpdate("insert into messages(msg) values('"+content+"')");
}
catch(Exception e){
e.printStackTrace();
}
%>
And yes, I can fetch my data from database ..as you could see my code. But i'm unable to insert data..
Surely, Help would be appreciated!
EDITED:
Here is my created table:
create database if not exists poststatus;
use poststatus;
create table messages(
msg_id INT auto_increment,
msg VARCHAR(1000) NOT NULL,
primary key(msg_id)
);
The update button that sends the AJAX request is also the form's submit button, so when you click it, it begins submitting the form, which navigates away from the current page, cutting off the code before it can run the AJAX request.
Modify the beginning of your click handler to:
$(".update_button").click(function(e) {
e.preventDefault();
Calling preventDefault() on the event will prevent the form from submitting, giving your AJAX function the chance to run.
Additionally, there is a serious problem in the Java code; because the value is inserted with string concatenation, it creates a blatant SQL injection vulnerability, and also will not work if someone innocently types an apostrophe. Change:
Statement st=con.createStatement();
int i=st.executeUpdate("insert into messages(msg) values('"+content+"')");
to:
PreparedStatement st = con.prepareStatement("insert into messages(msg) values(?)");
st.setString(1, content);
int i = st.executeUpdate();
My code is as below, I have a MySQL DB on AWS RDS. I have also already included the mysql-connector-java-5.1.31-bin.jar in my build path.
My code is as below :
<%# 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">
<%# page import="java.sql.*"%>
<%# page import="java.util.Scanner "%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome Customer to Online Mall</title>
</head>
<body>
<%
final String host = "jdbc:mysql://mySqlPath/ShopSystem";
final String uName = "myusername";
final String uPass = "mypassword";
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
//#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
String Cust_address, Cust_email, Cust_contact;
Connection con = DriverManager.getConnection( host, uName, uPass );
//View all shops
Statement stmt5 = con.createStatement();
ResultSet rs2 = stmt5.executeQuery("SELECT * FROM ShopSystem.Shop");
while(rs2.next())
{
System.out.print("s_id = "+rs2.getInt(1)+"\t");
System.out.print("s_name = "+rs2.getString(4)+"\t");
System.out.print("s_location = "+rs2.getString(3)+"\t");
System.out.println();
}
sc.close();
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
%>
</body>
</html>
I am getting the following error :
Aug 01, 2014 5:31:46 PM org.apache.jasper.compiler.Compiler removeGeneratedFiles
WARNING: Failed to delete generated Java file [C:\Users\Documents\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\local host\ShopSystem-AWSJavaWebProject\org\apache\jsp\WelcomeCustomer_jsp.java]
No suitable driver found for jdbc:mysql://mySqlPath/ShopSystem
Please help.
Thank you in advance.
Your this line seems to be incorrect.
final String host = "jdbc:mysql://mySqlPath/ShopSystem";
It should be something like this :
jdbc:mysql://localhost/ShopSystem
or
jdbc:mysql://{YOUR_IP}/ShopSystem // e.g. "jdbc:mysql://192.168.15.102/ShopSystem"