redirects not working in jsp - java

i have created a jsp page view.jsp and corresponding to that i have created a servlet admin.java
code of both below...
when i click on register a blank page appears...redirects are not working. please help me in resolving this
view.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="admin">
username <input type="text" name="username" value="" />
password <input type="text" name="password" value="" />
<input type="submit" name="register" value="register" />"
</form>
</body>
</html>
admin.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class admin extends HttpServlet {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/inventory";
static final String USER = "root";
static final String PASS = "root";
Connection conn = null;
Statement stmt = null;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
try {
String user = req.getParameter("username");
String pass = req.getParameter("password");
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "select * from admins";
//String sql = "select * from admins WHERE username='"+user+"' AND
password='"+pass+"'";
ResultSet rs = stmt.executeQuery(sql);
PrintWriter pw = res.getWriter();
//res.setContentType("text/html");
while (rs.next())
{
if((user.equals(rs.getString(0))) && (pass.equals(rs.getString(1))))
{
//String n=rs.getString("username");
//String p=rs.getString("password");
res.sendRedirect("loginsuccess.jsp");
}
else
{
res.sendRedirect("loginfailure.jsp");
}
}
pw.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Use RequestDispatcher instead of sendRedirect():
RequestDispatcher reqDispatcher = req.getRequestDispatcher("path/loginsuccess.jsp");
reqDispatcher.forward(req, res);
Read more about RequestDispatcher.
Read the difference between RequestDispatcher and sendRedirect, and whento use both of them.

Try this
getServletContext().getRequestDispatcher("/loginsuccess.jsp").forward(request, response);

sample code :
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user); // Login user.
response.sendRedirect("home"); // Redirects to http://example.com/context/home after succesful login.
} else {
request.setAttribute("error", "Unknown login, please try again."); // Set error.
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to same page so that you can display error.
}
you should try that method, but my suggestion as:
I think you should not close the statement, result set and connection,.
And then you should check the if condition. if maybe your condition have an error the page like empty. so should check that..
source from : https://stackoverflow.com/a/2048640/3242978

When you click 'register' button it submits the form as a HTTP POST request. You need to implement doPost() instead.

Related

Java not connecting to database

I'm trying to get my java code to connect to the database. I swear it was connecting a few hours ago and suddenly it's not. I have reinstalled, restarted xampp, eclipse my laptop. I even uninstalled and reinstalled mysql.
Here's my .java file:
import java.sql.DriverManager;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
public class Connect_db {
// private static final String url = "jdbc:mysql://localhost:3306/sjsu";
// private static final String user = "root";
// private static final String password = "";
//
// public static void main(String[] args) throws Exception {
// java.sql.Connection con = null;
// try {
// Class.forName("com.mysql.jdbc.Driver");
// con = DriverManager.getConnection(url, user, password);
// // commented since doesn't exists in Java 6
// // System.out.println(con.getSchema());
// System.out.println(con.getCatalog());
// } finally {
// con.close();
// }
// }
private static MysqlDataSource ds = null;
public static MysqlDataSource getDataSource(String db_name) {
if (ds == null) {
// db variables set here
getDataSource("jdbc:mysql://localhost:3306", "root", "", 3306);
}
ds.setDatabaseName(db_name);
return ds;
}
private static void getDataSource(String db_url, String db_user, String db_password, int db_port) {
try {
ds = new MysqlDataSource();
ds.setServerName(db_url);
ds.setUser(db_user);
ds.setPassword(db_password);
ds.setPort(db_port);
} catch (Exception e) {
System.out.println("MysqlDataSource err: " + e.getMessage());
e.printStackTrace();
}
}
}
My .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>atozknowledge.com demo Regjsp</title>
</head>
<body>
<%# page import ="java.sql.*" %>
<%# page import ="javax.sql.*" %>
<%
String user=request.getParameter("userid");
session.putValue("userid",user);
String pwd=request.getParameter("pwd");
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
String email=request.getParameter("email");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = Connect_db.getDataSource("sjsu").getConnection();
Statement st= con.createStatement();
ResultSet rs;
int i=st.executeUpdate("insert into users values ('"+user+"','"+pwd+"','"+fname+"', '"+lname+"','"+email+"')");
out.println("Registered");
%>
Home
</body>
</html>
My html:
<!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>atozknowledge.com demo Registration</title>
</head>
<body>
<form action="reg.jsp" method="post">
User name :<input type="text" name="userid" /><br/><br/>
password :<input type="password" name="pwd" /><br/><br/>
First name :<input type="text" name="fname" /><br/><br/>
Last name :<input type="text" name="lname" /><br/><br/>
Email :<input type="text" name="email" /><br/><br/>
<br/><br/>
<input type="submit" />
</form>
</body>
</html>
The error
It used to be able to put the userid, pwd, ... etc in my database and now it can't.
As the error states, it cannot find the class Connect_db. You need to add an explicit import for Connect_db to your JSP, that is add:
<%# page import ="package.of.Connect_db" %>
Querying directly from JSP is a poor choice, your should separate getting the data from displaying the data.
Tomcat also provides support for creating and registering data sources, use that instead of rolling your own. Especially, as MysqlDataSource doesn't provide connection pooling.
And finally, concatenating values into your query string is unsafe, especially with user provided input, as it leaves you open to SQL injection. Instead you should use a prepared statement with parameters. Please take a look at Using Prepared Statements in the JDBC tutorial.
I recommend you instead of giving the my.jsp inn the from action it is better to use a servlet. Maybe it can solve your. Create a new servlet and write your code inside of post method.

servlet error on console doesn't redirect to error page

I have a problem when I try to enter duplicate entries as you can see in the servlet below. The problem is that tomcat shows the duplicate error but the servlet doesn't redirect to the desired error page (dup_organism.jsp). However I have no problem when I enter a new record and redirect to another page, while the code is pretty much the same.
I have this servlet:
package package_ergasia;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddOrganism extends HttpServlet
{
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
Connection connection= null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "ergasia";
String user = "root";
String password = "password";
String org_id = request.getParameter("id");
String oname = request.getParameter("oname");
try {
connection = DriverManager.getConnection(url + dbName, user, password);
Statement statement = connection.createStatement() ;
ResultSet resultset = statement.executeQuery("SELECT * FROM organism") ;
while(resultset.next()){
if(resultset.getString("org_id").equalsIgnoreCase(org_id)){
String contextPath= "http://localhost:8084/secured";
response.sendRedirect(response.encodeRedirectURL(contextPath + "/dup_organism.jsp"));
}
else{
PreparedStatement ps = connection.prepareStatement("INSERT INTO organism (org_id,organismName) VALUES (?,?)");
ps.setString(1, org_id);
ps.setString(2, oname);
ps.executeUpdate();
String contextPath= "http://localhost:8084/secured";
response.sendRedirect(response.encodeRedirectURL(contextPath + "/all_organisms.jsp"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public String getServletInfo() {
return "info";
}
}
this is the error page dup_organism.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="../CSS/mystyle.css">
<title>Duplicate entry</title>
</head>
<body>
<h1>Error</h1>
<% String org_id = request.getParameter("org_id"); %>
<h2><div align="center">
<br><br><br>
Duplicate data <br> #Organism Id:
<% out.println(org_id); %>
</div></h2>
</body>
</html>
browser shows nothing (still on servlet page) and tomcat shows the following error: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry '02' for key 'PRIMARY'
The problem why your getting null is that your using response.sendRedirect which creates a new instance of request and response object. you can do any one of the following:
Replace it with request.getRequestDispatcher(url);
Set the Org_id in the session object and retrieve it in the jsp.

Store filename of uploaded file in database java

I am using the program from the site http://codejava.net/coding/upload-files-to-database-servlet-jsp-mysql that allows the user to upload files in the database. So far I have no troubles in inserting the data into the database.
I want to add a field named filename in the database. But I am unable to get the file name of the uploaded file. Is there a method for getting it? Or can I use BufferedReader to read the file?
FileUploadDB.java
package com.process.web.controller;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#WebServlet("/fileuploaddb.html")
#MultipartConfig(maxFileSize = 16177215)
public class FileUploadDB extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
private String dbURL = "jdbc:jtds:sqlserver://localhost:1433;DatabaseName=ATS;SelectMethod=cursor;";
private String dbUser = "sa";
private String dbPass = "benilde";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// gets values of text fields
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("photo");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
Connection conn = null; // connection to the database
String message = null; // message will be sent back to client
try {
// connects to the database
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//DriverManager.getConnection(dbURL);
//com.microsoft.sqlserver.jdbc.Driver
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
if(conn!=null) {
System.out.println("Connection Successful!");
} else {
System.out.println("Error in Connection");
}
// constructs SQL statement
String sql = "INSERT INTO contact (firstname, lastname, photo) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, firstName);
statement.setString(2, lastName);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBinaryStream(3, filePart.getInputStream(), (int)(filePart.getSize()));
}
// sends the statement to the database server
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
This is the upload.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload to Database Demo</title>
</head>
<body>
<center>
<h1>File Upload to Database Demo</h1>
<form method="post" action="fileuploaddb.html" enctype="multipart/form-data">
<table border="0">
<tr>
<td>First Name: </td>
<td><input type="text" name="firstName" size="50"/></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type="text" name="lastName" size="50"/></td>
</tr>
<tr>
<td>Portrait Photo: </td>
<td><input type="file" name="photo" size="50"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
**This is the Message.jsp**
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Message</title>
</head>
<body>
<center>
<h3><%=request.getAttribute("Message")%></h3>
</center>
</body>
</html>
**On this part, the System.out.println(filePart.getName()); does not print the file
name of the selected file to be uploaded, but it prints out the word "photo".
Which is from
Part filePart = request.getPart("photo");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
Use the following method
private String getFileName(Part p){
String header=p.getHeader("content-disposition");
String filename = header.substring(header.indexOf("filename=\"")).split("\"")[1]; //getting filename
return filename;
}
The snippet is taken from my blog here
I have no troubles in inserting the data into the database but I am unable to get the file name of the uploaded file. Is there a method for getting it?
Since Servlet API 3.1, the Part interface provides the getSubmittedFileName() method which does what you need.
Gets the file name specified by the client
This class represents a part or form item that was received within a multipart/form-data POST request.
Alternatively you can use Commons Fileupload library provided by Apache that makes it easy to add robust, high-performance, file upload capability to your servlets and web applications.
Sample code:
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
String name = new File(item.getName()).getName();
}
}
Find complete code here and here

In struts 1.3 how to retrieve data from database and display it using DAO

*M new to struts. I am making simple login page that display username and password by retrieving it from database. I m using DAO.
I have LoginDAO.java, LoginAction.java and Displaydata.jsp pages. *
LoginDAO.java
public boolean login(String user,String pass) throws SQLException
{
Connection con = getConnection();
Statement st;
try {
st = con.createStatement();
st.executeQuery("select * from login where Username='" + user + "' and Password='" + pass + "'");
return true;
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return false;
}
LoginAction.java
public class LoginAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm rf= (DynaValidatorForm) form;
String username = rf.get("username").toString();
String password = rf.get("password").toString();
HttpSession session=request.getSession();
session.setAttribute("user", username);
Login dao= new Login();
if(dao.login(username,password))
{
System.out.println("GOT");
return mapping.findForward("success");}
else
{System.out.println("NOT");
return mapping.findForward("failure");
}
}
}
and also what do i write in Dislpaydata.jsp to display username and password in it dont want any java code in it.
Thankyou
Right. Some time ago I built an application with Struts 1.x and MySql with login.
LoginAction
public ActionForward login( ... ) throws Exception {
String forward;
final String mail = PropertyUtils.getProperty(form, "mail");
final String password = PropertyUtils.getProperty(form, "password");
if (LoginService.getInstance().validate(mail, password)) {
// Do something e.g. put name of user in session
forward = SUCCESS;
} else {
forward = ERROR;
}
return mapping.findForward(forward);
}
LoginService
public boolean validate(final String mail, final String password)
throws ServiceException {
try {
final boolean valid;
// Validate null and empty
// Validate with DB
final UserDAO dao = new UserDAO();
final User user = dao.findByPk(mail);
if (user == null) {
valid = false;
} else {
if (password.equals(user.getPassword())) {
valid = true;
} else {
valid = false;
}
}
return valid;
} catch (DAOException e) {
throw new ServiceException("Error validating user and password.", e);
}
}
UserDAO
private static final String FIND_BY_PK_SQL
= "SELECT mail, name, password, admin FROM user WHERE mail = ?";
public User findByPk(final String mail) throws DAOException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = getConnection();
ps = conn.prepareStatement(FIND_BY_PK_SQL);
ps.setString(1, mail); // PK, NOT NULL
rs = ps.executeQuery();
if (rs.next()) {
return fill(rs);
}
return null;
} catch (final SQLException e) {
throw new DAOException(e);
} finally {
// Close DB resources
}
}
private User fill(final ResultSet rs) throws SQLException {
final User user = new User();
user.setMail(rs.getString("mail"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setAdmin(rs.getBoolean("admin"));
return user;
}
In my case I have a table user with mail as a primary key. There are various forms.
More examples:
Building a Login Application
Struts Login Application Using Action Form Tutorial | DZone
Creating a Email Login Web Application with Struts
e.g. For show the name of variable user in session scope from the database:
LoginAction
if (LoginService.getInstance().validate(mail, password)) {
final HttpSession session = request.getSession();
final User user = UserService.getInstance().getUser(mail);
session.setAttribute("user", user);
forward = SUCCESS;
}
home.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
Welcome,
<bean:write scope="session" name="user" property="name" filter="false" />
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Login Page</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript"
src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>
</head>
<body bgcolor="#2EFEF7">
<form action="action" method="post" id="formDemo" name="MyForm">
<div id="header">
<h2 style="color: red;">Training</h2>
</div>
<hr>
<h3>Login</h3>
<div id="center" style="padding-top: 50px; padding-bottom: 220px;">
<table align="center">
<tr>
<th colspan="2"><h1 style="color: BLUE;">LOGIN</h1></th>
</tr>
<tr>
<th colspan="2"><h5 id="error" style="color: red;"></h5></th>
</tr>
<tr>
<td>UserID:</td>
<td><input type="text" size="40" name="UserId" maxlength="8"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" size="40" name="Password" maxlength="8"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
value="Login"> <input type="button" id="reset"
value="Clear"></td>
</tr>
</table>
</div>
<hr>
<div id="footer">
<label>Copy right# 2000-2008 FUJINET, All Rights Reserved.</label>
</div>
</form>
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate() {
if (document.MyForm.UserId.value === ""
|| document.MyForm.UserId.value === null) {
document.getElementById("error").innerHTML = "Please insert userId";
return false;
}
if (document.MyForm.Password.value === ""
|| document.MyForm.Password.value === null) {
document.getElementById("error").innerHTML = "Please insert password";
return false;
}
return (true);
}
$("#reset").click(function(event) {
document.MyForm.UserId.value = "";
document.MyForm.Password.value = "";
document.getElementById("error").innerHTML = "";
});
$("#formDemo").submit(function(event){
return validate();
});
</script>
</body>
</html>

trying to get a query to use the LIKE function with a variable in JSP

I have a query that is being used to pull usernames and info about the user. In Access I had the LIKE function so that the user didn't have to type in a specific name. I am now transferring it over to JSP. Here is the line in the query that I am having troubles with in JSP:
WHERE ObjectName Like '" + "%"+ VariableName + "%" +"';
The query runs fine but does not show any information even if I put in the entire name. If I change it to:
WHERE ObjectName = '" + VariableName +"';
it works, but I would like to give the user a chance to have to ability to put in partial names in case they do not know how to spell the name or typ eit incorrectly. Any help would be apprecited.
Thanks
The line you've shown is a bit odd, but syntactically valid. So the problem lies somewhere else. What does variableName actually contain?
That said, you shouldn't be writing raw Java code in JSP files. Do that in a Java class. You can use a Servlet class to preprocess or postprocess requests. Also grab PreparedStatement to avoid SQL injections. Here's a kickoff example:
public List<User> search(String username) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
List<User> users = new ArrayList<User>();
try {
connection = database.getConnection();
statement = connection.prepareStatement("SELECT id, username, age, email FROM user WHERE username LIKE ?");
statement.setString(1, "%" + username + "%");
resultSet = statement.executeQuery();
while (resultSet.next()) {
users.add(mapUser(resultSet));
}
} finally {
close(connection, statement, resultSet);
}
return users;
}
Avoid writing SQL queries in JSP
"SELECT * FROM something WHERE ObectName LIKE '%" + VariableName + "%'" should work
this is an answer for starting users
i am created a data base in a name ASHRAF, then i create a table in name CASH. the code is given below
CREATE TABLE CASH(NO INT NOT NULL PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(50) NOT NULL,ADDRESS VARCHAR(100),PET_NAME VARCHAR(50),PLACE VARCHAR(50),TYPE VARCHAR(20),TYPE_OF_PAY VARCHAR(20),AMOUNT INT(6) NOT NULL);
here the NO is auto increment ant it is primary key anyway you can search the contents from the table using jsp code that i given below
am search here using both NAME ADDRESS you can pass the parameters using a html page and a servlet
The html page(show.html) that i created is given below
<!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>show.html</title>
</head>
<body>
<h1><b><font color=020202>SHOW</font></b></h1><br><br>
<form name="f6" action="getshow" method="POST" onsubmit="return check(this)">
<table border="0">
<tr>
<td>Name :</td><td><input type="text" name="name"></td>
</tr>
<tr>
<td>House Name :</td><td><input type="text" name="address"></td>
</tr>
<tr>
<td><br><input type="SUBMIT" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
The servlet is(getshow.java) given below
package Servlets;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class getdata
*/
public class getshow extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public getshow() {
super();
// 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
try{
String url=null;
String s1=request.getParameter("name");
String s2=request.getParameter("address");
request.setAttribute("name",s1);
request.setAttribute("address",s2);
url="show.jsp";
RequestDispatcher view=request.getRequestDispatcher(url);
view.forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The jsp file is(show.jsp) given below
<%# 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>show.jsp</title>
</head>
<body>
<%String aid=(String)request.getAttribute("name"); %>
<%String sid=(String)request.getAttribute("address"); %>
<%
Connection con=null;
ResultSet rs=null;
String records=null;
StringBuffer appender=new StringBuffer();
java.sql.PreparedStatement st=null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection("jdbc:mysql://localhost/ASHRAF?user=root&password=password");
st=con.prepareStatement("select *from CASH where NAME like '" + aid + "%" +"' and ADDRESS like '" + sid + "%" +"'");
rs=st.executeQuery();
%>
<center><TABLE cellpadding="15" border="2">
<TR>
<TH>NO</TH>
<TH>NAME</TH>
<TH>HOUSE NAME</TH>
<TH>PET NAME</TH>
<TH>PLACE</TH>
<TH>TYPE OF OCCATION</TH>
<TH>TYPE OF PAY</TH>
<TH>AMOUNT</TH>
</TR>
<%
while (rs.next()) {
%>
<TR>
<TD><%=rs.getString(1)%></TD>
<TD><%=rs.getString(2)%></TD>
<TD><%=rs.getString(3)%></TD>
<TD><%=rs.getString(4)%></TD>
<TD><%=rs.getString(5)%></TD>
<TD><%=rs.getString(6)%></TD>
<TD><%=rs.getString(7)%></TD>
<TD><%=rs.getString(8)%></TD>
</TR>
<% } %>
</TABLE>
</center>
</div>
<%
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} %>
</body>
</html>
now you can search either with the name nor with the address or with both.

Categories

Resources