post method is not working for postman(chrome extension) - java

i have project,in this i just save the two values into mysql database,it working fine.my requirement is i want to send the data by using postman,but those values are not saved into database and i din't get any exception,please help me how to solve this problem.
mycode is:
homepage.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>
<script type="text/javascript">
function validateForm()
{
var x=document.getElementById("location").value;
if( x == "" )
{
alert( "Please Enter The Location!" );
return false;
}
var y=document.getElementById("time").value;
if( y == "" )
{
alert( "Please Enter The Time!" );
return false;
}
var digits = "0123456789";
var temp;
for (var i = 0; i < document.getElementById("time").value.length; i++) {
temp = document.getElementById("time").value.substring(i, i + 1);
if (digits.indexOf(temp) == -1) {
alert("Please enter correct time");
document.getElementById("time").focus();
return false;
}
}
}
</script>
</head>
<body bgcolor="cyan">
<form name="myForm" method="post" action="insert.jsp" onsubmit="return validateForm()">
<div style="background-image:url(bg.jpg);">
<center><h1><font color="red">TRAFFIC INFORMATION SYSTEM</font></h1></center><br>
</div>
<hr size="10" color="red">
<center>
<table cellpadding="12">
<tr>
<td align="left">
Location</td><td> <input type="text" name="location"></td>
<tr>
<td align="right">
Expected Time
</td>
<td align="left">
<input type="text" size="3" name="time" maxlength="3">
Minutes
</td>
</tr>
<tr><td></td>
<td><input type="image" src="submit.gif" alt="Submit" width="48" height="48"/></td></tr>
</table>
</center>
</form>
</body>
</html>
insert.jsp
<%
DBCreation creation;
Connection connection;
String location;
String time;
location=request.getParameter("location");
time=request.getParameter("time");
connection=new DBCreation().getConnection();
try {
PreparedStatement statement=connection.prepareStatement("insert into Jam_Info values(?,?)");
statement.setString(1, location);
statement.setString(2, time);
int i=statement.executeUpdate();
if(i>0)
{
RequestDispatcher dispatcher=request.getRequestDispatcher("success.jsp");
dispatcher.forward(request, response);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
%>

You will have to write commit, to save data
connection.commit();
You have not close the connection.
connection.close();
write that it in the Finally block.

Related

not able to get json back to jsp from servlet in ajax code

I am new to Ajax, Jquery, JSON stuff. I have created one login page in jsp servlet technology. On login page, when user presses submit button, data gets collected in JSON and transferred to controller through AJAX. Now, in controller if on some condition, login name found to be correct, then it should use RequestDispatcher to dispatch it to success page. However if condition not satisfied, then it should write the message in JSON object and return it as content type json. Now the problem is that I am able receive JSON data on controller, but not able to redirect on success and also not able to show alert box to user if he entered wrong data. Below are the files:
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
function validateAndSet()
{
var jsonRequest = {};
var login_name = $.trim($('#loginName').val());
var password = $.trim($('#password').val());
if(login_name=='' || login_name.length==0 ){
alert("Please enter login name.");
$('#loginName').focus();
return false;
}
if(password=='' || password.length==0 ){
alert("Please enter password.");
$('#password').focus();
return false;
}
jsonRequest["login_name"] = login_name;
jsonRequest["password"] = password;
return jsonRequest;
}
</script>
</head>
<body>
<jsp:include page="commonResources/Header.jsp">
<jsp:param value="none" name="headerMenu"/>
</jsp:include>
<script>
$(document).ready(function(){
$("#but").click(function(){
var formData=validateAndSet();
var strUrl="rwcntrlr.do?action=loginForm";
$.post(strUrl, {jsonData: JSON.stringify(formData)},function(response){
response = jQuery.parseJSON( response);
if(response.status=='NOT OK')
{
alert("not ok");
}
else{
alert('OK');
}
});
});
});
</script>
<br><br>
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<div class="container-fluid">
<div class="panel panel-default" id="p1">
<div class="panel-heading"><h3>Login</h3></div>
<div class="panel-body">
<center>
<table>
<tr>
<td height="50">LoginName:</td><td height="50"><input type="text" id="loginName" name="loginName"/></td>
</tr>
<tr>
<td height="20">Password:</td><td height="20"><input type="password" id="password" name="password"/></td>
</tr>
<tr><td height="50" colspan="2" align="right"><input type="submit" id="but" name="subBut" value="Go>" /></td></tr>
</table>
</center>
</div>
</div>
</div>
</div>
<div class="col-sm-4"></div>
</div>
</body>
</html>
controller servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String formName=request.getParameter("action");
if(formName.equalsIgnoreCase("loginForm")){
String strJSONData = request.getParameter("jsonData");
System.out.println(strJSONData);// data received correctly...
JSONObject jsonResponse = new JSONObject();
try{
JSONObject requestedJSONObject = new JSONObject(strJSONData);
String login_name = requestedJSONObject.getString("login_name");
String password = requestedJSONObject.getString("password");
if(login_name.equalsIgnoreCase("u2")){
RequestDispatcher rd=request.getRequestDispatcher("employeeSection/employeeDailySheet.jsp");
response.setContentType("text/html");
rd.forward(request, response);
}
else{
jsonResponse.put("status", "NOT OK");
response.setContentType("application/json");
response.getWriter().write(jsonResponse.toString());
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
When I presses submit button on login.jsp, nothing happens. No console error is shown. What should I do to resolve this problem.

Search inside table MySql database with JSB

I'm a beginner programmer, I already build page for data entry and page show all entries, but now I want to show specific row inside the table, which code can help me?
My table columns: fullname - email - Phone - education
I want to search by email to show the other data in one page.
I found this code on internet:
<%#page import="java.sql.*"%>
<% Class.forName("com.mysql.jdbc.Driver");%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%!
public class Showit {
String URL = "jdbc:mysql://localhost/regdata";
String USERNAME = "root";
String PASSWORD = "admin";
Connection conn = null;
PreparedStatement selectRegister = null;
ResultSet resultSet = null;
public Showit() {
try {
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
selectRegister = conn.prepareStatement(
"SELECT a.fullname, a.email,"
+ " FROM mainr a,"
+ "WHERE a.fullname = ?"
+ "AND a.email = ?");
} catch (Exception e) {
e.printStackTrace();
}
}
public ResultSet getShowit(String fullname, String email) {
try {
selectRegister.setString(1, fullname);
selectRegister.setString(2, email);
resultSet = selectRegister.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}
return resultSet;
}
}
%>
<%
String fullname = new String();
String email = new String();
if (request.getParameter("fullname") != null) {
fullname = request.getParameter("fullname");
}
if (request.getParameter("email") != null) {
fullname = request.getParameter("email");
}
Showit showit = new Showit();
ResultSet showits = showit.getShowit(fullname, email);
%>
<table border="1">
<tbody>
<tr>
<td>Full Name</td>
<td>Email</td>
<td>Title</td>
</tr>
<% while (showits.next()) {%>
<tr>
<td><%= showits.getString("fullname")%></td>
<td><%= showits.getString("email")%></td>
<td><%= showits.getString("Phone")%></td>
</tr>
<% }%>
</tbody>
</table>
</body>
</html>
which connect with this page:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.Scanner" %>
<% Class.forName("com.mysql.jdbc.Driver");%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Search</title>
</head>
<body>
<form name="search" action="display.jsp" method="POST">
<table border="0">
<tbody>
<tr>
<td>Full Name</td>
<td><input type="text" name="fullname" value="" size="50" /></td>
</tr>
<tr>
<td>E-Mail</td>
<td><input type="text" name="email" value="" size="50" /></td>
</tr>
</tbody>
</table>
<input type="reset" value="Reset" name="reset" />
<input type="submit" value="Submit" name="Submit" />
</form>
</body>
</html>
but it's not work.
The issue may be with this line:
fullname = request.getParameter("email");
Note that you are assigning the email parameter to the fullname variable.
first what i see is that the Query is wrong. Remove the , after the table alias "a" (here line 2) like this:
"SELECT a.fullname, a.email,"
+ " FROM mainr a"
+ "WHERE a.fullname = ?"
+ "AND a.email = ?");
There is also an issue here:
<td><%= showits.getString("Phone")%></td>
You did not include Phone in the SELECT statement, so it will not exist in the ResultSet.

Updating database with jquery ajax for jsp

I wish to create a simple script to store information dynamically without refreshing or redirecting to another page. I've sourced high and low for answers before coming here, and I followed this.
However, I'm still unable to get it to store data because I don't know where I've goen wrong. Also, I wish to ask the purpose of success: function(msg)
Thanks a lot!
Update 1: Got it to work after following Anoop's solutions. However, such a popup appears when the data is submitted
StaffReg.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Staff Registration</title>
</head>
<body>
<%-- HTTP header --%>
<%response.addHeader("Cache-Control","no-cache");
response.addHeader("Pragma","no-cache");
response.addHeader("Expires","0");
%>
<%-- Javascript --%>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#Register').click(function(e) {
e.preventDefault();
$.ajax({
url: "StaffRegAuth.jsp",
type: "post",
data: {
username: $('#username').val(),
password: $('#password').val(),
userGroup: $('#userGroup').val()
},
success: function(msg) {
alert(msg);
}
});
});
});
</script>
<%-- Main body --%>
<h1 align="center"> Account Registration: </h1>
<div align="center">
<table style="width = 30%" >
<tr>
<td> User Name: </td>
<td><input type="text" id="username"></td>
</tr>
<tr>
<td> Password: </td>
<td><input type="password" id="password"></td>
</tr>
<tr>
<tr>
<td> User Group: </td>
<td><select name = "userGroup" id="userGroup">
<option value="1">Administrator
</optin>
<option value="2">Clerk
</optin>
<option value="3">Operations
</optin>
<option value="4">Sales
</optin>
</select></td>
</tr>
<tr>
</table>
<input type="submit" value="Register" id="Register">
</div>
</body>
</html>
StaffRegAuth.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<%-- Imports --%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%#page import="javax.servlet.*" %>
<%#page import="javax.servlet.http.*" %>
<%-- HTTP header --%>
<%response.addHeader("Cache-Control","no-cache");
response.addHeader("Pragma","no-cache");
response.addHeader("Expires","0");
%>
<%-- Variables that will be written --%>
<% String sUsername = request.getParameter("username");
String sPassword = request.getParameter("password");
int sUserGroup = Integer.parseInt(request.getParameter("userGroup"));
%>
<%-- Creating new staff account - writing --%>
<%
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String conURL= "jdbc:odbc:HOD_DATA";
Connection con = DriverManager.getConnection(conURL);
Statement st = con.createStatement();
int status = st.executeUpdate("insert into Staff(username, password, user_group) values('"+sUsername+"','"+sPassword+"',"+sUserGroup+")");
if(status>0){
//out.println("Update sucessful");
}
else{
//out.println("Update unsuccessful");
}
st.close();
con.close();
}
catch(Exception e){
out.println(e);
}
%>
</body>
</html>
Remove the submit button and use a normal html button with Id as Register.
Modify your html input types and replace the name attribute with id attribute. Ex: use id="username" instead of name="username"
Debugging:
Use firebug to check what value is passed to server. Ensure the correct ajax request is submitted.
Hope it helps.

Unaable to hide <td> tag with javascript and unable to write scriplets as id of <td tag>

This is my jsp page
<%#page import="java.util.List"%>
<%#page import="org.hibernate.cfg.Configuration"%>
<%#page import="org.hibernate.Session"%>
<%#page import="org.hibernate.SessionFactory"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script>
function page_hide_show()
{
for(var i=8;i<22;i++)
{alert(i)
document.getElementsByClassName(i).style.display='none';
}
}
</script>
</head>
<body onload="page_hide_show()">
<%
SessionFactory sessionfactory=null;
Session Listsession=null ;
sessionfactory=new Configuration().configure().buildSessionFactory();
Listsession = sessionfactory.openSession();
String name="";
String age="";
String address="";
String phone_no="";
try
{
int c=0;
if(request.getAttribute("c")!=null)
{
c=Integer.parseInt(request.getAttribute("c").toString());
}
org.hibernate.Query query=Listsession.createQuery("select name,age,address,phone_number from paging order by auto_inc");
query.setFirstResult(c);
query.setMaxResults(10);
List check1 =query.list();
java.util.Iterator on=check1.iterator();
while(on.hasNext())
{
Object oo[]=(Object[])on.next();
name=(String)oo[0].toString().trim();
age=(String)oo[1].toString().trim();
address=(String)oo[2].toString().trim();
phone_no=(String)oo[3].toString().trim();
%>
<div align="center" style="border-bottom:1px solid #ccc "> Name <input type="text" name="text" value="<%=name %> " disabled="disabled">
<br><br>
</div>
<% }
}
catch(Exception ee){
out.print(ee.getMessage());
}
%>
<center> <img src="fgfdg.png"> </center>
<table align="center">
<tr>
<!-- <td>First Page</td> -->
<%
int value_counter=0;
int pagecount=0;
long counters=0;
try{
org.hibernate.Query query=Listsession.createQuery("select count(*) from paging order by auto_inc");
List check1 =query.list();
java.util.Iterator on=check1.iterator();
while(on.hasNext())
{
Object oo=on.next();
counters=((Number)oo).longValue();
}}
catch(Exception e)
{
out.println(e);
}
int count=(int)counters/10;
int Counter_in_int=count*10;
double xyz=Counter_in_int-counters;
if(xyz>=0)
{
for(int i=0;i<count;i++)
{
pagecount++;
%>
<td class="<%=pagecount%>"><%= pagecount%></td>
<% value_counter=value_counter+10;} }
else
{
%>
<%
for(int i=0;i<=count;i++)
{
pagecount++;
%>
<td class="<%=pagecount%>"><a href="Pagecount?c=<%=value_counter %>" ><%= pagecount%></a></td>
<% value_counter=value_counter+10;} }
%>
<!-- <td>Last Page</td> -->
</tr>
</table>
</body>
</html>
So My question is
in the above code I am trying to hide td tags with classname from 8 to 21 but I am unable to do so.I think my javascript function is right.Also when I am giving id to as
< td id="<%=pagecount%>">
I am unable to do so.
kindly tell me how to hide the td's with classname from 8 to 21 in this code.Is my javascript function wrong.
Your problem is that document.getElementsByClassName(something) returns an Array (the plural in elements). That means that you have to have something like this :
var list = document.getElementsByClassName(class_name);
for (i = 0; i < list.length; i++) alert(list[i]);
However, I see you only have one of each class name. In this case, you should just do something like this : document.getElementsByClassName(i)[0].style.display = 'none'.
Hope this was useful :)

unable to compile class for JSP

Iam working on a project in JSP using netbeans.
Iam getting the following error......but i didn't find the java any files..please provide me something.The error is:
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 205 in the generated java file
Syntax error, insert "Finally" to complete TryStatement
An error occurred at line: 206 in the generated java file
Syntax error, insert "}" to complete ClassBody
Stacktrace:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:92)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:330)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:439)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:349)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:327)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:314)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:589)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
The files i used are:
addNewUser.jsp:
<%# page language="java" %>
<%# page session="true" %>
<%# page import="java.util.*" %>
<HTML>
<head>
<LINK href="styles.css" type="text/css" rel="stylesheet">
</head>
<SCRIPT LANGUAGE="JavaScript">
<!--
history.go(+1);
function validate(){
x = document.NewUser.uid;
y = document.NewUser.pwd;
z = document.NewUser.auth;
var ed=x.value;
var pd=y.value;
var ad=z.value;
var pattern = /^([a-zA-Z0-9\_\.]{4,10})$/;
var Apattern = /^([0-3]{1})$/;
if(!(pattern.test(ed))){
alert("Invalid username");
return false;
}
else if(!(pattern.test(pd))){
alert("Invalid password");
return false;
}
else if(!(Apattern.test(ad))){
alert("Invalid Authentication");
return false;
}
else
return true;
}
//-->
</SCRIPT>
<br><br>
<body Class=Grad>
<center>
<BR><BR><br><br>
<FONT FACE="Century Gothic">
<FONT size="2" color="blue" FACE="Century Gothic">
<FORM NAME="NewUser" ACTION="AddNewUser1.jsp" METHOD="POST" onsubmit="return validate()">
<TABLE Border=0 align=center>
<TR class=row_title ALIGN="center">
<TH COLSPAN="2"> Add user</TH>
</TR>
<TR class=row_even>
<TD>UserID * </TD>
<TD><input TYPE=text name=uid size="10" maxlength="10"></TD>
</TR>
<TR class=row_odd>
<TD>Password * </TD>
<TD><input TYPE=password name=pwd size="10" maxlength="20"></TD>
</TR>
<TD><input type=hidden name=auth value=2>
<TR class=row_even>
<TD><INPUT TYPE=submit name=submit value="Submit">
</TD>
<TD><INPUT TYPE=reset name=resett value="Reset" >
</TD>
</TR>
</TABLE>
<A align="center" href="Login.jsp">BACK TO HOME</A>
</FORM>
</BODY>
</HTML>
addNewUser1.jsp:
<%# page language="java" %>
<%# page session="true" %>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%# page import="java.util.Random" %>
<html>
<head>
<LINK href="styles.css" type="text/css" rel="stylesheet">
<SCRIPT LANGUAGE="JavaScript">
<!--
history.go(+1);
//-->
</SCRIPT>
</head>
<jsp:include page="MultiLevelmenu.htm"/><br><br><body Class=SC>
<center>
<BR><BR>
<FONT FACE="Century Gothic">
<!--Declaration of varaibles-->
<%! String errormsg ;%>
<%! String disluserid ;%>
<%! String dislpwd ;%>
<%! int auth ;%>
<%
/*Retreiving user id and password*/
disluserid = request.getParameter("uid");
if(disluserid == null)
disluserid = "";
dislpwd = request.getParameter("pwd");
if(dislpwd == null)
dislpwd = "";
String sauth = request.getParameter("auth");
if(sauth == null)
auth=0;
auth = Integer.parseInt(sauth);
//System.out.println(disluserid+dislnewpwd+dislpwd);
%>
<%
/*Declaration of variables*/
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
String Userid,Password;
try
{
/*Getting the connection variable from session*/
con=(Connection)session.getAttribute("connection");
stmt = con.createStatement();
String Query = "SELECT * from student where studentid = \'"+disluserid+"\'";
System.out.println(Query);
rs = stmt.executeQuery(Query);
}
catch(Exception e)
{
System.out.println("Exception"+e);
/* If user provides valid username & password then update the new password to database*/
if(rs.next())
{%>
<script>
for(i=1;i<=6;i++) document.write("<br>");
</script>
<H3 align="center"> User already exists</H3>
<BR>
<center>
Back
</center>
<%
}
else{
String UpdateQuery =
"Insert into student values(\'"+disluserid+"\',\'"+dislpwd+"\',"+auth+")";
//System.out.println(UpdateQuery);
int rowsAffected=stmt.executeUpdate(UpdateQuery);
//System.out.println("Rows Affected = " + rowsAffected);
if(rowsAffected==1)
{%>
<script>
for(i=1;i<=10;i++) document.write("<br>");
</script>
<H3 align="center">User Created Successfully </H3>
Create Another User
<br/>
Home
<BR>
<%}
/* If user provides invalid password or username*/
else{%>
<script>
for(i=1;i<=6;i++) document.write("<br>");
</script>
<H3 align="center">Unable to create user please try again </H3>
<BR>
<% } %>
<%
}
%>
</FONT>
</center>
</BODY>
</html>
try {
/*Getting the connection variable from session*/
con=(Connection)session.getAttribute("connection");
stmt = con.createStatement();
String Query = "SELECT * from student where studentid = \'"+disluserid+"\'";
System.out.println(Query);
rs = stmt.executeQuery(Query);
} catch(Exception e) { System.out.println("Exception"+e);
In the above code section you are not completing the try's catch block.

Categories