Sample Ajax program for JSP+Servlets+Hibernate - java

In my app im using JSP as view,servlet as controller,hibernate as model..
in that app jsp pages im have to fill form while creating new user with fields like username and all.
now i want to use AJAX code to check if username name with entered name in form is already there in the database or not...
can any1 guide me how to write coding for this as well as the control flow..
i have googled but didnt got any idea how to do this requirement..
thanks in advance

Here you are having two option for user name validation.
1> Client(User Interface) Side validation
2> Server side validation
For option 1>, you need to write ajax call which will make a request to server and respond a result which will inform if a use is valid or not.
For client side, I will suggest you to use java script OR jQuery.
Here is the sample jQuery ajax code.
$.ajax({
url: "validateUser.html?username=username",
success:function(data){
//YOUR CODE FOR FUTHRE ACTION FOR VALID/INVALID ACTION
}
});
You can refer jQuery ajax here.
For option 2>, validation on server side...
You can validate the user name on submit of the form.
you can retrieve the value by request.getParamter("userName"); and check into the DB if it already there OR not.
Regards,
Gunjan.

In Jsp
<script type="text/javascript">
function VerifyUsername()
{
//alert("In Verify Method");
var name=document.getElementById("username").value;
//alert(name);
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
//alert("http");
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
alert("http active");
}
xmlhttp.onreadystatechange=function()
{
//alert("in Function()");
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
try
{
//alert("In Try");
document.getElementById("errorpass").innerHTML=xmlhttp.responseText;
/*var response = xmlhttp.responseText;
alert(response);
if(response.toString()=='notmatch')
{
alert("Ok");
document.getElementById("errorpass").innerHTML ="OK";
}
if(response =='match')
{
alert("Not Ok");
document.getElementById("errorpass").innerHTML ="Take Other Name.";
}*/
}
catch(ex)
{
alert("Exception in function "+ex);
}
}
}
//xmlhttp.open("POST","servlet/UsernamePresence_Serv?UserId"+name,true);
xmlhttp.open("POST","servlet/UsernamePresence_Serv?"+name,true);
var params = "UserId="+name;
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
</script>
in Servlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try
{
Session session=Hibernate_Class.sessionObject();
String userID=null;
userID = request.getParameter("UserId");
login_model loginModel_Obj=new login_model();
loginModel_Obj._Name=userID;
System.out.print("at "+userID);
boolean username_bool=Hibernate_Class.usernamePresence(loginModel_Obj, session);
if (username_bool)
{
out.println("Username Present In Database");
}
else
{
out.println("Username Not Present In Database");
}
}
finally{}
out.close();
}

In Below code just replace JDBC code with your Hibernate Code .
JSP
<!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=iso-8859-1" />
<title> - User Login</title>
<style type="text/css">
#marqueecontainer{
position: relative;
width: 150px; /*marquee width */
height: 163px; /*marquee height */
/*background-color: white;*/
overflow: hidden;
/*border: 3px solid orange;
padding: 2px;
padding-left: 4px;*/
}
</style>
</head>
<script language="javascript">
var mWindow="windows";
var objLogRequest;
function chekUserId()
{
try
{
if(document.getElementById("userID").value=="")
{
alert(" You have not entered Username. ");
return 0;
}
if(document.getElementById("userPass").value=="")
{
alert("You have not entered Password.");
return 0;
}
var userId = document.getElementById("userID").value;
var userPass = document.getElementById("userPass").value;
//alert("userId:->"+userId);
//alert("userPass:->"+userPass);
serUrl ='/servlet/UserLogin?userID='+userId
+'&userPass='+userPass+'&randomNum='+Math.random()*Math.random();
//alert("serUrl:->"+serUrl);
if(window.ActiveXObject)
{
objLogRequest = new ActiveXObject('Microsoft.XMLHTTP');
//alert("Windos Browser");
}
else
{
objLogRequest = new XMLHttpRequest();
mWindow = "nonWindows";
}
if(objLogRequest)
{
//alert("objAddRequest 1");
objLogRequest.onreadystatechange = sendLogInfo;
//alert("objAddRequest 2");
objLogRequest.open('Get',serUrl);
//alert("objAddRequest 3");
if(mWindow=='nonWindows')
{
objLogRequest.send('');
}
else
{
//alert("before send ");
objLogRequest.send();
//alert("after send ");
}
}
}// end try
catch(e)
{
alert("Exception in chekUserId function "+e);
}
}
function sendLogInfo()
{
try
{
//alert('object state :-> '+objLogRequest.readyState)
if(objLogRequest.readyState==4)
{
if(objLogRequest.status==200)
{
var response = objLogRequest.responseText;
//alert('response :-> '+response)
if(response =='notmatch')
{
document.getElementById("errorpass").innerHTML ="Username and
password do not match.(You provided
"+document.getElementById("userID").value+" )";
document.getElementById("userPass").value="";
}
if(response =='match')
{
alert('user valid');
}
}
}
}
catch(ex)
{
alert("Exception in sendInfo function "+ex);
}
}
</script>
<body marginheight="0" marginwidth='0' topmargin='0'
bottommargin='0'leftmargin='0' class="body">
<table width="751" border="0" align="center" cellpadding="0"
cellspacing="0">
<tr>
<td bgcolor="#000099"><table width="751" border="0"
cellspacing="1" cellpadding="0">
<tr>
<td bgcolor="#FFFFFF"><table width="751" border="0"
cellspacing="0" cellpadding="0">
<tr>
<td>
</td>
</tr>
<tr>
<td height="25" align="left" valign="middle"
bgcolor="#C7C7C7" class="plan-a-trip"><span class="welcometext"></
span></td>
</tr>
<tr>
<td height="10" align="left" valign="top"></td>
</tr>
<tr>
<td><table width="751" border="0" cellspacing="0"
cellpadding="0">
<tr>
<td width="10" align="left" valign="middle"> </
td>
<td width="150" align="left" valign="top">
</td>
<td width="10" align="left" valign="top"></td>
<td width="571" height="270" align="left"
valign="top" bgcolor="#999999"><table width="571" border="0"
cellspacing="1" cellpadding="0">
<tr>
<td width="579" height="476" align="left"
valign="top" bgcolor="#FFFFFF">
<table width="571" height="391" border="0" cellpadding="0"
cellspacing="0">
<form name='loginform' method='get' action='/servlet/UserLogin'
onSubmit="return submit(document.loginform);" >
<tr>
<td width="25" rowspan="11" align="left"
valign="top"> </td>
<td width="459" height="20" align="left"
valign="top"> </td>
<td width="20" rowspan="11" align="left"
valign="top"> </td>
</tr>
<tr>
<td height="16" align="left"
valign="middle"><img src="/image/PlanATrip/UserLogin/member_login.jpg"
width="120" height="13" /></td>
</tr>
<tr>
<td height="10" align="left"
valign="middle"> </td>
</tr>
<tr>
<td height="5" align="left" valign="top"></td>
</tr>
<tr>
<td height="100" align="left"
valign="top"><table width="479" height="115" border="0"
cellpadding="0" cellspacing="0">
<tr>
<td width="85" align="left"
valign="middle" class="text">Username</td>
<td width="10" rowspan="6" align="left"
valign="top"> </td>
<td width="376">
<input id="userID" name="userID"
type="text" class="inputtext" maxLength="25"/> </td>
</tr>
<tr>
<td height="5" align="left"
valign="middle"></td>
<td height="5" align="left" valign="top"></
td>
</tr>
<tr>
<td align="left" valign="middle"
class="text">Passward</td>
<td><input id="userPass" name="userPass"
type="password" maxlength="15" class="inputtext" /></td>
</tr>
<tr>
<td height="5" align="left"
valign="middle"></td>
<td height="5" align="left" valign="top"
class="wrongpass" id="errorpass"> </td>
</tr>
<tr>
<td align="left" valign="middle"> </
td>
<td><input name="loginBut" type="button"
id="loginBut" class="searchButton" value="Login"
onclick="chekUserId()"/></td>
</tr>
<tr>
<td align="left" valign="middle"> </
td>
<td ><a href="/servlets/Registration.html"
class="fyp">New User Sign Up</a></td>
</tr>
</table></td>
</tr>
<tr>
<td height="10" align="left"
valign="top"> </td>
</tr>
<tr>
</tr>
</form>
</table></td>
</tr>
</table></td>
<td width="10" align="left" valign="middle"> </
td>
</tr>
</table></td>
</tr>
<tr>
<td></td>
</tr>
</table></td>
</tr>
</table></td>
</tr>
</table>
</body>
</html>
Servlet Code
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class UserLogin extends HttpServlet
{
public String DBUrl = "jdbc:mysql://127.0.0.1:3306/
databasename";
public void init ()
{
//getCon();
System.out.println("UserLogin called");
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
ResultSet rs=null;
Connection con = null;
Statement stm=null;
//Vector userId;
String userID=null,userPass=null,currentDate=null;
userID = req.getParameter("userID");
userPass = req.getParameter("userPass");
HttpSession session = req.getSession(true);
try
{
con = pool.getCon();
stm = con.createStatement();
//System.out.println("connect");
////chek user ID Start ***//////
String querySelctId = "select count(*)user from userinfo where
UserId='"+userID+"'AND UserPassword='"+userPass+"';";
rs = stm.executeQuery(querySelctId);
//System.out.println("4");
int count = 0
try{
count = rs.getString(1);
}catch(SQLException sqlEx){
System.out.println("sqlEx");
}catch(Exception ex){
System.out.println("Ex");
}
if(count==1)
{
System.out.println(userID+":-> Login");
out.print("match");
}
else
{
out.print("notmatch");
}
}
catch (SQLException sqle)
{
System.out.println("SQLException");
System.out.println(sqle);
//res.sendRedirect("/servlets/RegistrationFail.html");
}
catch (Exception ex)
{
System.out.println("Exception");
System.out.println(ex);
res.sendRedirect("/servlets/ErrorPage.htm");
}
finally
{
try
{
if(con != null)
{
System.out.print("UserLogin Servlet release:-> ");
pool.releaseConnection(con);
rs.close();
stm.close();
out.flush();
out.close();
}
}
catch(Exception Ex)
{
System.out.println(" Exception in release the connection ");
System.out.println(Ex);
}
}
}
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException, IOException
{
doPost(req,res);
}
public Connection getCon()
{
Connection con = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(DBUrl,"root","");
databaseMetaData = con.getMetaData();
stm = con.createStatement();
}catch(java.lang.ClassNotFoundException e)
{
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}catch (SQLException sqle)
{
System.out.println("SQLException");
System.out.println(sqle);
}catch (Exception ex)
{
System.out.println("Exception");
System.out.println(ex);
}
return con;
}
}

Related

get data from a table in a page with Java

I'm working in this project that opens a site pages fills the necesary fields get push the submit buttons and opens another window where some values are shown in a table, so far everything works ok but I don't know how to get the data from the table into my java program to save it in a file.
I'm working with Selenium WebDriver
this it's the code for my java program, I just need to get the info on the table:
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.exec.util.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
public class Know_Your_Case_Status {
public void FillData(WebDriver driver) throws InterruptedException {
for (int i = 1; i < 12; i++) {
driver.get("http://cms.nic.in/ncdrcusersWeb/login.do?method=caseStatus");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//Select Radio Button for State Commission
driver.findElement(By.cssSelector("[id='UserType'][value='C']"))
.click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// Now Select State Assam
WebElement SelectState = driver.findElement(By.name("state_id"));
Select Sl = new Select(SelectState);
Sl.selectByVisibleText("Assam");
/**** Select From Date ******/
driver.findElement(By.cssSelector("img.ui-datepicker-trigger"))
.click();
// Select may Month
Select SelMonth = new Select(driver.findElement(By
.className("ui-datepicker-month")));
SelMonth.selectByValue("4");
// Select Year 2015
Select SelYear = new Select(driver.findElement(By.id("scrollyear")));
SelYear.selectByVisibleText("2015");
// Select date 1
driver.findElement(By.linkText("1")).click();
/**** Select To Date ******/
// driver.findElement(By.cssSelector("img.ui-datepicker-trigger")).click();
driver.findElement(By.xpath("(//img[#alt='...'])[2]")).click();
// Select Jan Month
Select SelToMonth = new Select(driver.findElement(By
.className("ui-datepicker-month")));
SelToMonth.selectByVisibleText("January");
// Select Year 2016
Select SelToYear = new Select(driver.findElement(By
.id("scrollyear")));
SelToYear.selectByVisibleText("2016");
// Select date 1
driver.findElement(By.linkText("8")).click();
Select SelCaseType = new Select(driver.findElement(By
.name("condition")));
SelCaseType.selectByVisibleText("CaseType");
Select Selval = new Select(driver.findElement(By.name("ctId")));
Selval.selectByIndex(i+1);
//Selval.selectByValue("8");
driver.findElement(By.name("advs")).click();
}
}
}
And the code source from the page I'm trying to get the info it's:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Query Report</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="./stylesheet/confoStyle.css" rel="stylesheet" type="text/css" />
<script language="javascript" type="text/javascript" src="javascript/CommonCDRC.js"></script>
<script language="javaScript">
function doPrint()
{
tbHead.style.display = "none";
tbTail1.style.display = "none";
tbTail2.style.display = "none";
tbMenu.style.display = "none";
window.print();
tbHead.style.display = "";
tbTail1.style.display = "";
tbTail2.style.display = "";
tbMenu.style.display = "";
}
function submitForm()
{
var flgSubmit = 1;
var dtOfHearing = document.loginForm.dtOfHearing.value;
if(flgSubmit == 1)
{
document.loginForm.method.value = "loadSelectloginForCLhtml";
document.loginForm.submit();
}
else
return false;
}
function loadProceeding(caseid, fano)
{
document.loginForm.fano.value=fano;
document.loginForm.cid.value=caseid;
document.loginForm.action="ViewProceedingCS.jsp";
document.loginForm.submit();
}
</script>
</head>
<body bgcolor="#9cd3ed">
<form name="loginForm" method="post" action="/ncdrcusersWeb/login.do" onsubmit="return submitForm()">
<input type="hidden" name="method" value="ViewProceedingCS">
<input type="hidden" name="fano" value="">
<input type="hidden" name="case_id_in" value="">
<input type="hidden" name="dtOfHearing" value="">
<input type="hidden" name="courtId" value="">
<input type="hidden" name="cid" value="">
<input type="hidden" name="stateCode" value="5">
<input type="hidden" name="distCode" value="0">
<table class="baseContaner topGroup" width="100%" align="center">
<tr>
<td width="3%" class="rptsubnumhd">SN</td>
<td width="10%" class="rptsubnumhd">Case No</td>
<td width="17%" class="rptsubtxthd">Complainant</td>
<td width="17%" class="rptsubtxthd">Respondent</td>
<td width="18%" class="rptsubtxthd">Complainant-Advocate</td>
<td width="17%" class="rptsubtxthd">Respondent-Advocate</td>
<td width="8%" class="rptsubnumhd">Date of Filing</td>
<td width="10%" class="rptsubnumhd">
Date of Next Hearing
</td>
</tr>
<tr>
<td class="rptnumhval">1</td>
<td class="rptnumhval"><a class="help" href="javascript:loadProceeding('5/0/A/19/2015','A/19/2015' )">
A/19/2015 </a></td>
<td class="rpttxthval">Managing Director, The Assam Power Distribution Company Ltd.</td>
<td class="rpttxthval">Smti Khaleda Begum</td>
<td class="rpttxthval">Mr. P. Bhowmick</td>
<td class="rpttxthval"></td>
<td class="rptnumhval">15/05/2015</td>
<td class="rptnumhval">
19/05/2015
</td>
</tr>
<tr>
<td class="rptnumhval">2</td>
<td class="rptnumhval"><a class="help" href="javascript:loadProceeding('5/0/A/20/2015','A/20/2015' )">
A/20/2015 </a></td>
<td class="rpttxthval">The Chief Regional Manager, United India Insurance Company Ltd.</td>
<td class="rpttxthval">Mr. Dulu Dey</td>
<td class="rpttxthval">Mr. R. Goswami</td>
<td class="rpttxthval"></td>
<td class="rptnumhval">20/05/2015</td>
<td class="rptnumhval">
26/05/2015
</td>
</tr>
<tr>
<td class="rptnumhval">3</td>
<td class="rptnumhval"><a class="help" href="javascript:loadProceeding('5/0/A/21/2015','A/21/2015' )">
A/21/2015 </a></td>
<td class="rpttxthval">Dr. Vijay Nahata</td>
<td class="rpttxthval">Smti. Moushumi Nath</td>
<td class="rpttxthval">Mr. N. Sharma</td>
<td class="rpttxthval">Ms. D. Tamuli</td>
<td class="rptnumhval">05/06/2015</td>
<td class="rptnumhval">
11/09/2015
</td>
</tr>
<tr>
<td class="rptnumhval">4</td>
<td class="rptnumhval"><a class="help" href="javascript:loadProceeding('5/0/A/22/2015','A/22/2015' )">
A/22/2015 </a></td>
<td class="rpttxthval">Sri Biren Kalita</td>
<td class="rpttxthval">The Branch Manager, Ulubari Branch (CDO-II), Oriental Insurance Co. Ltd.</td>
<td class="rpttxthval">Mr. A. K. Gupta</td>
<td class="rpttxthval">Mr. S. Bhuyan</td>
<td class="rptnumhval">15/06/2015</td>
<td class="rptnumhval">
21/09/2015
</td>
</tr>
<tr>
<td class="rptnumhval">5</td>
<td class="rptnumhval"><a class="help" href="javascript:loadProceeding('5/0/A/23/2015','A/23/2015' )">
A/23/2015 </a></td>
<td class="rpttxthval">Smti. Sabita Roy</td>
<td class="rpttxthval">Managing Director, Birla Sun Life Insurance Co. Ltd.</td>
<td class="rpttxthval">Mr. N. N. Karmakar</td>
<td class="rpttxthval"></td>
<td class="rptnumhval">15/06/2015</td>
<td class="rptnumhval">
07/09/2015
</td>
</tr>
<tr>
<td class="rptnumhval">6</td>
<td class="rptnumhval"><a class="help" href="javascript:loadProceeding('5/0/A/24/2015','A/24/2015' )">
A/24/2015 </a></td>
<td class="rpttxthval">Branch Manager, Indian Overseas Bank</td>
<td class="rpttxthval">Mr. Padmeswar Baruati</td>
<td class="rpttxthval">Mr. V.K.Dewan</td>
<td class="rpttxthval"></td>
<td class="rptnumhval">24/06/2015</td>
<td class="rptnumhval">
17/09/2015
</td>
</tr>
<tr>
<td class="topHdMsg" colspan="8"><input type=button value="Back" onClick="history.go(-1)"></td>
</tr>
</table>
</form>
</body>
</html>
I was thinking that maybe a driver.findElement(By.tagName("table")).getText() may work but I'm getting all the data in one line, is it a way to separete the head and the lines ?
You should try as below :-
List<WebElement> rows = driver.findElement(By.tagName("table")).findElements(By.tagName("tr"));
for(WebElement row : rows)
{
List<WebElement> columns = row.findElements(By.tagName("td"));
for(WebElement column : columns)
{
String columnText = column.getText();
}
}
Hope it helps...:)

404 not found error for servlet

I have embedded department.jsp in create.jsp. My department.jsp has a table in which i submit data, the action is on a servlet but on submitting it is giving a 404 error for servlet.
create.jsp in body-
<header>
<img style="text-align:left" src="images.png" width="200" height="100" alt="NSIC-logo1"/>
<h1>File Tracking System</h1>
<form style="float:right;" action=" LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
<br>
</header>
Create
<iframe style="height:530px;width:1340px " src="department.jsp" name="frame2">
<p>Your browser does not support iframes.</p>
</iframe>
department.jsp in body-
<form action="DepartmentServlet" method="post">
<center>
<table id="depart">
<thead>
<tr>
<th colspan="2">Create Department</th>
</tr>
</thead>
<tbody>
<tr>
<td>Company Name :</td>
<td><input type="text" name="company" value="" size="50" /></td>
</tr>
<tr>
<td>Department Name</td>
<td><input type="text" name="department" value="" size="50" /> </td>
</tr>
<tr>
<td>Head Office :</td>
<td><input type="text" name="place" value="" size="50" /></td>
</tr>
</tbody>
</table>
</center>
<input type="reset" value="Clear" name="Clear" />
<input type="submit" value="Submit" name="Submit" />
</form>
DepartmentServlet.java
public class DepartmentServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//request.getRequestDispatcher("link.html").include(request, response);
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("JSESSIONID")){
System.out.println("JSESSIONID="+cookie.getValue());
break;
}
}
}
HttpSession session = request.getSession(false);
System.out.println("admin="+session.getAttribute("admin"));
if(session!=null && session.getAttribute("admin") != null){
String admin=(String)session.getAttribute("admin");
boolean status=false;
try{
String department=request.getParameter("department");
String company=request.getParameter("company");
String place=request.getParameter("place");
boolean checkd=dcheck.value(department);
boolean checkc=checkchar.value(company);
boolean checkp=checkchar.value(place);
if(checkd==true&&checkc==true&&checkp==true) {
Connection con=ConnectionProvider.getCon();
String sql="insert into department(departmentname,company,place) values (?,?,?)";
PreparedStatement pstmt =con.prepareStatement(sql);
pstmt.setString(1,department);
pstmt.setString(2,company);
pstmt.setString(3,place);
int rs=pstmt.executeUpdate();
if(rs>0){status=true;}
if(status){
PrintWriter out= response.getWriter();
out.print("values have been inserted,"+admin);
response.sendRedirect("insert.jsp");
}
else
{
PrintWriter out= response.getWriter();
out.print("failed to insert");
response.sendRedirect("notinsert.jsp");
}
}
else{response.sendRedirect("entry.jsp");}
}catch(SQLException e){}
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
}

Not able to read an url content in Java

URL oracle = new URL("hurlAddress/dinfo.cgi");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
I get
<html>
<head>
<!-- RUI RC=100 -->
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
<title>Don't open this page!</title>
</head>
<body bgcolor="#C0C0C0">
<center>
<table border="0" cellpadding="0" cellspacing="4" width="400">
<tr><td align="center" valign="top" width="48">
<img src="en/media/ss_wrn.gif" border="0" width=32 height=32>
</td>
<td>
<font size="4" face="Helvetica,Arial">
<b>User information is disabled.</b><br>
This operation cannot be accepted. User certification is invalid or date expired.<br>
Update page.<br>
</font>
</td>
</tr>
<tr><td></td>
<td align="right">
<img src="en/media/b_ok.gif" border="0" alt="OK" title="OK">
</td>
</tr>
</table>
</center>
</body>
I was expecting
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
<title>Remote UI:Device Information</title>
</head>
<body bgcolor="white" link="blue" alink="red" vlink="blue">
<a name="page_top"></a>
<form>
<SCRIPT LANGUAGE="JavaScript">
var has_fax = false; // true or false
var Fax_Type = "0"; // 0(None),1(PSTN),2(PSTNx2),3(ISDN)
var has_send =true; // has send
var is_oem = false;
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
function reload_device(){
var cgi_str = "./dinfo.cgi?";
// for Expire Cache!!
var now_time = new Date();
cgi_str += "Dummy=" + now_time.getTime();
document.location.href = cgi_str;
}
</SCRIPT>
<table border="0" cellpadding="0" cellspacing="2" width="100%">
<tr>
<td valign="middle"><font size="4" color="#000066"><b><table border="0" cellpadding="0" cellspacing="2">
<tr>
<td rowspan="2" nowrap><img src="en/media/imgs030.gif"></td>
<td nowrap><font face="Helvetica,Arial" size="4" color="#000066"><b>slq29986</b></font></td>
</tr>
<tr>
<td nowrap><font size="2">iR5570</font></td>
</tr>
</table></b></font></td>
<td valign="middle" width="70" align="right"><font size="4" color="black"><b><img src="en/media/bh_updt.gif" width="28" height="28" border="0" alt="Update" title="Update"></b></font></td>
</tr>
</table>
<hr noshade size="2">
<table border="0" cellpadding="0" cellspacing="4" width="100%">
<tr>
<td align="left"><font size="1"> Last Updated :05/26/2016 19:30:54</font></td>
</tr>
</table><table border="0" cellspacing="0" cellpadding="2" width="100%">
<tr height="26">
<td bgcolor="#000066" height="26"><font color="white" face="Helvetica,Arial"><b> Device Information</b></font></td>
</tr>
</table><table border="0" cellspacing="2" cellpadding="2" width="100%">
<SCRIPT LANGUAGE="JavaScript">
if(is_oem == false)
{
document.write('<tr>');
document.write('<td width="3%"></td>');
document.write('<td width="40%"><font face="Helvetica,Arial" size="2">Manufacturer :</font></td>');
document.write('<td><font size="4">CANON INC</font></td>');
document.write('</tr>');
}
</SCRIPT>
<tr>
<td width="3%"></td>
<td width="40%"><font face="Helvetica,Arial" size="2">Device Name :</font></td>
<td><font size="4">slq29986</font></td>
</tr>
<tr>
<td width="3%"></td>
<td width="40%"><font face="Helvetica,Arial" size="2">Location :</font></td>
<td><font size="4">MESAAS</font></td>
</tr>
<tr>
<td width="3%"></td>
<td width="40%"><font face="Helvetica,Arial" size="2">Product Name : </font></td>
<td>iR5570</td>
</tr>
<tr>
<td colspan="3"><hr size="1"></td>
</tr>
<tr>
<td width="3%"></td>
<td width="40%"><font face="Helvetica,Arial" size="2">Serial Number :</font></td>
<td>SLQ29986</td>
</tr>
<tr>
<td width="3%"></td>
<td width="40%"><font face="Helvetica,Arial" size="2">Main Board Version :</font></td>
<td>1</td>
</tr>
<tr>
<td width="3%"></td>
<td width="40%"><font face="Helvetica,Arial" size="2">Controller Version :</font></td>
<td>3604.838.3201</td>
</tr>
<tr>
<td width="3%"></td>
<td width="40%"><font face="Helvetica,Arial" size="2">Scanner Version :</font></td>
<td>401.100</td>
</tr>
<tr>
<td width="3%"></td>
<td width="40%"><font face="Helvetica,Arial" size="2">Finisher Version :</font></td>
<td>801</td>
</tr>
<SCRIPT LANGUAGE="JavaScript">
if(has_send == true)
{
document.write('<tr>');
document.write('<td colspan="3">');
document.write('<hr size="1">');
document.write('</td>');
document.write('</tr>');
document.write('<tr>');
document.write('<td width="3%"></td>');
document.write('<td width="40%"><font face="Helvetica,Arial" size="2">Receive E-mail Address :</font></td>');
document.write('<td>aaa#aaa.edu</td>');
document.write('</tr>');
}
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
if( has_fax == true )
{
document.write('<tr>');
document.write('<td colspan="3">');
document.write('<hr size="1">');
document.write('</td>');
document.write('</tr>');
document.write('<tr>');
document.write('<td width="3%"></td>');
document.write('<td width="40%"><font face="Helvetica,Arial" size="2">Telephone Number :</font></td>');
document.write('<td></td>');
document.write('</tr>');
if( Fax_Type == "3" )
{
document.write('<tr>');
document.write('<td width="3%"></td>');
document.write('<td width="40%"><font face="Helvetica,Arial" size="2">Subaddress :</font></td>');
document.write('<td></td>');
document.write('</tr>');
}
}
</SCRIPT>
<tr>
<td colspan="3">
<hr size="1">
</td>
</tr>
<tr>
<td width="3%"></td>
<td width="40%"><font face="Helvetica,Arial" size="2">System Manager :</font></td>
<td>MESAAS</td>
</tr>
<tr>
<td width="3%"></td>
<td width="40%"><font face="Helvetica,Arial" size="2">Contact Information :</font></td>
<td></td>
</tr>
<tr>
<td width="3%"></td>
<td width="40%"><font face="Helvetica,Arial" size="2">E-mail Address :</font></td>
<td></td>
</tr>
<tr>
<td width="3%"></td>
<td width="40%"><font face="Helvetica,Arial" size="2">Support :</font></td>
<td></td>
</tr>
<tr>
<td width="3%"></td>
<td width="40%"><font face="Helvetica,Arial" size="2">Administrator Comment (E-mail) :</font></td>
<td></td>
</tr>
<tr>
<td colspan="3">
<hr size="1">
</td>
</tr>
<tr>
<td width="3%"></td>
<td width="40%"><font face="Helvetica,Arial" size="2">Contact Person :</font></td>
<td></td>
</tr>
<tr>
<td width="3%"></td>
<td width="40%"><font face="Helvetica,Arial" size="2">Phone :</font></td>
<td></td>
</tr>
<tr>
<td width="3%"></td>
<td width="40%"><font face="Helvetica,Arial" size="2">Comment (E-mail) :</font></td>
<td></td>
</tr>
</table>
<p>
<hr size="2">
<table border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td valign="bottom"><img src="en/media/ba_ptp.gif" border="0" hspace="2" vspace="2" alt="Back to the Top on This Page" title="Back to the Top on This Page"></td>
</tr>
</table>
</form>
</body>
</html>
Thanks to amitmah and Gilbert Le Blanc I installed
httpfox addon on firefox and I noticed that I need to set a cookie
URL url = new URL("urlAddress/dinfo.cgi");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("Cookie", "iR=7472571");
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))){
StringBuilder builder = new StringBuilder();
int cp;
while ((cp = in.read()) != -1) {
builder.append((char) cp);
}
return builder.toString();
}
In browser this cookie is set if I access first urlAddress. If I tried to access directly urlAddress/dinfo.cgi I get the same "User information is disabled..." response.

from json it is not returning the result

This is jsp code what is happening is when i submit the code it will call url of ajax function and executing that function also but when returning it will call to other url
If i'm calling ajax from jsp that is going to that particular url and executing it after that it entering to the other url without returning the result
<form name="frm" action="createnewcatgoryBean.jsp" onsubmit="return validatenewcat()" method="post">
<table style="padding: 5px 0px 0px 8px;">
<tr>
<th colspan="2">
<div style="width: width:271px; color:red;" id="validate"></div>
</th>
</tr>
<tr>
<th>Category Name<span>:</span>
</th>
<td>
<input id="cat" onblur="return validatenewcat()" type="text" name="category">
</td>
</tr>
<tr>
<th>Quotations form<span>:</span>
</th>
<td>
<input type="checkbox" name="quotations">
</td>
</tr>
<tr>
<th>Agreement form<span>:</span>
</th>
<td>
<input type="checkbox" name="agreement">
</td>
</tr>
<tr>
<th>Payment form<span>:</span>
</th>
<td>
<input type="checkbox" name="payment">
</td>
</tr>
<tr>
<th>ETI<span>:</span>
</th>
<td>
<input type="checkbox" name="eti">
</td>
</tr>
<tr>
<td colspan="2" style="float:right; padding-top:15px">
<input type="submit" value="Submit" style="width: 60px;">
</td>
</tr>
</table>
</form>
This is the JavaScript code that includes the AJAX request:
function validatenewcat() {
var category = document.getElementById("cat").value;
if (category == "") {
setTimeout(document.getElementById("validate").innerHTML = "!PLz Enter The Category Name", 2000);
return false;
} else {
var url = "catnamecheck.do?id=" + category;
xmlhttp.open("post", url, true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
var temp = xmlhttp.responceText;
obj = JSON.parse(temp);
alert(obj);
if (temp != "") {
document.getElementById("validate").innerHTML = "!PLz Enter The Unique Category Name";
document.getElementById("cat").focus();
return false;
}
}
}
}
}
}
this my java code
public Map<String, String> catuniqecheck(String id) {
Connection c = null;
PreparedStatement ps1 = null;
ResultSet rs1 = null;
String sql=null;
try{
c = JDBCHelper.getConnection();
if(c!=null)
{
Map<String, String> map = new HashMap<String, String>();
sql="select * from catgory where catgoryname=?";
ps1=c.prepareStatement(sql);
ps1.setString(1, id);
ps1.execute();
rs1=ps1.getResultSet();
if(rs1.next())
{
System.out.println("insdide of the catuniqecheck");
map.put("catgoryname",rs1.getString("catgoryname"));
}
return map;
}
else
{
System.out.println("DB connection Established");
return null ;
}
}
catch (Exception e) {
// TODO: handle exception
return null ;
}
finally{
JDBCHelper.close(rs1);
JDBCHelper.close(ps1);
JDBCHelper.close(c);
}
}
this my servlet code
Map<String, String> result =p1.catuniqecheck(id);
if(result!=null)
{
System.out.println("inside success");
JSONObject json = new JSONObject();
json.accumulateAll(result);
System.out.println("inside json"+json.toString());
response.setContentType("application/json");
response.getWriter().write(json.toString());
}
try with
obj = JSON.parse("["+temp+"]")
And then first response length
alert(obj[0].length);
alert(obj[0]);
bcoz sometime response itself inside Square brackets like [{...}]

How to get jquery text editor in multiple text area in one action

I have a jquery text Editor & Have a Multiple Text area I want to show jquery text editor in every text area in one action but only first text area i able to show text editor
Here is my Jquery Code
<script type="text/javascript" id="themeUIPhysicalFinding">
$(document).ready(function () {
var options = {
width: 962,
height: 230,
controls: "bold italic underline strikethrough subscript superscript | font size " +
"style | color highlight removeformat | bullets numbering | outdent " +
"indent | alignleft center alignright justify | undo redo | " +
"rule link image unlink | cut copy paste pastetext | print source"
};
var editor = $("#editor").cleditor(options)[0];
// $("#editor").kendoEditor({
// encoded: false
// });
//alert("asdfasdf");
$("#Generate").click(function () {
alert($("#editor").value());
//$("#editor").val("");
});
});
</script>
My Java Script Action Code is
function getPatientInformationTest(){
var admissionNo=document.getElementById("apnNo").value;
var url = "getPatientDemographyActionTestIPDPatientInfo.do?patientAdmissionNo="+admissionNo;
makeRequestNoImage(url,"patientDischargeDiv" ,"themeUIPhysicalFinding");
here is my HTML code
<%#taglib prefix="s" uri="/struts-tags"%>
<!--
-->
<div>
<table border="0" class="" width="100%">
<tr>
<td><fieldset><legend>Patient Demography </legend><table width="100%" style="border:0px solid #FFFFFF" cellpadding="0" cellspacing="0">
<tr>
<td>HN</td>
<td><s:property value='deschargeInfo.patientRegistrationNo'/></td>
</tr>
<tr>
<td>Age</td>
<td><s:property value='deschargeInfo.patientAge'/></td>
</tr>
<tr>
<td>Name</td>
<td><s:property value='deschargeInfo.patientName'/></td>
</tr>
<tr>
<td>Gender</td>
<td><s:property value='deschargeInfo.patientGender'/></td>
</tr>
<tr>
<td>Contact Info</td>
<td><s:property value='deschargeInfo.patientContactNo'/></td>
</tr>
</table></fieldset></td>
<td><fieldset><legend>Doctor's Info</legend><table width="100%" border="0" style="border:0px solid #FFFFFF" cellpadding="0" cellspacing="0">
<tr>
<td>Admitted Under</td>
<td><s:property value='deschargeInfo.patientAdmittingUnder'/></td>
</tr>
<tr>
<td>Admitted By</td>
<td><s:property value='deschargeInfo.patientAdmittingDoctor'/></td>
</tr>
<tr>
<td>Department Name</td>
<td><s:property value='deschargeInfo.departmentName'/></td>
</tr>
</table></fieldset></td>
<td><fieldset><legend>Admission Information</legend><table width="99%" border="0" style="border:0px solid #FFFFFF" cellpadding="0" cellspacing="0">
<tr>
<td>Date Of Admission</td>
<td><s:property value='deschargeInfo.patientDateOfAdmission'/></td>
</tr>
<tr>
<td>Date Of Discharge</td>
<td><s:property value='deschargeInfo.patientDateOfDischarge'/></td>
</tr>
<tr>
<td>Length of LOS</td>
<td><s:property value=''/></td>
</tr>
<tr>
<td>Ward No</td>
<td><s:property value='deschargeInfo.patientWordNo'/></td>
</tr>
<tr>
<td>Bed/Cabin No</td>
<td><s:property value='deschargeInfo.patientBedNo'/></td>
</tr>
</table></fieldset></td>
</tr>
<tr>
<td height="265" colspan="3"><div id="headerRemoveDiv">
<table class="subTableCC" width="100%">
<tr>
<th width="100%">Header Name</th>
<!-- <th width="42">Remove</th>-->
</tr>
<s:iterator status="stat" value="deschargeList">
<tr>
<td width="100%">
<s:property value="headerName" />
</td>
</tr>
<tr>
<td width="100%" height="211" colspan="8" style="padding:0px;">
<textarea name="textarea" cols="150" rows="13" id="<s:property value='headerNo'/>" ></textarea></td>
</tr>
</s:iterator>
</table></div></td>
</tr>
</table>
</div>
Here is my Java action class code
public String getPatientDemographyActionTest(){
PatientDischargeInfo patientDischargeInfo = new PatientDischargeInfo();
deschargeInfo=patientDischargeInfo.getPatientInfoForDescharge(patientAdmissionNo);
DepartmentHeaderInfo departmentHeaderInfo = new DepartmentHeaderInfo();
deschargeList=departmentHeaderInfo.getDepartmentHeader(patientAdmissionNo);
ActionContext.getContext().getSession().put(sessionVariable.getHeaderInfo(), deschargeList);
return "getPatientDemographyActionTest";
}
Here is my SQL code
public PatientDeschargeInfo getPatientInfoForDescharge(
String p_admission_no) {
//String vDAY_PK_NO = "";
if (dbConnection == null) {
dbConnection = new DatabaseConnection();
}
String strProcedure = "{call pkg_discharge.prc_dispatinfo(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}";
try {
connection = dbConnection.connectDB();
cs = connection.prepareCall(strProcedure);
cs.setString(1, p_admission_no);
cs.registerOutParameter(2, java.sql.Types.DATE);
cs.registerOutParameter(3, java.sql.Types.DATE);
cs.registerOutParameter(4, java.sql.Types.VARCHAR);
cs.registerOutParameter(5, java.sql.Types.VARCHAR);
cs.registerOutParameter(6, java.sql.Types.VARCHAR);
cs.registerOutParameter(7, java.sql.Types.VARCHAR);
cs.registerOutParameter(8, java.sql.Types.VARCHAR);
cs.registerOutParameter(9, java.sql.Types.VARCHAR);
cs.registerOutParameter(10, java.sql.Types.VARCHAR);
cs.registerOutParameter(11, java.sql.Types.VARCHAR);
cs.registerOutParameter(12, java.sql.Types.VARCHAR);
cs.registerOutParameter(13, java.sql.Types.VARCHAR);
cs.registerOutParameter(14, java.sql.Types.VARCHAR);
cs.registerOutParameter(15, java.sql.Types.VARCHAR);
cs.registerOutParameter(16, java.sql.Types.VARCHAR);
cs.registerOutParameter(17, java.sql.Types.VARCHAR);
cs.execute();
//deschargeInfo = new PatientDeschargeInfo();
deschargeInfo.setPatientDateOfAdmission(cs.getDate(2));
deschargeInfo.setPatientDateOfDischarge(cs.getDate(3));
deschargeInfo.setPatientRegistrationNo(cs.getString(4));
deschargeInfo.setPatientName(cs.getString(5));
deschargeInfo.setPatientNationalId(cs.getString(6));
deschargeInfo.setPatientGender(cs.getString(7));
deschargeInfo.setPatientBloodGroup(cs.getString(8));
deschargeInfo.setPatientContactNo(cs.getString(9));
deschargeInfo.setPatientAge(cs.getString(10));
deschargeInfo.setPatientAdmittingDoctor(cs.getString(11));
deschargeInfo.setPatientAdmittingUnder(cs.getString(12));
deschargeInfo.setPatientBedNo(cs.getString(13));
deschargeInfo.setPatientWordNo(cs.getString(14));
deschargeInfo.setPatientAddress(cs.getString(15));
deschargeInfo.setDepartmentId(cs.getString(16));
deschargeInfo.setDepartmentName(cs.getString(17));
// vDAY_PK_NO = cs.getString(9);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
cs.close();
connection.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// System.out.println("pkStrring " + vDAY_PK_NO);
return deschargeInfo;
}
SQL code is ..
public List<PatientDeschargeInfo> getDepartmentHeader(String ADMISSION_NO){
List<PatientDeschargeInfo> deschargeInfo = new ArrayList<PatientDeschargeInfo>() ;
boolean fg = true;
con = dbc.connectDB();
if (con == null) {
fg = false;
}
if(fg){
try{
st=con.createStatement();
String qty ="select LKP_ID , (select lkp_name " +
"from m00_lkp " +
"where grp_id =10 " +
"and rsta = 0 " +
"and lkp_id = a.lkp_id) head_name " +
"from eh_discheadmap a " +
"where dept_no = ( select parent_dept " +
"from hr_dept " +
"where dept_no = (select dept_no " +
"from ip_admission " +
"where admission_no = '"+ADMISSION_NO+"'))";
System.out.println("Qry :"+qty);
rs = st.executeQuery(qty);
while (rs.next()) {
//deschargeInfo.setPatientAddress(rs.getString(""));
//deschargeInfo.setPatientAdmissionNo(rs.getString(""));
PatientDeschargeInfo patientDeschargeInfo = new PatientDeschargeInfo();
patientDeschargeInfo.setHeaderName(rs.getString("head_name"));
patientDeschargeInfo.setHeaderNo(rs.getInt("LKP_ID"));
deschargeInfo.add(patientDeschargeInfo);
//resultList.add(deschargeInfo);
}
} catch (SQLException sq) {
sq.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
return deschargeInfo;
}

Categories

Resources