I have a image in my sql and I want to retrieve it in web page
so i have developed a servlet. now when I hit the submit button then it calls to the servlet but image is not displayed but in the browser if if I am writing localhost:8080/y/testimageServlet then the image is displayed.
imagetestServlet.java
import java.sql.*;
import DB.DataBaseConnection;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class imagetestServlet
*/
#WebServlet("/imagetestServlet")
public class imagetestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public imagetestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException {
Blob image = null;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
DataBaseConnection db= new DataBaseConnection();
ServletOutputStream out = response.getOutputStream();
try {
Class.forName("com.mysql.jdbc.Driver");
con=db.connet();
stmt = con.createStatement();
rs = stmt.executeQuery("select img from one where id = '4'");
if (rs.next()) {
image = rs.getBlob(1);
} else {
response.setContentType("text/html");
out.println("<font color='red'>image not found for given id</font>");
return;
}
response.setContentType("image/gif");
InputStream in = image.getBinaryStream();
int length = (int) image.length();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.flush();
} catch (Exception e) {
response.setContentType("text/html");
out.println("<html><head><title>Unable To Display image</title></head>");
out.println("<body><h4><font color='red'>Image Display Error=" + e.getMessage() +
"</font></h4></body></html>");
return;
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
login
<form id="f1" name="f1" action="imagetest" method="post" onsubmit="return ccheck()">
<img src="header.png"><br><br><br><br><br>
<table >
<tr>
<td>
<table class="table">
<tr>
<td>
<table class="table">
<tr>
<td>
<div class="content"><div class="signin-header"><h3>Welcome to DiaEmr</h3></div></div>
</td>
</tr>
<tr>
<td>
<div class="content">
<div class="signin-box">
<p class="one">
Welcome to all at the <b>"Workshop on Ileal Interposition".</b><br>
<b>Brazil</b> to inaugurate & launch this very important Data Registry<br>
Key features of the solution-<br>
</div>
</div>
</td>
</tr>
</table>
</td>
<td>image</td>
<td>
<table class="table" >
<tr>
<td>
<div class="content">
<div class="signin-header">
<h3>Portal Login</h3>
</div>
</div>
</td>
</tr>
<tr>
<td>
<div class="content">
<div align="center" class="signin-box">
<table class="table">
<tr>
<td><b>User ID</b></td>
<td><input name="uid" type="text" /></td>
</tr>
<tr >
<td><b>Password</b></td>
<td><input name="cpass" type="password" /></td>
</tr>
<tr >
<td><input type="submit"
class="button button-submit" value="Submit" /></td>
<td><input type="reset" class="button button-submit"
value="Reset" /></td>
<tr>New UserRegister</tr><br>
</tr>
</table>
</div>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
<div class="footer-bar">
<img align="left" src="footer.png">
</div>
</form>
your form sends a post request,
<form id="f1" name="f1" action="imagetest" method="post" onsubmit="return ccheck()">
but you only define a doGet method in your servlet. This is resulting in your page working if you navigate in a browser (GET) but not when submitting your form (POST).
You will either need to change your form to use get or implement your code in the doPost method
Related
I have embedded department.jsp in create.jsp. My department.jsp has a table in which i submit data, the action is on a servlet but on submitting it is giving a 404 error for servlet.
create.jsp in body-
<header>
<img style="text-align:left" src="images.png" width="200" height="100" alt="NSIC-logo1"/>
<h1>File Tracking System</h1>
<form style="float:right;" action=" LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
<br>
</header>
Create
<iframe style="height:530px;width:1340px " src="department.jsp" name="frame2">
<p>Your browser does not support iframes.</p>
</iframe>
department.jsp in body-
<form action="DepartmentServlet" method="post">
<center>
<table id="depart">
<thead>
<tr>
<th colspan="2">Create Department</th>
</tr>
</thead>
<tbody>
<tr>
<td>Company Name :</td>
<td><input type="text" name="company" value="" size="50" /></td>
</tr>
<tr>
<td>Department Name</td>
<td><input type="text" name="department" value="" size="50" /> </td>
</tr>
<tr>
<td>Head Office :</td>
<td><input type="text" name="place" value="" size="50" /></td>
</tr>
</tbody>
</table>
</center>
<input type="reset" value="Clear" name="Clear" />
<input type="submit" value="Submit" name="Submit" />
</form>
DepartmentServlet.java
public class DepartmentServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//request.getRequestDispatcher("link.html").include(request, response);
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("JSESSIONID")){
System.out.println("JSESSIONID="+cookie.getValue());
break;
}
}
}
HttpSession session = request.getSession(false);
System.out.println("admin="+session.getAttribute("admin"));
if(session!=null && session.getAttribute("admin") != null){
String admin=(String)session.getAttribute("admin");
boolean status=false;
try{
String department=request.getParameter("department");
String company=request.getParameter("company");
String place=request.getParameter("place");
boolean checkd=dcheck.value(department);
boolean checkc=checkchar.value(company);
boolean checkp=checkchar.value(place);
if(checkd==true&&checkc==true&&checkp==true) {
Connection con=ConnectionProvider.getCon();
String sql="insert into department(departmentname,company,place) values (?,?,?)";
PreparedStatement pstmt =con.prepareStatement(sql);
pstmt.setString(1,department);
pstmt.setString(2,company);
pstmt.setString(3,place);
int rs=pstmt.executeUpdate();
if(rs>0){status=true;}
if(status){
PrintWriter out= response.getWriter();
out.print("values have been inserted,"+admin);
response.sendRedirect("insert.jsp");
}
else
{
PrintWriter out= response.getWriter();
out.print("failed to insert");
response.sendRedirect("notinsert.jsp");
}
}
else{response.sendRedirect("entry.jsp");}
}catch(SQLException e){}
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
}
I am having an issue with retriving "grouped" data from HTML form to servlet. I will describve the scenario below.
In companies, they record the salary of the employees once a month.When they record it, they do not do it by visiting each an every employees personal "profile" (or whatever according to the system). Instead what they do is apply the salaries of all of them in one page.
To do the above thing they prefer excel like tabular sheets.
Now, I have a html form, where the form content is a table. One row is dedicated to a one employee.
Below is my form.
<%--
Document : index2
Created on : Mar 5, 2015, 10:04:45 AM
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form method="post" action="EmployeeSampleServlet">
<table border="1" style="width:100%">
<thead>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</thead>
<tbody name="tableBody" value="1">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
<tbody name="tableBody" value="2">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
<tbody name="tableBody" value="3">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
<tbody name="tableBody" value="4">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
<tbody name="tableBody" value="5">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
</table>
<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
As you can see, I have wrapped every row with a <tbody>. The value attribute of the <tbody> will contain the employee id.
Once the form is submitted, the below servlet will capture it.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EmployeeSampleServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String[]empId = request.getParameterValues("tableBody");
for(int i=0;i<empId.length;i++)
{
out.println(empId[i]);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
What I was trying is get the value attribute of <tbody> (so I can identify the id of the employee) and get the data inside that <tbody>. However this didn't work, because I ended up with NullpointerException because it failed to read the <tbody> value.
So, how can I pass the data from table to servlet where it can clearly understand that one row is representing data belong to a one employee? If this is not the way to do it, I am also open for other methods.
That is obviously not going to work as only the input field values are submitted to the server.
You will need to discriminate the names of each input field in some way as currently you cannot match these to individual employees:
I assume you generate the table from some kind of list of employees so you could do this something like below:
<tr>
<td><input type="text" name="nameTxt_${employee.employeeId}" style="width:100%"/></td>
<td><input type="text" name="positionTxt_${employee.employeeId}" style="width:100%"/></td>
<td><input type="text" name="salaryTxt_${employee.employeeId}" style="width:100%"/></td>
</tr>
Now instead of receiving a bunch of random parameters 'nameTxt' etc., you reeive 'nameText_21', 'salaryText_21' etc. and have a means to identify the input with an employee. How you do this will depend on whether you have the list of Employees available in the Servlet on form submission.
e.g.
//employees = load the same list originally loaded for edit
for(Employee e : employees){
e.setSalary(Double.parseDouble(request.getParameter("salaryTxt_" + e.getid())));
}
Otherwise you will need to iterate the parameters for some field and proceed that way.
for(String s: request.getParameterNames()){
if(s.startsWith("nameTxt")){
//extract suffix
//load the employee with corresponding ID
//get the other params with same id
}
}
Look the below HTML, this will get all the table row-wise value and convert that as a json array. Now you can pass this array to servlet via ajax.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sample</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<table border="1" id="mytable" border="1" >
<thead>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</thead>
<tbody>
<tr>
<td><input type="text" name="nameTxt" value="12" /></td>
<td><input type="text" name="positionTxt" value="13" /></td>
<td><input type="text" name="salaryTxt" value="14" /></td>
</tr>
<tr>
<td><input type="text" name="nameTxt" value="21" /></td>
<td><input type="text" name="positionTxt" value="22" /></td>
<td><input type="text" name="salaryTxt" value="23" /></td>
</tr>
<tr>
<td><input type="text" name="nameTxt" value="31" /></td>
<td><input type="text" name="positionTxt" value="32" /></td>
<td><input type="text" name="salaryTxt" value="33" /></td>
</tr>
<tr>
<td><input type="text" name="nameTxt" value="41" /></td>
<td><input type="text" name="positionTxt" value="42" /></td>
<td><input type="text" name="salaryTxt" value="43" /></td>
</tr>
<tr>
<td><input type="text" name="nameTxt" value="51" /></td>
<td><input type="text" name="positionTxt" value="52" /></td>
<td><input type="text" name="salaryTxt" value="53" /></td>
</tr>
</tbody>
</table>
<br/>
<input type="button" value="Submit" onclick="convertValuesToJson();">
</body>
</html>
And you script looks like,
<script>
function convertValuesToJson(){
var myStringArray = [];
// Iterate each row
$('#mytable tbody tr').each(function() {
var myObject = new Object();
myObject.name = $(this).find("input[name='nameTxt']").val();
myObject.position = $(this).find("input[name='positionTxt']").val();
myObject.salary = $(this).find("input[name='salaryTxt']").val();
myStringArray.push(JSON.stringify(myObject));
});
// function for ajax goes here...
jQuery.ajax({
url: "ServletURL",
type : 'POST',
dataType: "json",
data : {"myData" : myStringArray},
error : function(jqXHR, textStatus, errorThrown) {
alert("error occurred");
}
});
}
</script>
See my updated Demo
I had tried from servlet set value by setattribute and it have to iterate in jsp by getattribute by setter and getter method without EL and JSTl but am getting this error .kindly help on this i searched in google but i cant found.
java.lang.NullPointerException
org.apache.jsp.Home_jsp._jspService(Home_jsp.java:138)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
here serlvet code
package servlet2;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.TreeSet;
import javafx.css.PseudoClass;
import javax.servlet.RequestDispatcher;
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 servlet.Dao;
import jdbc.jdbcconnection;
/**
* Servlet implementation class Homepage
*/
//#WebServlet(asyncSupported = true, urlPatterns = { "/Homepage" })
public class Homepage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Homepage() {
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
System.out.println("inside==========>");
String name=request.getParameter("name");
String password=request.getParameter("password");
String phone=request.getParameter("Phone");
String Deptmart=request.getParameter("Dep");
String gender=request.getParameter("gender");
String country=request.getParameter("country");
Dao d=new Dao();
try
{
jdbcconnection jc=new jdbcconnection();
Connection con=jc.getconnection();
String sql="insert into homepage(name,password,phone,Dept,gender,Country) values(?,?,?,?,?,?)";
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, password);
ps.setString(3, phone);
ps.setString(4, Deptmart);
ps.setString(5, gender);
ps.setString(6, country);
System.out.println("ps=========>"+ps);
ps.execute();
con.commit();
String select="select * from homepage";
PreparedStatement ps1=con.prepareStatement(select);
ResultSet rs=ps.executeQuery();
ArrayList t=new ArrayList();
while(rs.next())
{
d.setid(rs.getInt(1));
d.setName(rs.getString(2));
d.setPassword(rs.getString(3));
d.setPhone(rs.getInt(4));
d.setDeptmart(rs.getString(5));
d.setGender(rs.getString(6));
d.setCountry(rs.getString(7));
t.add(d);
}
request.setAttribute("users",t);
RequestDispatcher rs1=request.getRequestDispatcher("/Home.jsp");
rs1.forward(request, response);
}
catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Jsp page:
<%#page import="servlet.Dao,java.util.*" %>
<!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="Homepage" method="get">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="password" id="password"></td>
<tr>
<td>Phone:</td>
<td><input type="text" name="Phone" id="Phone">
</tr>
</td>
<tr>
<td>Department:</td>
<td><select id="Dep" name="Dep">
<option value="it">IT</option>
<option value="finace">Finace</option>
<option value="market">Marketing</option>
</select></td>
</tr>
<tr>
<td>Gender:</td>
<td><input type="radio" name="gender" id="gender" Value="Male">Male
<input type="radio" name="gender" id="gender" Value="Female">Female</td>
</tr>
<tr>
<td>Country:</td>
<td><input type="checkbox" name="country" id="country"
Value="India">India <input type="checkbox" name="country"
id="country" Value="Other">Other</td>
</tr>
<br>
<tr>
<td><input type="submit" name="Add" Value="ADD" ></td>
<td><input type="button" name="Clear" Value="CLEAR"></td>
</tr>
</table>
</form>
<table border="1">
<tr><td>Id</td><td>name</td>
<td>Password</td>
<td>Phone</td>
<td>Deptmart</td>
<td>Gender</td>
<td>country</td>
<td>Edit</td>
<td>Delete</td>
</tr>
<%
try
{
List<Dao> al1 = (List) request.getAttribute("users");
// System.out.println(al1); // prints null
for(Dao user : al1) {
%>
<tr>
<td><%=user.getid() %></td>
<td><%=user.getName() %></td>
<td><%=user.getPassword() %></td>
<td><%=user.getPhone() %></td>
<td><%=user.getDeptmart() %></td>
<td><%=user.getGender() %></td>
<td><%=user.getCountry() %></td>
<td></td>
<td></td>
</tr>
<%} }
catch(Exception e)
{
e.printStackTrace();
}
%>
</table>
</body>
</html>
web.xml
<servlet>
<servlet-name>Homepage</servlet-name>
<servlet-class>servlet2.Homepage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Homepage</servlet-name>
<url-pattern>/Homepage</url-pattern>
</servlet-mapping>
I'm new to mysql and teaching myself the ropes. I've come across a problem and hoping for some advice.
I created a form in a jsp page to insert data to a mysql database. All data is properly inserted, and when I do select* all data is properly displayed in a table I created. My problem is with my update page.
When I call data from the database back into a form on my editdata.jsp page, only everything before a space is returned. For example, I put the name 'Tom Jones' into a database, but when I go to retrieve it from the name field, only 'Tom' is returned; 'Jones' is not, but is still there in the database.
Here's my editdata.jsp code:
<%#page import="java.sql.ResultSet"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action ="UpdateData" method ="post">
<table border ="1" width="80%">
<%ResultSet res = (ResultSet) request.getAttribute("EditData");%>
<%if(res.next()){
%>
<tr>
<td>ID</td>
<td><input type="text" name="id" value=<%=res.getString("id")%>>
</td>
</tr>
<tr>
<td>Container Number </td>
<td><input type="text" name="id" value=
<%=res.getString("containerNumber")%> ></td>
</tr>
<tr>
<td>Size </td>
<td><input type="text" name="id" value=<%=res.getString("size")%>>
</td>
</tr>
<tr>
<td>Vessel </td>
<td><input type="text" name="id" value=<%=res.getString("vessel")%>>
</td>
</tr>
<tr>
<td>Full Out Date </td>
<td><input type="text" name="id" value=
<%=res.getString("fullOut")%>> </td>
</tr
<tr>
<td>Empty In Date </td>
<td><input type="text" name="id" value=<%=res.getString("emptyIn")%>
></td>
</tr>
<tr>
<td>Empty Out Date </td>
<td><input type="text" name="id" value=
<%=res.getString("emptyOut")%>> </td>
</tr>
<tr>
<td>Full In Date </td>
<td><input type="text" name="id" value=<%=res.getString("fullIn")%>>
</td>
</tr>
<tr>
<td>Comments </td>
<td><input type="text" name="id" value=
<%=res.getString("comments")%>> </td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Update" name="update"> </td>
</tr>
<%}%>
</table>
</form>
</body>
</html>
And my EditRecord servlet:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EditRecord extends HttpServlet {
Connection conn;
ResultSet res;
Statement stmt;
String id, query;
DatabaseConnection dbconn;
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
id = request.getParameter("id");
dbconn = new DatabaseConnection();
conn = dbconn.setConnection();
stmt = conn.createStatement();
query = "select * from inventory where id = "+id;
res = dbconn.getResult(query, conn);
}catch(Exception e){
}
finally {
request.setAttribute("EditData", res);
RequestDispatcher rd = request.getRequestDispatcher("editdata.jsp");
rd.forward(request, response);
out.close();
}
}
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Again, the long and short of my problem is that full strings of data are not returned after spaces. So 'TOM JONES' only returns 'TOM' to the form above for editing. How do I get the full string of data to be returned. I don't know if it matters, but I used VARCHAR for all my record info.
Thanks for any and all help.
Attributes inside HTML tags are separated by spaces. That's why you're supposed to use quotes around the attribute values.
BAD:
<input type="text" name="id" value=<%=res.getString("comments")%>>
GOOD:
<input type="text" name="comments" value="<%=res.getString("comments")%>" />
Jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" language="Javascript" >
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add Course_Subject</title>
<style type="text/css">
<!--
body {
background-color: #FFCCFF;
}
.style1 {
color: #0066FF;
font-weight: bold;
}
.style2 {font-size: 18px}
.style17 { font-family: "Monotype Corsiva";
font-size: 24px;
font-weight: bold;
font-style: italic;
color: #6633CC;
}
.style19 {color: #000099}
.style21 {color: #000099; font-weight: bold; }
-->
</style>
</head>
<body>
<jsp:include page="Log_Admin.jsp"/><br/>
<form action="" method="post" name="form1" id="form1">
<table width="46%" height="43" border="3" bgcolor="##CCCC99" align="center">
<tr>
<td width="85%" align="center" bgcolor="#FFFF99"><label><span class="style17">Course and Subject Information</span></label></td>
</tr>
<tr><td>
<table width="666" height="207" border="0" align="center" bordercolor="#F0F0F0" bgcolor="#CCCC99" >
<tr>
<td width="186" height="46" align="left"><div align="left"><span class="style19">
<label><strong>Coourse ID</strong></label>
</span></div></td>
<td><label>
<select name="cid" size="1" id="cid" align="left" onclick="loaadCourseName()">
<option selected="selected">None</option>
<option>C001</option>
<option>C002</option>
<option>C003</option>
<option>C004</option>
<option>C005</option>
<option>C006</option>
<option>C007</option>
<option>C008</option>
<option>C009</option>
<option>C010</option>
</select>
</label></td>
<td width="186" height="46" align="left"><div align="left"><span class="style19">
<label><strong>Coourse Name</strong></label>
</span></div></td>
<td width="310" align="left"><input name="cname" type="text" id="cname" size="25" maxlength="50" /></td>
</tr>
<tr>
<td width="186" height="46" align="left"><div align="left"><span class="style19">
<label><strong>Subject ID</strong></label>
</span></div></td>
<td><label>
<select name="sid" size="1" id="sid" align="left">
<option selected="selected">None</option>
<option>S01</option>
<option>S02</option>
<option>S03</option>
<option>S04</option>
<option>S05</option>
<option>S06</option>
<option>S07</option>
<option>S08</option>
<option>S09</option>
<option>S10</option>
</select>
</label></td>
<td width="186" height="46" align="left"><div align="left"><span class="style19">
<label><strong>Subject Name</strong></label>
</span></div></td>
<td width="310" align="left"><input name="sname" type="text" id="sname" size="25" maxlength="50" /></td>
</tr>
<tr>
<td> </td>
<td> <input name="save" type="submit" id="save" value="Save" onclick="validate(this.form)"/>
<input name="reset" type="reset" id="reset" value="Reset" /></td>
</tr>
</table>
</td></tr>
</table>
</form>
</body>
</html>
Servlet
package DBCon;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
/**
*
* #author Nayan
*/
public class searchCourseName extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String cname=null,courseid;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/online_exam?"+"user=root&password=pass");
Statement stmt=con.createStatement();
courseid=request.getParameter("cid");
ResultSet rs=stmt.executeQuery("select course_name from course where course_id='"+courseid+"'");
while(rs.next())
{
cname=rs.getNString("course_name");
//String s=rs.getString(1);
}
request.getSession().setAttribute("courseName",cname);
//RequestDispatcher requestDispatcher=getServletContext().getRequestDispatcher("http://localhost:8080/ONLINEEXAMINATION/removeCourse2.jsp");
//requestDispatcher.forward(request,response);
}
catch(Exception e) {
out.println("<h1>"+e.getStackTrace()+"</h1>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* #param request servlet request
* #param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
// </editor-fold>
}
Now when I select an item in the dropdown cid I want to display the corresponding courname in the cname textfield. How can I achieve this?
Remove
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
They are superfluous and dangerous when using JSP. JSP already sets its own content type. When getting the response writer in the servlet, you'll only risk seeing IllegalStateException errors in server logs when forwarding to JSP.
Replace
request.getSession().setAttribute("courseName",cname);
//RequestDispatcher requestDispatcher=getServletContext().getRequestDispatcher("http://localhost:8080/ONLINEEXAMINATION/removeCourse2.jsp");
//requestDispatcher.forward(request,response);
by
request.setAttribute("courseName",cname);
request.getRequestDispatcher("/removeCourse2.jsp").forward(request, response);
This sets the variable in request scope so that it's available by ${courseName} and forwards the request back to same JSP where the form is in. The session scope will also work, but you don't want that here. It'll affect other requests (the visitor may for instance have opened the same form in multiple browser tabs).
Update
<input name="cname" type="text" id="cname" size="25" maxlength="50" />
with
<input name="cname" value="${courseName}" type="text" id="cname" size="25" maxlength="50" />
The ${courseName} will print the value of the request attribute. Doing so in the value attribute of the input element will make it to show up in the browser. If this is an user controlled value, you may want to use JSTL fn:escapeXml() to avoid XSS attacks.
See also:
Our Servlets wiki page - Contains a Hello World