I have a JSP page in which I have two tags. In first I am trying get input such as Car Maker name such as Tata, Hyundai, Toyota, Audi etc. When user selects any option in first , it should display car models from that maker such as Innova,Land Cruiser etc. So when user selects any option in first tag, I am calling a servlet which gets all the models from database in a list and setting the list as attribute of session and forwarding the request back to JSP. But in jsp when I try to fetch the list it is giving NULL POINTER EXCEPTION. How to solve it?
The code is as below:
DbReviewCar.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn= null;
PreparedStatement pstmt= null;
ResultSet rs;
String sql= null;
String maker= request.getParameter("make");
List modellist= new ArrayList();
/*if(maker==null)
{
modellist.add("ferrari");
modellist.add("hummer");
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
else
{*/
try {
Class.forName("com.mysql.jdbc.Driver");
conn= DriverManager.getConnection("jdbc:mysql://localhost/cardetails", "root", "Welcome123");
sql= "select model from cars where make=?;";
pstmt= conn.prepareStatement(sql);
pstmt.setString(1, maker);
rs= pstmt.executeQuery();
while(rs.next())
{
String mod= rs.getString(1);
modellist.add(mod);
System.out.println(mod+">>>>>>>>>>>>>>>>>>.");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
CarReview.jsp
Here is my JSP file
<form action="DbReviewCar" method="get" name="myform">
<table>
<tr>
<td>
<tr>
<td>Make:</td>
<td><select name="make" onchange="this.form.submit()"><option>select</option>
<option>Maruti</option>
<option>Ford</option>
<option>Honda</option>
<option>Skoda</option>
<option>Tata</option>
<option>Audi</option>
<option>Toyota</option></select><br></br></td>
</tr>
<%
List list = new ArrayList();
list.addAll((List) (request.getSession().getAttribute("value")));
%>
<tr>
<td>Model:</td>
<td><select name="model">
<%
for (int i = 0; i < list.size(); i++) {
%>
<option value=<%=list.get(i)%>><%=list.get(i)%></option>
<%
}
%>
</select><br></br></td>
</tr>
<tr>
<td>Rating For Style:</td>
<td><input type="text" name="style"><br></br></td>
</tr>
<tr>
<td>Rating for comfort:</td>
<td><input type="text" name="comfort"><br></br></td>
</tr>
<tr>
<td>Rating for Performance:</td>
<td><input type="text" name="performance"><br></br></td>
</tr>
<tr>
<td>Rating for FuelEconomy:</td>
<td><input type="text" name="economy"><br></br></td>
</tr>
<tr>
<td>Review:</td>
<td><textarea cols="18" rows="3"></textarea><br></br></td>
</tr>
<tr>
<td><Button>Save</Button></td>
<td><input type="reset" name="cancel" value="Cancel" /></td>
</tr>
</table>
</form>
When jsp loading for the first time the "value" atribute is not set.
Try to check null for value:
request.getSession().getAttribute("value")
Related
I attempted to retrieve user information from the MySQL database, but when I ran my program and searched for the user by name, nothing appeared in the HTML table. I can't figure out what's the issue. Below in my code,
Web Service Code
#WebMethod(operationName = "search")
public List<UserRegister> search(#WebParam(name = "name")String name ) {
Connection connection = DBUtils.getConnection();
List<UserRegister> user = new ArrayList<>();
UserRegister u=null;
try {
String searchQuery = "select * from register where name= ?";
PreparedStatement ps = connection.prepareStatement(searchQuery);
ps.setString(1, name);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
u = new UserRegister();
u.setName(rs.getString("name"));
u.setBranch(rs.getString("branch"));
u.setAge(rs.getString("age"));
u.setPhone(rs.getString("phone"));
user.add(u);
}
}catch(SQLException asd){
System.out.println(asd.getMessage());
}
return user;
}
Java Servlet
#WebServlet("/SearchServlet")
public class SearchServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String Name = request.getParameter("name");
UserRegister userRegister = new UserRegister();
userRegister.setName(Name);
searchClass sclass = new searchClass();
request.setAttribute("name", sclass.search(Name));
RequestDispatcher view = request.getRequestDispatcher("display.jsp");
view.forward(request, response);
}
}
Java Class For Call the Web Service
public class searchClass {
public List<UserRegister> search( String username) {
SerachService_Service service=new SerachService_Service();
SerachService proxy =service.getSerachServicePort();
return (List<UserRegister>) proxy.search(username);
}
}
JSp For Search Bar
<form method="Get" action="SearchServlet">
<table border="0" width="300" align="center" bgcolor="#CDFFFF">
<tr><td colspan=2 align="center">
<h3>Search Employee</h3></td></tr>
<tr><td ><b>User Name</b></td>
<td>: <input type="text" name="name">
<tr><td colspan=2 align="center">
<input type="submit"></td></tr>
</table>
</form>
</body>
JSP Display Data
<table>
<c:forEach var="user" items="${name}">
<tr>
<td>
<c:out value="${user.name}" />
</td>
<td>
<c:out value="${user.branch}" />
</td>
<td>
<c:out value="${user.age}" />
</td>
<td>
<c:out value="${user.phone}" />
</td>
</tr>
</c:forEach>
</body>
I have created a table in the jsp, for the table the data will be loaded from database and rendered into the jsp or web page to show the all appointments , in this particular scenario i want to delete the selected row from database .
The tried code is below but couldn't make it happen and no error is shown as well:
JSP:
<main>
<h1 style="margin-left:5rem; text-align: center; margin-top:4%;"> Scheduled Appointments </h1>
<div class="title-box">
<form method="POST">
<c:choose>
<c:when test="{empty list}">
<h1>No upcoming Appointments</h1>
</c:when>
<c:otherwise>
<table class="styled-table" style="margin-bottom: 15px; margin-top:15px;">
<thead>
<tr>
<th>Patient Name</th>
<th>Appointment Date</th>
<th>Delete</th>
</tr>
</thead>
<c:forEach items="${list}" var="record">
<c:if test="${record.ageInDays lt 1}">
<tbody>
<tr class="active-row">
<td>${record.name}</td>
<td>${record.date}</td>
<td><input type="" name="id" value="${record.appointmentId}"><i class="fas fa-trash-alt"></i></td>
</tr>
</tbody>
</c:if>
</c:forEach>
</table >
</form>
</c:otherwise>
</c:choose>
</div>
</main>
Servlet:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getServletPath().contains("/delete")){
/* deleting the appointment*/
int id= Integer.parseInt(request.getParameter("id"));
if(id>0){
StaffManager.getInstance().deleteAppointments(id);
List list = new ArrayList<>();//Creating a list to hold data
list = StaffManager.getInstance().getAppointments();//MVC method implementation for Searching patient
request.setAttribute("list", list);
request.getRequestDispatcher("/Appointments.jsp").forward(request, response);
}
}
}
The staff Manager:
public void deleteAppointments(int id) {
staff.deleteAppointments(id);
}
The Dao Class:
public void deleteAppointments(int id) {
try{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hms", "root", "");
PreparedStatement st=conn.prepareStatement("DELETE FROM appointments WHERE AppointmentsID = ? ");
st.setInt(1, id);
st.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
}
}
I'm still new into java web development , so please excuse for not always following the best practices here .
And would really appreciate help to make this work , thank you in advance.
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 have a HTML form
<form method="post" accept-charset="UTF-8"
action="<%=blobstoreService.createUploadUrl("/nonameyet")%>"
enctype="multipart/form-data">
<tr>
<td><input type="text" name=name /></td>
<td><input type="text" name=price /></td>
<td><input type="text" name=quantity /></td>
<td><input type="file" name="image" /></td>
<td><input type="submit" value="add" /></td>
</tr>
after sending the data I receive it here:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
List<BlobKey> blobKeys = blobs.get("image");
if (blobKeys.get(0) == null) {
resp.sendRedirect("/");
}
req.setCharacterEncoding("UTF-8");
BlobKey blobKey = blobKeys.get(0);
Product product = new Product();
String name = req.getParameter("name");
String priceAsString = req.getParameter("price");
int price = Integer.parseInt(priceAsString);
String quantityAsString = req.getParameter("quantity");
int quantity = Integer.parseInt(quantityAsString);
product.setName(name);
product.setPrice(price);
product.setQuantity(quantity);
String url = ImagesServiceFactory.getImagesService().getServingUrl(ServingUrlOptions.Builder.withBlobKey(blobKey));
product.setImage(url);
ofy().save().entities(product).now();
resp.sendRedirect("/index.jsp");
}
and now the JSP is:
<%
List<Product> list = ofy().load().type(Product.class).limit(20)
.list();
for (Product product : list) {
%>
<tr>
<td><%=product.getName()%></td>
<td><%=product.getPrice()%></td>
<td><%=product.getQuantity()%></td>
<td><img alt="<%=product.getName()%>"
src="<%=product.getImage()%>" width="100" height="100" /></td>
<td>delete
</tr>
<%
}
%>
But when I view the page in Chrome it looks like this:
After examining the data in http://localhost:8888/_ah/admin/datastore, I can see the word in Hebrew is correct:
So I get to the conclusion that somewhere on the way from the datastore to the jsp the text gets garbled. Can someone help?
This is jsp code what is happening is when i submit the code it will call url of ajax function and executing that function also but when returning it will call to other url
If i'm calling ajax from jsp that is going to that particular url and executing it after that it entering to the other url without returning the result
<form name="frm" action="createnewcatgoryBean.jsp" onsubmit="return validatenewcat()" method="post">
<table style="padding: 5px 0px 0px 8px;">
<tr>
<th colspan="2">
<div style="width: width:271px; color:red;" id="validate"></div>
</th>
</tr>
<tr>
<th>Category Name<span>:</span>
</th>
<td>
<input id="cat" onblur="return validatenewcat()" type="text" name="category">
</td>
</tr>
<tr>
<th>Quotations form<span>:</span>
</th>
<td>
<input type="checkbox" name="quotations">
</td>
</tr>
<tr>
<th>Agreement form<span>:</span>
</th>
<td>
<input type="checkbox" name="agreement">
</td>
</tr>
<tr>
<th>Payment form<span>:</span>
</th>
<td>
<input type="checkbox" name="payment">
</td>
</tr>
<tr>
<th>ETI<span>:</span>
</th>
<td>
<input type="checkbox" name="eti">
</td>
</tr>
<tr>
<td colspan="2" style="float:right; padding-top:15px">
<input type="submit" value="Submit" style="width: 60px;">
</td>
</tr>
</table>
</form>
This is the JavaScript code that includes the AJAX request:
function validatenewcat() {
var category = document.getElementById("cat").value;
if (category == "") {
setTimeout(document.getElementById("validate").innerHTML = "!PLz Enter The Category Name", 2000);
return false;
} else {
var url = "catnamecheck.do?id=" + category;
xmlhttp.open("post", url, true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
var temp = xmlhttp.responceText;
obj = JSON.parse(temp);
alert(obj);
if (temp != "") {
document.getElementById("validate").innerHTML = "!PLz Enter The Unique Category Name";
document.getElementById("cat").focus();
return false;
}
}
}
}
}
}
this my java code
public Map<String, String> catuniqecheck(String id) {
Connection c = null;
PreparedStatement ps1 = null;
ResultSet rs1 = null;
String sql=null;
try{
c = JDBCHelper.getConnection();
if(c!=null)
{
Map<String, String> map = new HashMap<String, String>();
sql="select * from catgory where catgoryname=?";
ps1=c.prepareStatement(sql);
ps1.setString(1, id);
ps1.execute();
rs1=ps1.getResultSet();
if(rs1.next())
{
System.out.println("insdide of the catuniqecheck");
map.put("catgoryname",rs1.getString("catgoryname"));
}
return map;
}
else
{
System.out.println("DB connection Established");
return null ;
}
}
catch (Exception e) {
// TODO: handle exception
return null ;
}
finally{
JDBCHelper.close(rs1);
JDBCHelper.close(ps1);
JDBCHelper.close(c);
}
}
this my servlet code
Map<String, String> result =p1.catuniqecheck(id);
if(result!=null)
{
System.out.println("inside success");
JSONObject json = new JSONObject();
json.accumulateAll(result);
System.out.println("inside json"+json.toString());
response.setContentType("application/json");
response.getWriter().write(json.toString());
}
try with
obj = JSON.parse("["+temp+"]")
And then first response length
alert(obj[0].length);
alert(obj[0]);
bcoz sometime response itself inside Square brackets like [{...}]