I created a web application that edit a database...
I would like to know how I add or redirect the page after clicking on submit.
Sorry i'm still learning...
Currently Im using "usebean" to insert the content of the form to the database. I would like to know if how to redirect the page after the enter all info in the fields then click submit..
Thanks
here's the code:
<%# page language="Java" import="java.sql.*" %>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<html>
<head><title>CSN Survey</title></head>
<body bgcolor="#ffffff">
<div>
<img id="title" src="images/CSN.gif" width="243" height="27" alt="CSN"/>
<img id="logo" src="images/tr_logo_40.gif" width="178" height="40" alt="tr_logo_40"/>
</div>
<hr>
<h1> insert comment </h1>
<div id="container">
<form action="" name="form1" method="POST">
<br>
<br>
<br>
<td><br>Write your comment here:</td>
<div id="q1"
<td>id:<%=request.getParameter("id")%></td>
<td>First name:<textarea name="first_name" rows="1" cols="10"></textarea></td>
<td>Last name:<textarea name="last_name" rows="1" cols="10"></textarea></td>
<br>
<br>
</div>
<td>
<input type = "submit" value="Submit">
</td>
</form>
</div>
<jsp:useBean id="survey" class="csnsurveysource.csnsurveyclass" scope="page">
<jsp:setProperty name="survey" property="*"/>
</jsp:useBean>
<% survey.insert();%>
</body>
</html>
csnsurveyclass.java:
package csnsurveysource;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
public class csnsurveyclass
{
private int id;
private String first_name;
private String last_name;
private Connection connection=null;
private ResultSet rs = null;
private Statement st = null;
String connectionURL = "jdbc:postgresql://localhost:5432/test";
public csnsurveyclass()
{
try {
// Load the database driver
Class.forName("org.postgresql.Driver");
// Get a Connection to the database
connection = DriverManager.getConnection(connectionURL, "postgres", "qqQQ11!!");
}catch(Exception e){
System.out.println("Exception is ;"+e);
}
}
public void setid(int id)
{
this.id = id;
}
public int getid()
{
return (this.id);
}
public void setfirst_name(String first_name)
{
this.first_name = first_name;
}
public String getfirst_name()
{
return (this.first_name);
}
public void setlast_name(String last_name)
{
this.last_name = last_name;
}
public String getlast_name()
{
return (this.last_name);
}
public void insert()
{
try
{
String sql = "update testing set fname = '"+first_name+"',lname = '"+last_name+"' where id = "+id+"";
Statement s = connection.createStatement();
s.executeUpdate (sql);
s.close ();
}
catch(Exception e){
System.out.println("Exception is ;"+e);
}
}
}
It will be good to use MVC pattern, you can move business logic
survey.insert();
into controller and then send redirect
response.sendRedirect("...");
put where you want to redirect in the action inside your form tag
<form action="put here ur action/url" name="form1" method="POST">
Related
This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 5 years ago.
This is my first time asking so im sorry in advance if i messed up.Ok so here it goes
i have this mysql table that i want to display in a jsp page and i actually got it to work but its not really a good approach since all the code(connecting to the database etc) is in the JSP.So i made a java bean that controls the connecting to database and executing sql query part , and a separate JSP page where i can display the table.
main.jsp
<%# page import="java.sql.*" %>
<?xml version='1.0' encoding='UTF-8' ?>
<!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"
xmlns:h="http://java.sun.com/jsf/html">
<head>
<title>Welcome to Car Rental System</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css"></link>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<script src="jquery.backstretch.min.js"></script>
<link rel="stylesheet" href="style.css"></link>
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro" rel="stylesheet">
</head>
<body>
<p><div><center><h1><b>Car Rental System</b></h1></center></div></p>
<%
<jsp:useBean id="displayCarList" class="displayCarList.displayCarList" >
<jsp:setProperty name="displayCarList" property="*"/>
</jsp:useBean>
<%
String carbookId = request.getParameter("carbookId");
String manufacturername = request.getParameter("manufacturername");
String modelname = request.getParameter("modelname");
String price_day = request.getParameter("price_day");
%>
<table border='3' align='center'>
<tr>
<td><b>Car ID</td>
<td><b>Manufacturer</td>
<td><b>Model name</td>
<td><b>Price per day</td>
</tr>
<tr>
<td><%=displayCarList.getCarbookid()%></td>
<td><%=displayCarList.getManufacturername()%></td>
<td><%=displayCarList.getModelname()%></td>
<td><%=displayCarList.getPriceday()%></td>
</tr>
</table>
<br></br>
<form action=secondpage.jsp method="post">
<fieldset><legend>Fill in the form below :</legend>
<p><b>Name:</b> <input type="text" name="name" size="20" maxlength="40" /></p>
<p><b>Telephone number</b> <input type="text" name="phonenumber" th:field="*{phonenumber}" size="20" maxlength="40" /></p>
<p><b>Rental date:</b> <input type="date" th:field="*{rentaldate}" name="rentaldate"></p>
<p><b>Return date:</b> <input type="date" th:field="*{returndate}" name="returndate"></p>
<p><b>Car ID:</b> <input type="text" name="carID" th:field="*{carID}" size="20" maxlength="40" /></p>
<div align="left"><input type="submit" name="submit" value="Submit " /></div>
</form>
<script>
$.backstretch("background2.jpg");
</script>
</body>
</html>
The following is the java bean, displayCarList.java
package displayCarList;
import java.io.*;
import static java.lang.System.out;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class displayCarList {
private String carbookId, manufacturername, modelname, price_day;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
public displayCarList(){
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(displayCarList.class.getName()).log(Level.SEVERE, null, ex);
}
con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/rentalcar","root","");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM carlist");
while(rs.next()){
carbookId = rs.getString(1);
manufacturername= rs.getString(2);
modelname = rs.getString(3);
price_day = rs.getString(4);
}
stmt.close();
con.close();
// displaying record
} catch (SQLException e) {
System.out.println("couldnotconnecYO");
}
}
public String getCarbookid(){
return carbookId;
}
public void setCarbookid(){
this.carbookId = carbookId;
}
public String getManufacturername(){
return manufacturername;
}
public void setManufacturername(){
this.manufacturername = manufacturername;
}
public String getModelname(){
return modelname;
}
public void setModelname(){
this.modelname = modelname;
}
public String getPriceday(){
return price_day;
}
public void setPriceday(){
this.price_day = price_day;
}
}
But for some reason, only one record is displayed which is the last one , where it shouldve returned everything in the table(supposedly)
enter image description here
So i would appreciate if you guys could help me and point out what i did wrong , and help me get all the records in the table displayed like this one
enter image description here
thanks again
UPDATE
As per the instructions by Shuddh i made a few changes to the codes and yet it still doesnt work for some bloody reason
public ArrayList displayCarList(){
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(displayCarList.class.getName()).log(Level.SEVERE, null, ex);
}
con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/rentalcar","root","");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM carlist");
while(rs.next()){
int i = 1;
while(i <= 12){
carlist.add(rs.getString(i++));
}
}
stmt.close();
con.close();
// displaying record
} catch (SQLException e) {
System.out.println("couldnotconnecYO");
}
return carlist;
}
its now returning null in every colum
The reason you are getting just last row is because you are not storing the other rows anywhere. So it overwrites the variables and this last row is being captured. Store the local variable as list and that will do the trick.
Create a List and add every resultset into that
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(displayCarList.class.getName()).log(Level.SEVERE, null, ex);
}
con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/rentalcar","root","");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM carlist");
while(rs.next()){
carbookId = rs.getString(1);
manufacturername= rs.getString(2);
modelname = rs.getString(3);
price_day = rs.getString(4);
// add to list here.
}
stmt.close();
con.close();
// displaying record
} catch (SQLException e) {
System.out.println("couldnotconnecYO");
}
return List. // If you have no idea about list in java google it and learn how to use it
Write your above code in a method and not in constructor.
I'm trying to create Java web application using tomcat 8 server in eclipse.
I've created servlet which forwards request to jsp page and initialize table inside this page with data from two tables. I've been following several examples on the internet on how to fill html table with recoreds from MySQL DB but failed. I'm using MainServlet's doGet method to get data from my local database into list and set it as attribute in request. But when i'm launching servlet there are no records in jsp table. Servlet connects to db and recieves records from it (i've already debugged app). So what is wrong with my code? I'm new to html and css,servlet and jsp technology. Maybe problem is with css framework i'm using (Materialize CSS).
Here is my MainServlet.java code:
package redirect;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import util.Book;
#WebServlet(name="Libbook",urlPatterns={"/libbook"})
public class MainServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static String url = "jdbc:mysql://localhost:3306/Test";
private static String user = "user",password = "password";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
List<Book> books = new ArrayList<>();
Connection connection = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url,user,password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(
"SELECT IDBook,Title,AddDate,ISBN,Name,Sirname "
+ "FROM Book INNER JOIN Author "
+ "ON Book.IDAuthor = Author.IDAuthor;");
while (resultSet.next())
{
Book b = new Book();
b.setId(resultSet.getInt(1));
b.setTitle(resultSet.getString(2));
b.setIsbn(resultSet.getLong(4));
b.setDate(resultSet.getDate(3).toString());
b.setName(resultSet.getString(5));
b.setSirname(resultSet.getString(6));
books.add(b);
}
}
catch (SQLException | ClassNotFoundException e)
{
e.printStackTrace();
}
finally {
try {if(connection != null)connection.close();}catch (SQLException e) {e.printStackTrace();}
}
request.setAttribute("books", books);
request.getRequestDispatcher("pages/libbook.jsp").forward(request, response);
}
}
libbook.jsp page:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8"/>
<title>LibBook</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<style type="text/css">
.logo{
color: #444;
text-transform: uppercase;
letter-spacing: 0.3em;
font-size: 2em;
}
.logo img{
width: 5%;
margin: 0.5%;
vertical-align: middle;
margin-right: 0.5em;
}
</style>
</head>
<body>
<nav class="white">
<div class="navbar-wrapper container">
<a id="logo-container" href="#" class="logo">
LIBBOOK
<img src="assets/book.svg" alt="LibBooklogo">
</a>
<ul class="right">
<li><a class="waves-effect waves-light btn" href="pages/new_author.jsp"><i class="material-icons left">perm_identity</i>NEW AUTHOR</a></li>
<li><a class="waves-effect waves-light btn" href="pages/new_book.jsp"><i class="material-icons left">class</i>NEW BOOK</a></li>
</ul>
</div>
</nav>
<div class="container">
<div class="row">
<div class="card-panel">
<form action="test">
<div class="input-field">
<input placeholder="Type here (title,author) and press enter.." id="search_bar" type="text">
<label for="search_bar">Search</label>
</div>
</form>
</div>
</div>
<div class="row">
<div class="card-panel">
<table>
<thead>
<tr>
<th>ISBN</th>
<th>Title</th>
<th>Author</th>
<th>Info/Edit</th>
<th>Remove</th>
</tr>
</thead>
<c:forEach var="book" items="${books}">
<tr>
<td><c:out value="${book.isbn}"/></td>
<td><c:out value="${book.title}"/></td>
<td><c:out value="${book.name}"/></td>
<td>
<i class="material-icons">mode_edit</i>
</td>
<td>
<i class="material-icons">delete</i>
</td>
</tr>
</c:forEach>
</table>
</div>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
</body>
</html>
Book class:
package util;
import java.io.Serializable;
public class Book implements Serializable
{
private Integer id;
private String title;
private String date;
private Long isbn;
private String name;
private String sirname;
public Book(){
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Long getIsbn() {
return isbn;
}
public void setIsbn(Long isbn) {
this.isbn = isbn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSirname() {
return sirname;
}
public void setSirname(String sirname) {
this.sirname = sirname;
}
}
Found solution. Problem was in jsp file, i did not include imports related to c tag scriplet:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%# taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
And didn't add jstl-1.2.jar library to my project
Java looks for a getter method in a bean class to read the data.
As you bean class(Book) getter method names are like getISBN(), getTitle() , getAName() etc. You should use code in jsp like
<td><c:out value="${book.iSBN}"/></td>
<td><c:out value="${book.title}"/></td>
<td><c:out value="${book.aName}"/></td>
i have a jsp page that gets two parameters 1 for adding another for viewing.this jsp page is named as sucessAdmin.jsp. I have another jsp page admin1.jsp which calls sucessadmin.jsp. admin1.jsp has a form view and add.so if i press the view button it calls sucessAdmin.jsp and displays datas. when i press the add button then it displays a form to enter data but its not adding values to the mysql DB. when i call the same page again,it does not add the data.Please tell me where i have mistake
this is the bean
package sucessAdmin;
import java.sql.*;
import java.io.*;
import java.util.*;
public class sucessAdmin {
private String question;
private String answer;
private String questionNo;
private String opt1;
private String opt2;
private String opt3;
private String opt4;
public sucessAdmin()
{
}
public void setQuestion(String question)
{
this.question=question;
}
public String getQuestion()
{
return question;
}
public void setAnswer(String answer)
{
this.answer=answer;
}
public String getAnswer()
{
return answer;
}
public void setQuestionNo(String questionNo)
{
this.questionNo=questionNo;
}
public String getQuestionNo()
{
return questionNo;
}
public void setOpt1(String opt1)
{
this.opt1=opt1;
}
public String getOpt1()
{
return opt1;
}
public void setOpt2(String opt2)
{
this.opt2=opt2;
}
public String getOpt2()
{
return opt2;
}
public void setOpt3(String opt3)
{
this.opt3=opt3;
}
public String getOpt3()
{
return opt3;
}
public void setOpt4(String opt4)
{
this.opt4=opt4;
}
public String getOpt4()
{
return opt4;
}
public Vector getDetails()
{
int x=0;
Vector v= new Vector();
try
{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/Ontest";
Connection con=DriverManager.getConnection(url,"root","spanwave");
ResultSet rs=null;
Statement st=con.createStatement();
rs=st.executeQuery("select * from questions");
String quer="SELECT * FROM questions";
rs=st.executeQuery(quer);
ResultSetMetaData rsmd = rs.getMetaData();
int NumOfCol=0;
NumOfCol=rsmd.getColumnCount();
System.out.println("Query Executed!! No of Colm="+NumOfCol);
while(rs.next())
{
for(int i=1;i<NumOfCol+1;i++)
{
if(i==NumOfCol)
{System.out.print(rs.getString(i));System.out.println();}else
System.out.print(rs.getString(i)+" ");
v.addElement(rs.getString(i));
}
}
}
catch(Exception e)
{
System.out.println(e);
}
return v;
}
public void addDetails(String question,String opt1,String opt2,String opt3,String opt4,String questionNo,String answer)
//public void addDetails()
{
int qnNo=0;
try
{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/Ontest";
Connection con=DriverManager.getConnection(url,"root","spanwave");
ResultSet rs=null;
qnNo=Integer.parseInt(questionNo);
PreparedStatement ptst=con.prepareStatement("insert into questions values(?,?,?,?,?,?,?)");
ptst.setString(1,question );
ptst.setString(2,opt1 );
ptst.setString(3,opt2 );
ptst.setString(4,opt3 );
ptst.setString(5,opt4 );
ptst.setInt(6, qnNo);
ptst.setString(7,answer);
ptst.executeUpdate();
int NumOfCol=0;
System.out.println("Query Executed!! No of Colm="+NumOfCol);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
this is the calling page
<%# 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>
<jsp:useBean id="admin" scope="request" class="admin.adminBean">
<jsp:getProperty property="userId" name ="admin"/>
</jsp:useBean>
<jsp:useBean id="sucessAdmin" scope ="request" class="sucessAdmin.sucessAdmin"></jsp:useBean>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title><jsp:getProperty property="userId" name ="admin"/></title>
</head>
<body bgcolor="pink">
<form action="details.jsp" method="get">
view questions<input type="radio" name="details" value="view"><br>
edit questions
<input type="radio" name="details" value="edit"><br>
add questions
<input type="radio" name="details" value="add"><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
this is the called page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><jsp:useBean id="sucessAdmin" scope ="request" class="sucessAdmin.sucessAdmin">
</jsp:useBean>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Details</title>
</head>
<body>
<%String input; %>
<%=input=request.getParameter("details") %>
<%if (input.equals("view")) {
%><%Vector v; %>
<%v=(Vector)sucessAdmin.getDetails();
out.println(sucessAdmin.getDetails()); }
%><%
if(input.equals("add"))
{out.println("addds");
%>
<form method="POST" action="details.jsp">
<table>
<tr>
<td>question<input type="text" name="question" value="" /></td>
</tr>
<tr>
<td>opt1<input type="text" name="opt1" value="" /></td>
</tr>
<tr>
<td>opt2<input type="text" name="opt2" value="" /></td>
</tr>
<tr>
<td>opt3<input type="text" name="opt3" value="" /></td>
</tr>
<tr>
<td>opt4<input type="text" name="opt4" value="" /></td>
</tr>
<tr>
<td>questionNumber<input type="text" name="questionNo" value="" /></td>
</tr>
<tr>
<td>answer<input type="text" name="answer" value="" /></td>
</tr>
</table><br><input type="hidden" name="details"/>
<br><input type="submit" name="submit" value="submit"/>
<%sucessAdmin.addDetails("question","opt1","opt2","opt3","opt4","questionNo","answer");%>
</form>
<%out.println("adding");}
%>
</body>
</html>
replace <%sucessAdmin.addDetails("question","opt1","opt2","opt3","opt4","questionNo","answer");%>
with
<%
String question = request.getParameter("question");
String opt1= request.getParameter("opt1");
String opt2 = request.getParameter("opt2");
String opt3 = request.getParameter("opt3");
String opt4 = request.getParameter("opt4");
String questionNo = request.getParameter("questionNo");
String answer = request.getParameter("answer");
if(question!=null && opt1!=null && opt2 != null
opt3!=null && opt4 !=null && questionNo!=null && answer!=null)
{
sucessAdmin.addDetails(question,opt1,opt2,opt3,opt4,questionNo,answer);
}
%>
Try this and let's hope it works..
In my application I have a username with a textbox, a checkbutton and a password. After entering the username into the textbox, if I click on check button it should search in the MySQL database for the username, if it is available it should display the message if not an other message should be displayed.
How do I do that with JSP?
i tried the follwing code:
<form method="post" name="frm_addUser" action="./adduserserver.jsp"><br><br>
<table width="500px;" border="0" cellpadding="5" cellspacing="1" bgcolor="#f8f8ff" bordercolor="#333366" align="center">
<tr>
<td bordercolor="Gainsboro"><font size="4">User ID</font></td>
<td bordercolor="Gainsboro"><input name="userid" style="WIDTH: 200px"></td></tr>
<tr>
<td bordercolor="Gainsboro"><font size="4"> </font></td>
<!--<td><input value="Check availability" onclick="" class="btn_checkavail" type="button"></td></tr>-->
</td>
<td>
<input type="submit" value="check" name="check"
onclick="" /></td></tr>
<tr>
<td bordercolor="Gainsboro"><font size="4">Pass Word </font></td>
<td bordercolor="Gainsboro"><input name="password" type="password" style="WIDTH: 200px"></td></tr>
<tr>
<td bordercolor="Gainsboro"><font size="4">Confirm Password </font></td>
<td bordercolor="Gainsboro"><input name="confirmpassword" type="password" style="WIDTH: 200px"></td></tr>
<tr>
<%
try{
String username=request.getParameter("username");
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","sumith");
st=con.createStatement();
sqlQuery="select distinct username from usernameexist where username='"+username+"'";
rs=st.executeQuery(sqlQuery);
int count=0;
while(rs.next())
{
count++;
}
if(count>0)
{
out.println("<html>");
out.println("<head>");
out.println("<title>MeterDetailsPage</title>");
out.println("</head>");
out.println("<body>");
out.println("<table align='center' color='red'>");
out.println("<tr color='red'>");
out.println("<td ><font size=4 color=red >username Already Exist</font></td>");
out.println("</tr>");
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
else
{
if(username!=null )
{
if(!username.equals(""))
{
//st.executeUpdate("insert into usernameexist(username) values('"+username+"')");
out.println("<html>");
out.println("<head>");
out.println("<title>username</title>");
out.println("</head>");
out.println("<body>");
out.println("<table align='center'>");
out.println("<tr>");
out.println("<td ><font size=4 color=green><b>available </b></font></td>");
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
}
}
st.close();
con.close();
}
catch(Exception e){}
%>
</table>
</form>
</body>
</html>
Try This it will work,
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index Page</title>
<script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
<script src="js/app-ajax.js" type="text/javascript"></script>
</head>
<body>
Enter Your Name: <input type="text" id="name" /><br>
Enter our user name :<input type="text" id="userName"><br>
Enter your Password :<input type="password" id="password"><br>
<input type="button" value="Submit" onclick="ajaxCall();">
<br>
<strong> Response</strong>:
<div id="ajaxGetUserServletResponse"></div><br>
</body>
</html>
Ajax file
function ajaxCall(){
var name = jQuery("#name").val();
var userName = jQuery("#userName").val();
var password= jQuery("#password").val();
alert(name);
alert(userName);
alert(password);
jQuery.ajax({
url : "GetUserServlet",
method: "GET",
type : "JSON",
data : "name="+name+"&userName="+userName+"&password="+password,// query parameters 1st
success : function(response){
$('#ajaxGetUserServletResponse').text(response);
}
});
}
Servlet
import java.io.IOException;
import java.util.ArrayList;
import javax.management.relation.RelationSupportMBean;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
userBean ub = new userBean();
String name = request.getParameter("name").trim();
String userName = request.getParameter("userName").trim();
String password = request.getParameter("password").trim();
System.out.println("name catched "+name);
System.out.println("username catched"+userName);
System.out.println("Password catched"+password);
ArrayList<userBean> list = new ArrayList<userBean>();
ub=new userBean();
ub.setName(name);
ub.setUserName(userName);
ub.setPassword(password);
list.add(ub);
response.setContentType("text/plain");
response.getWriter().print(list);
}
}
Pojo Class
public class userBean
{
private String name;
private String userName;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
My scenario was little bit different you can alter the code in index.jsp and add the call on button "Check Availability" and bring the response from servlet.
check your table name in query
select distinct username from usernameexist where username='"+username+"'";
make sure your table is usernameexist
and
String username=request.getParameter("username");
here parameter is userid not username
so use
String username=request.getParameter("userid");
Your should do below :
Make sure that your jsp is passing all fields including checked field to servlet. You can do form post which has all attributes.
Your servlet should read all parameters and if check-box is checked then you put appropriate logic in servlet (like querying your MySQL db)
Return proper response from your servlet so that jsp can show appropriate message. You can keep messages in your jsp/js and based on flag you can show appropriate message to user.
you can use as follows.. attach jquery file in source code
<script src="jquery-1.9.1.js">
IN Form
<input type="text" name="userName" id="userName" onBlur="checkId(this.value)">
<span id="status"></span>
<script type="text/javascript">
function checkId(member_id)
{
$.ajax({
type: "POST",
url: "processAjax.jsp", /* The request will be processed in this file.. */
beforeSend: function() {
$("#divIdStatus").html("geting name...");
},
data: "member_id=" + member_id ,
success: function(msg) {
$("#divIdStatus").html(msg);
}
});
}
IN processAjax.js
String member_id = (request.getParameter("member_id")).trim();
if (member_id.equals("")) {
out.print("! This is Required");
} else {
ResultSet result = // check in database if any record with this user name;
if (result.next()) {
out.print("! Not Available");
} else {
out.print("OK..");
}
}
Its my jsp page from where i'm sending the data to javabean:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#taglib uri="/struts-tags" prefix="s" %>
<%#taglib uri="/struts-dojo-tags" prefix="sx" %>
<%#page session="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<sx:head parseContent="true" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Set the Leaves </title>
<script language="JavaScript" src="../Advance_Academic_ERP/css/Ck_Effect.js"></script>
<link rel="stylesheet" type="text/css" media="all"
href="../Advance_Academic_ERP/css/jsDatePick_ltr.min.css" />
<script type="text/javascript"
src="../Advance_Academic_ERP/css/jsDatePick.min.1.3.js"></script>
<script type="text/javascript">
window.onload = function(){
new JsDatePick({
useMode:2,
target:("fromDate"),
dateFormat:"%d-%m-%Y"
});
new JsDatePick({
useMode:2,
target:("toDate"),
dateFormat:"%d-%m-%Y"
});
};
</script>
<script type="text/javascript">
function display(val) {
var o = document.getElementById('name1');
var b = document.getElementById('leaveNo1');
(parseInt(val) == '5' || parseInt(val)=='6')? o.style.display = 'block' : o.style.display = 'none';
(parseInt(val) == '5' || parseInt(val)=='6')? b.style.display = 'block' : b.style.display = 'none';
}
</script>
</head>
<body>
<s:form action="LeaveSetterAction" name="leave" validate="true">
<s:select label="Type Of Holiday/Leave*"
headerKey="-1" headerValue="Select Type"
list="#{'1':'National Holidays', '2':'Weekly Holidays', '3':'Local Holidays', '4':'Situational Holidays', '5':'Seek Leaves', '6':'Personal Leaves'}"
name="leaveType" id="leaveType" onchange="display(this.value);"/>
<table id="name1" style="display: none;">
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
</tr>
</table>
<table id="leaveNo1" style="display: none;">
<tr>
<td>No Of Alloted Leaves</td>
<td><input type="text" name="leaveNo" id="leaveNo"></td>
</tr>
</table>
<s:textfield name="fromDate" label="From date*" key="fromDate" id="fromDate"></s:textfield>
<s:textfield name="toDate" label="To date*" key="toDate" id="toDate"></s:textfield>
<s:textfield name="difference" label="Duration" key="difference" id="difference" readonly="readonly"></s:textfield>
<s:textarea name="desc" label="Description*" key="desc" onmouseover="setDifference(this);"></s:textarea>
<s:submit align="center"></s:submit> <s:reset align="center"></s:reset>
</s:form>
</body>
</html>
Its mine javabean page where i'm supposed to get the data:
package abc.Model;
public class SetLeave {
String leaveType;
String name;
String leaveNo;
String fromDate;
String toDate;
String difference;
String desc;
public String getLeaveType() {
return leaveType;
}
public void setLeaveType(String leaveType) {
this.leaveType = leaveType;
}
public String getName() {
System.out.println(name);
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLeaveNo() {
System.out.println(leaveNo);
return leaveNo;
}
public void setLeaveNo(String leaveNo) {
this.leaveNo = leaveNo;
}
public String getFromDate() {
return fromDate;
}
public void setFromDate(String fromDate) {
this.fromDate = fromDate;
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public String getDifference() {
return difference;
}
public void setDifference(String difference) {
this.difference = difference;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
I'm using javascript on some textfields which are getting null values
Please help me out.
Thanks in advance.
<s:textfield name="difference" label="Duration" key="difference" id="difference" disabled="true"></s:textfield>
In this field you have disabled="true", so the value that would be send to the Model/Bean would be null obviously.
<s:textfield name="difference" label="Duration" key="difference" id="difference" disabled="true"></s:textfield>
<s:hidden name="difference"/>
If you want to send value to your bean. If you still get error, then reply.
Ok , Get this done and reply..
<table id="name" style="display: none;">
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
</tr>
</table>
<table id="leaveNo" style="display: none;">
<tr>
<td>No Of Alloted Leaves</td>
<td><input type="text" name="leaveNo" id="leaveNo"></td>
</tr>
</table>
You are using same id's for table and textfield in both the above cases change the id of table to name1 and leaveNo1 and try. I guess this is the only problem.
Your solution is there in the below code paste it and enjoy.
<s:textfield name="difference" label="Duration" key="difference" id="difference" readonly="readonly"></s:textfield>