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..");
}
}
Related
I have 3 pages, I want to do that when I enter name in textbox. Email and Phone display in different textbox using ajax. It displays both values in 1 textbox but I want both values in two different textboxes.
HTML
This is my html page:
<%--
Document : Test
Created on : Oct 10, 2017, 9:59:46 PM
Author : Lenovo
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="Bootstrap/bootstrap.css"/>
<title>JSP Page</title>
</head>
<body>
<form action="NameDB.jsp" method="post" name="add_name" id="add_name">
<table class="table table-bordered" border="1" id="dynamic_field">
<tr>
<th>Enter Name</th>
<th>Enter email</th>
</tr>
<tr>
<td><input type="text" name="name_1" placeholder="Enter Name" size="25" class="searchName" id="search1"/></td>
<td><input type="text" name="email_1" id="esearch1"/></td>
<td><input type="text" name="phone_1" id="psearch1"/></td>
<td>
<button type="button" name="add" id="add">Add More</button>
</td>
</tr>
</table>
<input type="submit" name="submit" value="Submit"/>
</form>
JQuery
This is my Jquery and Ajax
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$(document).ready(function()
{
var i=1;
$('#add').click(function()
{
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" id="search'+i+'" class="searchName" name="name_'+i+'" placeholder="Enter Name"/></td>\n\
<td><input type="text" id="esearch'+i+'" class="searchEmail" name="email_'+i+'"/></td>\n\
<td><input type="text" id="psearch'+i+'" class="searchPhone" name="phone_'+i+'" placeholder="Enter Phone"/></td>\n\
<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td>\n\
<td><input type="hidden" name="count" value="'+i+'"/></td></tr>');
});
$(document).on('click','.btn_remove',function()
{
var button_id=$(this).attr("id");
$('#row'+button_id+'').remove();
});
$(document).on('change','.searchName',function()
{
var id=$(this).attr("id");
var name=$('#'+id).val();
//var email=$('#e'+id).val();
$.ajax({
url:"AjaxDB.jsp",
type:"post",
dataType:"text",
data:{name:name},
cache:false,
success:function(data)
{
//$('#show').html(data);
$('#e'+id).val(data);
}
});
});
});
AjaxDB.JSP
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page language="java"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%
try
{
String name=request.getParameter("name");
String email=null;
String phone=null;
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/atm","root","root");
Statement st=con.createStatement();
ResultSet rs;
rs=st.executeQuery("SELECT * FROM test where name='"+name+"'");
while(rs.next())
{
email=rs.getString("email");
phone=rs.getString("phone");
out.print(email);
out.print(phone);
}
}
catch(Exception e)
{
System.out.println(e);
}
%>
If you want to receive data from server, then it is recommend to use JSON. You are sending data as plain text from "AjaxDB.JSP"
If response is by using JSON, then you should Servlet instead of JSP page.
Both following points are explained through code:
Your servlet code might be following:
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import org.json.simple.*;
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("application/json");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data
JSONObject response = new JSONObject();
try {
String name=request.getParameter("name");
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/atm","root","root");
Statement st=con.createStatement();
ResultSet rs;
rs=st.executeQuery("SELECT * FROM test where name='"+name+"'");
JSONArray list = new JSONArray();
while(rs.next()) {
JSONObject obj = new JSONObject();
obj.put("email",rs.getString("email"));
obj.put("email",rs.getString("phone"));
list.add(obj);
}
response.put("response", list);
} catch(Exception e) {
System.out.println(e);
}
pw.println(response.toJSONString());
pw.close();//closing the stream
}
}
And your client side code can be following:
$.ajax({
url:"AjaxDB.jsp",
type:"post",
dataType:"json",
data:{name:name},
cache:false,
success:function(data) {
console.log(data);
console.log(data.response[0].email);
console.log(data.response[0].phone);
}
});
});
Special Note: The code is untested. So debug if any error found!
i'm trying to create simple market web application. I want to add a sign-in functionality to add users in my db, but i can't understand, how can i "call" my registration method (from java) in js script. Currently, the only thing that my web-app actually does is show records(which i added manually) from users-table.
Here is my db-manager:
`public class DatabaseManager {
public static String host = "localhost";
public static String port = "5432";
public static String dbname = "market";
public static String user = "postgres";
public static String pass = "123456";
public static String url = "jdbc:postgresql://"+host+":"+port+"/"+dbname+"?user="+user+"&password="+pass;
static {
try {
DriverManager.registerDriver(new org.postgresql.Driver());
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
try {
return DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Can not connect to the database:\n"+e.getMessage());
}
return null;
}
public static void closeConnection(Connection connection) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}`
Auth - dto:
public class Auth {
public static class RegisterReq {
public String name;
public String lastname;
public String login;
public String pass;
public int age;
public String gender;
public RegisterReq(String name, String lastname, String login, String pass, int age, String gender) {
this.name = name;
this.lastname = lastname;
this.login = login;
this.pass = pass;
this.age = age;
this.gender = gender;
}
}
public static class RegisterResp {
public boolean status;
public RegisterResp(boolean status) {
this.status = status;
}
}
public static class LoginReq {
public String login;
public String pass;
public LoginReq(String login, String pass) {
this.login = login;
this.pass = pass;
}
}
public static class LoginResp {
public boolean status;
public LoginResp(boolean status) {
this.status = status;
}
}
}
Auth-class with sign-up method:
`
import static dto.Auth.*;
#Path("/auth")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public class Auth {
#POST
#Path("/register")
public RegisterResp register(RegisterReq req) {
boolean result = false;
//sql
Connection connection = null;
try {
connection = DatabaseManager.getConnection();
Statement stmt = connection.createStatement();
String checkSql = "select e_mail from users";
ResultSet resultSet=stmt.executeQuery(checkSql);
while (resultSet.next()) {
if(req.login.equals(resultSet.getString(1))) return new RegisterResp(result);
}
//unsafe query
String sql = "INSERT INTO users" +
" (u_name, u_lastname, e_mail, password, age, gender, reg_date)" +
" VALUES (" +
req.name + ","+
req.lastname + ","+
req.login + ","+
req.pass + "," +
req.age + ","+
req.gender + ","+
new java.sql.Timestamp(new java.util.Date().getTime()) + ")";
result = stmt.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) DatabaseManager.closeConnection(connection);
}
return new RegisterResp(result);
}`
Main page HTML file:
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>Market start page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="./resources/css/app.css">
</head>
<body ng-controller="UserController">
<div style="background: #8fb9ee" class="jumbotron">
<h1>Market homepage</h1>
<h2>Welcome!</h2>
<p align="center">
Register
Log in
</p>
</div>
<hr>
<div >
<ul>
<p style="font-size: xx-large" >Total user count: {{users.length}} </p>
<table class="TableStyle">
<tr class="RowHeaderStyle">
<th >Firstname</th>
<th >Lastname</th>
<th >E-mail</th>
<th >Age</th>
<th >Gender</th>
</tr>
<tr ng-repeat="user in users" class="RowStyle">
<td >{{user.name}}</td>
<td >{{user.lastname}}</td>
<td >{{user.e_mail}}</td>
<td >{{user.age}}</td>
<td >{{user.gender}}</td>
</tr>
</table>
</ul>
</div>
<input type="checkbox" ng-model="value"> admin ?
<div ng-if="value">Admin</div>
<div ng-if="!value">User</div>
<div ng-view></div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-resource.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-route.js"></script>
<script src="./resources/js/app.js"></script>
</body>
</html>
Register HTML-file:
<h2>Register</h2>
<div ng-controller="RegisterController" align="center" class="container-fluid">
<table >
<tr>
<td>First name</td>
<td><input type="text" ng-model="fname"></td>
</tr>
<tr>
<td>Last name</td>
<td><input type="text" ng-model="lname"></td>
</tr>
<tr>
<td>E-mail</td>
<td><input type="text" ng-model="uemail"></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="text" ng-model="upass"></td>
</tr>
<tr>
<td>Gender</td>
<td>
<select ng-model="ugend" >
<option>male</option>
<option>female</option>
</select>
</td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" ng-model="uage"></td>
</tr>
</table>
<button role="button" ng-click="AddUser()"> Confirm </button>
</div>
And app JS file with my silly tries to do something:
`angular.module('app', ['ngResource', 'ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: './resources/partials/login.html',
controller: 'RegisterController'
}).
when('/register', {
templateUrl: './resources/partials/register.html',
controller: 'LoginController'
}).
otherwise({
redirectTo: '/'
});
}])
.controller('UserController', ['$scope', '$resource', function($scope, $resource) {
var User = $resource('/r/users');
var users = User.query(function() {
$scope.users = users;
});
}])
.controller('LoginController', ['$scope', '$resource', function($scope, $resource) {
}])
.controller('RegisterController', ['$scope', '$resource',"$http", function($scope,$http, $resource) {
//here should be something smart
$scope.AddUser = function() {
};
}]);`
I'm working in Intellij, and this is my first try to do something, so don't stone me =).
Roughly, your RegisterController should look like this:
.controller('RegisterController', ['$scope', '$resource', function($scope, $resource) {
var auth = $resource('/auth/:action', null, {
login: {
method: 'POST',
params: {
action: 'login'
},
},
register: {
method: 'POST',
params: {
action: 'register'
}
}
});
$scope.AddUser = function() {
// your data consumed from UI
var data = {
name: $scope.name
lastname: $scope.lastname,
login: $scope.login,
pass: $scope.pass,
age: $scope.age,
gender: $scope.gender
};
auth.register(null, data, function(resp) {
// your callback when response is received
// resp variable contains response data sent from server
if (resp.status) {
// registered successfully
} else {
// some error occurred
}
});
};
}]);
If i understood your question correcty. One way to go about that is to create an angular service to perform the ajax post ill paste an example from a current spring-boot angular app im developping. im using es6 but the conecpt is the same
So here is a snippet of the service
class UserService
{
constructor($http)
{
HTTP.set(this, $http);
}
// getGroups(groupId){
// return HTTP.get(this).get(`/api/v1/group/group/?id=${groupId}`).then(result => result.data.objects );
// }
//
// createUserInGroup(groupId,user){
// return HTTP.get(this).post(`/api/v1/group/user/${groupId}`,user);
// }
updateUser(userId,user){
return HTTP.get(this).put(`/api/v1/user/${userId}`, user);
}
You can tell im injecting the $http angular object to be able to perform the request, you'll have to do the same thing if you decide to go with making a service
In The controller, Im injecting the service
class NewGroupController{
constructor($timeout,$modalInstance, groupSvc,currentGroup){
GROUP_SERVICE.set(this, groupSvc);
MODAL_INSTANCE.set(this,$modalInstance);
TIMEOUT.set(this, $timeout);
CURRENT_GROUP.set(this,currentGroup);
With the Group Service in i can call the method and thats it.
Hope it helps
I'm inexperienced with Java and JSP. I created a form and it works the way it is supposed to, but I want to have some fun with it and have it reorder the results after the form is submitted. I'll include some images to show what I mean. I'm having a hard time searching for what I want and don't really know where to start. Any help will be appreciated.
Here is the form page:
Here is the results:
Here is what I want the results to look like (notice 'last' goes from 2 to 3, 'middle' from 3 to 5, 'item' from 4 to 2, and 'address' from 5 to 4):
Java File
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ShowParameters extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
String title = "Reading All Request Parameters";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Parameter Name<TH>Parameter Value(s)");
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<TR><TD>" + paramName + "\n<TD>");
String[] paramValues =
request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<I>No Value</I>");
else
out.println(paramValue);
} else {
out.println("<UL>");
for(int i=0; i<paramValues.length; i++) {
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");
}
}
out.println("</TABLE>\n</BODY></HTML>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("STOP1\n");
doGet(request, response);
}
}
JSP file
<%# 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>Lab 3</title>
<style type="text/css">
.address {
height: 50px;
}
</style>
</head>
<body>
<body BGCOLOR="#FF0000">
<h1 align="center">Basic FORM</h1>
<form action="ShowParameters" method="post">
First Name: <input type="text" name="first"> <br>
Last Name: <input type="text" name="last" value="$"> <hr/>
Middle Name: <input type="text" name="middle"> <br>
Item: <input type="text" name="item"> <br>
Address: <input type="text" name="address" class="address"> <br>
Credit Card: <br>
<input type="radio" name="cardType" value="Visa">Visa <br>
<input type="radio" name="cardType" value="MasterCard">MasterCard <br>
Credit Card Number: <input type="text" name="cardNum"> <br><br>
<center><input type="submit" value="Submit Order"></center>
</form>
</body>
</html>
instead of creating html in servlet create a class to hold form input information like:
public class Person {
private String firstName;
private String midlleName;
private String lastName;
private String item;
private String address;
private String cardType;
private String cardNumber;
//getters and setters
}
in servlet create instance of Person class and set values then simply add person instance to request and forward to jsp.
Person person = new Person();
person.setFirstName(request.getParameter("first"));
//set other person values here
request.setAttribute("person", person);
request.getRequestDispatcher("filename.jsp").forward(request, response);
in jsp display like:
<table border="2">
<tr bgcolor="#FFAD00">
<th>Parameter Name</th>
<th>Parameter Value(s)</th>
</tr>
<tr>
<td>first</td><td>${person.firstName}</td>
</tr>
<tr>
<td>item</td><td>${person.item}</td>
</tr>
<tr>
<td>last</td><td>${person.midlleName}</td>
</tr>
<tr>
<td>address</td><td>${person.address}</td>
</tr>
<tr>
<td>middle</td><td>${person.lastName}</td>
</tr>
<tr>
<td>cardType</td><td>${person.cardType}</td>
</tr>
<tr>
<td>cardNum</td><td>${person.cardNumber}</td>
</tr>
</table>
Benefits:
easy to change the order as you like in html.(simply move the <tr/> elements)
No need of loop.
Follows Object-oriented programming (OOP) style of programming.
Rather than getting an enumeration of the parameters by request.getParameterNames you could have a string array of all the parameter names you expect with them in the order you want, and you could loop through that array like so:
String[] paramNames = { "item", "last", "first" };
for(int i=0; i<paramNames.length; i++)
{
out.print("<tr>");
out.print("<td>" + paramNames[i] + "</td>");
out.print("<td>");
String[] paramValues = request.getParameterValues(paramNames[i]);
...
...
out.print("</td>");
out.print("</tr>");
}
Please take note that one of the things you are not doing in your code is properly closing the cells with </td> and the rows with </tr>. You should really also close the LIs with </li>.
Hi, my problem is increasing the table row automatically. Actually, when I click GET button the product type and product name values are getting from database. Here, after getting those values, I will give another id based on that id again for values will come. But it was not setting in another row. Here is my java code and jsp:
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver loaded");
System.out.println("Driver is loaded");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/charms?user=root&password=root");
System.out.println("Connection created");
Statement st =con.createStatement();
String query="select * from product where ProductType_v='"+a+"' and ProductId_v='"+b+"'";
ResultSet rs = (ResultSet)st.executeQuery(query);
int i=0;
while(rs.next())
{
i++;
request.getSession().setAttribute("edit","success");
request.getSession().setAttribute("proType ", rs.getString("ProductType_v"));
request.getSession().setAttribute("proId", rs.getString("ProductId_v"));
request.getSession().setAttribute("strength", rs.getString("Strength_v"));
request.getSession().setAttribute("proName", rs.getString("ProductName_v"));
request.getSession().setAttribute("brand", rs.getString("BrandName_v"));
request.getSession().setAttribute("generic", rs.getString("GenricName_v"));
request.getSession().setAttribute("uom", rs.getString("UOM_v"));
request.getSession().setAttribute("formE", rs.getString("FormE_v"));
request.getSession().setAttribute("presReqd", rs.getString("PresReqd_v"));
}
if(i==0)
{
request.getSession().setAttribute("edit", "fail");
}
}
catch(Exception e)
jsp code
<tr>
<td>
<input class="textfield-form-date-req" type="text" id="pro_type">
</td>
<%
if(editStatus =="success")
{
%>
<script type="text/javascript">
document.getElementById("pro_type").value='<%=session.getAttribute("proType")%>';
</script>
<%
}
<td>
<input class="textfield-form-date-req" type="text" id="pro_id">
</td>
<%
if(editStatus =="success")
{
%>
<scripttype="text/javascript">
document.getElementById("pro_id").value='<%=session.getAttribute("proName")%>';
</script>
<%
}
%>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
I have created a sample for you with ajax. It gets the data from the server side and append it , in the existing table.
The jar files I have used is ,
jackson-all-1.9.0.jar - to convert the java object to json format
servlet-api-2.4.jar - for servlet
My TableAppend.jsp will be,
<%# 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>Insert title here</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
//alert("DOM is ready");
});
function sendData() {
$.ajax({
type : 'POST',
url : "TableAppend",
data : "name=" + $('#name').val() + "&age=" + $('#age').val()
+ "&sid=" + new Date(),
dataType : 'html',
success : function(result) {
//alert("Result ::::>>> "+result);
if(result != null && $.trim(result) != "" && result != undefined){
var json = JSON.parse(result);
//alert(json.name);
//alert(json.age);
appendToTable(json.name, json.age);
}
},
error : function(e) {
alert('Error in Processing');
}
});
}
function appendToTable(name, age) {
var tr = "<tr><td>" + name + "</td><td>" + age + "</td></tr>"
$('#mytable').append(tr);
}
</script>
</head>
<body>
Name :
<input type="text" id="name" name="name" /> Age :
<input type="text" id="age" name="age" />
<input type="button" value="Append to table" onclick="sendData()">
<br></br>
<br></br>
<br></br>
<table id="mytable" border="1">
<tbody>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>HumanBeing</td>
<td>25</td>
</tr>
<tr>
<td>Saideep</td>
<td>26</td>
</tr>
</tbody>
</table>
</body>
</html>
My TableAppend.java servlet will be,
public class TableAppend extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public TableAppend() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("UTF-8");
response.setContentType("UTF");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String age = request.getParameter("age");
String json ="";
System.out.println("-----------------");
if(name != null && age != null){
TableAppendPojo obj = new TableAppendPojo();
obj.setName(name);
obj.setAge(age);
ObjectMapper mapper = new ObjectMapper();
json = mapper.writeValueAsString(obj);
System.out.println("json : "+json);
}
out.println(json);
}
}
Then java class will be,
public class TableAppendPojo {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
Note : Please apply the above logic in your code . In your case , you don't need to give the data from the UI. You retrieves the data from the database in the servlet.So please convert the retrieved data from the database to the json format and append it to the table.
Hope this helps.
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">