JSP form submit and list population issue - java

I'm having a couple issues with a simple JSP app. When I go to the Add or Delete pages, I'm able to input data and submit it, the item is either added or deleted to/from the database as it is supposed to be, but instead of returning me to the page, it sends me to a page that says, "Served at: /ToDoList". I can use the back button to return to the page, but it is supposed to simply reload the same jsp page. It worked previously, but I'm not sure what I changed.
Additionally, I'm trying to populate a table with the data from a database on the Show List page (show.jsp), but it gives me a ConcurrentModificationException that I can't figure out. I'm really not sure what I'm doing wrong here. Any help is appreciated. The ListItem object is just an int itemID and string itemDesc. Code follows:
add.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Add an item</title>
</head>
<body>
<h1>Add an item</h1>
<form action="AddItem" method="post">
<table>
<tr><td><input type="text" name="desc" value="" size="100"/></td></tr>
<tr><td><input type="submit" value="Submit" name="addSub" /></td></tr>
</table>
</form>
<input type="submit" name="btnAdd" value="Back to menu" onclick="window.location='/ToDoList/index.jsp'">
</body>
</html>
delete.jsp
<%#page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Show list</title>
</head>
<body>
<h1>To-Do List</h1>
<form action="ShowList" method="post">
<input type="submit" value="Populate">
</form>
<table>
<c:forEach var="item" items="${dispList}">
<tr>
<td>${item.itemID}</td>
<td>${item.itemDesc}.</td>
</tr>
</c:forEach>
</table>
<input type="submit" name="btnAdd" value="Back to menu" onclick="window.location='/ToDoList/index.jsp'">
</body>
</html>
show.jsp
<%#page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Show list</title>
</head>
<body>
<h1>To-Do List</h1>
<form action="ShowList" method="post">
<input type="submit" value="Populate">
</form>
<table>
<c:forEach var="item" items="${dispList}">
<tr>
<td>${item.itemID}</td>
<td>${item.itemDesc}.</td>
</tr>
</c:forEach>
</table>
<input type="submit" name="btnAdd" value="Back to menu" onclick="window.location='/ToDoList/index.jsp'">
</body>
</html>
ItemList.java
package todolist;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.apache.tomcat.util.http.fileupload.util.LimitedInputStream;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
public class ItemList {
List<ListItem> list = new ArrayList<>();
List<ListItem> tempList = new ArrayList<>();
public static SessionFactory factory;
public ItemList() {
super();
}
public void addItem(String itemStr) {
//list.add(item);
//list.get(list.size() - 1).setItemNumber(list.size());
ListItem item = new ListItem(itemStr);
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
Session session = factory.openSession();
Transaction tx = null;
Integer itemID = null;
try {
tx = session.beginTransaction();
itemID = (Integer) session.save(item);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public void delItem(int itemNbr) {
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
Session session = factory.openSession();
Transaction tx = null;
ListItem item2 = (ListItem)session.get(ListItem.class, itemNbr);
try {
tx = session.beginTransaction();
session.delete(item2);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public List<ListItem> getList() {
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query<ListItem> queryList = session.createQuery("FROM itemlist");
tempList = queryList.list();
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
list = tempList;
return list;
}
public int size() {
return list.size();
}
}
AddItem.java
package todolist;
import java.io.IOException;
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;
/**
* Servlet implementation class AddItem
*/
#WebServlet("/AddItem")
public class AddItem extends HttpServlet {
private static final long serialVersionUID = 1L;
ItemList list = new ItemList();
/**
* #see HttpServlet#HttpServlet()
*/
public AddItem() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("add.jsp");
rd.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("desc")!=null) {
String desc = request.getParameter("desc");
list.addItem(desc);
RequestDispatcher rd = request.getRequestDispatcher("add.jsp");
rd.forward(request, response);
}
}
}
DelItem.java
package todolist;
import java.io.IOException;
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 org.hibernate.HibernateException;
/**
* Servlet implementation class DelItem
*/
#WebServlet("/DelItem")
public class DelItem extends HttpServlet {
private static final long serialVersionUID = 1L;
ItemList list = new ItemList();
/**
* #see HttpServlet#HttpServlet()
*/
public DelItem() {
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
RequestDispatcher rd = request.getRequestDispatcher("delete.jsp");
rd.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("itemNbr")!=null && request.getParameter("itemNbr")!="") {
int itemNbr = Integer.parseInt(request.getParameter("itemNbr"));
list.delItem(itemNbr);
RequestDispatcher rd = request.getRequestDispatcher("delete.jsp");
rd.forward(request, response);
}
}
}
ShowList.java
package todolist;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
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;
/**
* Servlet implementation class ShowList
*/
#WebServlet("/ShowList")
public class ShowList extends HttpServlet {
private static final long serialVersionUID = 1L;
ItemList list2 = new ItemList();
/**
* #see HttpServlet#HttpServlet()
*/
public ShowList() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("show.jsp");
rd.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<ListItem> tempList = new ArrayList<>();
tempList = list2.getList();
request.setAttribute("dispList", tempList);
RequestDispatcher rd = request.getRequestDispatcher("show.jsp");
rd.forward(request, response);
}
}

Related

The servlet call order failed

Good afternoon!
In an example I did in class, when I debug the servlet comes in front of the filter.
On the system I'm doing the filter is called first that the servlet ... and this is causing problems.
I'm doing the login part of the system.
I am using version 3.0 of the servlet.
In class I did not need to use xml, but in some sites indicate to do this ... which also did not work.
Index
<%# 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>
<div>
<form action="template/inicio.html" method="post">
<label for="login">Login </label>
<input type="text" name="login">
<br>
<label for="senha">Senha </label>
<input type="text" name="senha">
<br>
<input type="submit" value="Entrar">
</form>
</div>
${msg}
</body>
</html>
FiltroLogin
package filtro;
import java.io.IOException;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet Filter implementation class FiltroLogin
*/
#WebFilter(
dispatcherTypes = {
DispatcherType.REQUEST,
DispatcherType.FORWARD,
DispatcherType.INCLUDE,
DispatcherType.ERROR
}
,
urlPatterns = {
"/FiltroLogin",
"/template/*"
})
public class FiltroLogin implements Filter {
/**
* Default constructor.
*/
public FiltroLogin() {
// TODO Auto-generated constructor stub
}
/**
* #see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* #see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
if(session.getAttribute("login") != null ){
//Se estiver logado, deixa a pagina ser exibida
chain.doFilter(request, response);
}else{
//mandar embora
res.sendRedirect( req.getContextPath() );
}
}
/**
* #see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
ControleLogin
package control;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.firebirdsql.jdbc.parser.JaybirdSqlParser.function_return;
import model.Funcionario;
import persistence.FuncionarioDao;
import persistence.LoginDao;
/**
* Servlet implementation class ControleLogin
*/
#WebServlet({"/ControleLogin","/template/inicio.html", "/template/logout.html"})
public class ControleLogin extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ControleLogin() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
execute(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
execute(request, response);
}
protected void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
String url = request.getServletPath();
if(url.equalsIgnoreCase("/template/inicio.html")){
String login = request.getParameter("login");
String senha = request.getParameter("senha");
if(new LoginDao().logar(login, senha).booleanValue() == true){
Funcionario func = new LoginDao().buscarUsuario(login);
HttpSession session = request.getSession();
session.setAttribute("nomeP", func.getNome());
response.sendRedirect("template/indCadastro.jsp");
}else{
request.setAttribute("msg", "<div class = 'alert alert-info'>"+ "Email ou senha Incorretos!"+"</div>");
request.getRequestDispatcher("../index.jsp").forward(request, response);
}
}else if(url.equalsIgnoreCase("/template/logout.html")){
HttpSession session = request.getSession();
session.removeAttribute("nomeP");
session.invalidate();
response.sendRedirect( request.getContextPath() + "/");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
I solved The index, was with the "Action =" template / Logar "", when I switched to "Action =" Logar "", it worked.
Silly mistake.

Can't get SQL query results to display on a JSP Page table?

I am creating a dynamic web project using eclipse, following the MVC design. I am currently trying to get data from my sql table to display on a JSP page but it just comes back as blank. I am using JNDI datasorce for the connection which works fine. when l deploy the project to the server the table headers appear fine but with no data below.
Here’s my Code
JSP code
<%# 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>
<title>View All Students</title>
</head>
<body>
<h1>Students List</h1>
<table cellpadding="5" border=1>
<tr valign="bottom">
<th><%= request.getAttribute("Student_Id") %></th>
<th>First Name</th>
<th>Last Name</th>
<th>Week 1</th>
<th>Week 2</th>
<th>Week 3</th>
<th>Week 4</th>
<th>Week 5</th>
<th>Week 6</th>
<th>Week 7</th>
<th>Week 8</th>
<th>Week 9</th>
<th>Week 10</th>
<th>Week 11</th>
<th>Week 12</th>
</tr>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach var="student" items="${viewAllStudents}">
<tr valign="top">
<td><p>${student.Student_Id}</td>
<td><p>${student.firstName}</td>
<td><p>${student.lastName}</td>
<td><p>${student.Week1}</td>
<td><p>${student.Week2}</td>
<td><p>${student.Week3}</td>
<td><p>${student.Week4}</td>
<td><p>${student.Week5}</td>
<td><p>${student.Week6}</td>
<td><p>${student.Week7}</td>
<td><p>${student.Week8}</td>
<td><p>${student.Week9}</td>
<td><p>${student.Week10}</td>
<td><p>${student.Week11}</td>
<td><p>${student.Week12}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
Servelt (Controller) Code
package uk.ac.qub.PTStudentView;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
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 javax.sql.DataSource;
import uk.ac.qub.Beans.Student;
import uk.ac.qub.LoginController.Account;
/**
* Servlet implementation class PTStudentViewController
*/
#WebServlet("/PTStudentViewController")
public class PTStudentViewController extends HttpServlet {
private static final long serialVersionUID = 1L;
private DataSource ds;
/**
* #see HttpServlet#HttpServlet()
*/
public PTStudentViewController() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
try {
InitialContext initContext = new InitialContext();
Context env = (Context) initContext.lookup("java:comp/env");
ds = (DataSource) env.lookup("jdbc/testdb");
} catch (NamingException e) {
throw new ServletException();
}
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<Student> viewAllStudents = PTViewStudent.list();
request.setAttribute("students", viewAllStudents); // Will be available as ${students} in JSP
request.getRequestDispatcher("ViewAllStudentsPage.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Cannot obtain products from DB", e);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Class for Sql statment
package uk.ac.qub.PTStudentView;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import uk.ac.qub.Beans.Student;
public class PTViewStudent {
private static Connection conn;
public PTViewStudent (Connection conn){
this.conn = conn;
}
public static List<Student> list() throws SQLException{
String sql = "select * from student where Student_Id = 666";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
List<Student> viewAllStudents = new ArrayList<>();
while(rs.next()){
Student student = new Student();
student.setId(rs.getInt("Student_Id"));
student.setFirstName(rs.getString("firstName"));
student.setLastName(rs.getString("lastName"));
student.setWeek1(rs.getDouble("Week1"));
student.setWeek2(rs.getDouble("Week2"));
student.setWeek3(rs.getDouble("Week3"));
student.setWeek4(rs.getDouble("Week4"));
student.setWeek5(rs.getDouble("Week5"));
student.setWeek6(rs.getDouble("Week6"));
student.setWeek7(rs.getDouble("Week7"));
student.setWeek8(rs.getDouble("Week8"));
student.setWeek9(rs.getDouble("Week9"));
student.setWeek10(rs.getDouble("Week10"));
student.setWeek11(rs.getDouble("Week11"));
student.setWeek12(rs.getDouble("Week12"));
viewAllStudents.add(student);
}
return viewAllStudents;
}
}
Thanks For any help
I found your bug!
Right, so in your jsp, you have this line of code
<c:forEach var="student" items="${viewAllStudents}">
Which means, look in the request scope for a list called viewAllStudents, and then loop through them all
Which is valid, however, in your actual servlet code, you have this:
List<Student> viewAllStudents = PTViewStudent.list();
request.setAttribute("students", viewAllStudents); // Will be available as ${students} in JSP
request.getRequestDispatcher("ViewAllStudentsPage.jsp").forward(request, response);
Which is also valid, however, you need to change your JSTL to be this
<c:forEach var="student" items="${students}">

Making link go to servlet to redirect to another page

SO first off let me begin by saying that my servlet loads the option lists in a form i have just fine. The problem is when i start from the index.jsp like i want, the lists dont load. So basically, i want to click a link on the index.jsp to take me to the servlet to then redirect me to the correct page based on the link clicked. Maybe I have been looking at this too long and just need fresh eyes but I cant get why it wont work.
I have included my Index.jsp and servlet
Index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.ArrayList" %>
<!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 method="get" action="customerServlet">
Add Customer
<br/>
Add Pet
</form>
</body>
</html>
Servlet
package edu.witc.Assignment03.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.servlet.annotation.WebServlet;
//import javax.servlet.http.HttpServlet;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import edu.witc.Assignment03.model.Customer;
import edu.witc.Assignment03.model.Phone;
import edu.witc.Assignment03.model.States;
#WebServlet(description = "servlet to get act as controller between form and models", urlPatterns = { "/customerServlet","/addCustomer","/addPet" })
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public CustomerServlet() {
super();
}
private void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
Phone phone = new Phone();
States state = new States();
Collection<Phone> phones = phone.getPhoneCollection();
Collection<States> states = state.getStateCollection();
session.setAttribute("phones", phones);
session.setAttribute("states", states);
request.getRequestDispatcher("/customerManagement.jsp").forward(request, response);
//}
}
private List<edu.witc.Assignment03.model.Customer> customers = new ArrayList<Customer>();
private void addCustomer(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/customerManagement.jsp";
processRequest(request, response);
request.getRequestDispatcher(url).forward(request,response);
}
private void addPet(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/pets.jsp";
request.getRequestDispatcher(url).forward(request,response);
}
private Customer getCustomer(int customerId) {
for (Customer customer : customers) {
if (customer.getCustomerId() == customerId) {
return customer;
}
}
return null;
}
private void sendEditCustomerForm(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String url = "/customerManagement.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String uri = request.getRequestURI();
if (uri.endsWith("/addCustomer")) {
addCustomer(response, request);
} else if (uri.endsWith("/addPet")) {
addPet(response, request);
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
// update customer
int customerId = 0;
try {
customerId =
Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
}
Customer customer = getCustomer(customerId);
if (customer != null) {
customer.setFirstName(request.getParameter("firstName"));
customer.setLastName(request.getParameter("lastName"));
customer.setEmail(request.getParameter("email"));
customer.setPhone(request.getParameter("phone"));
customer.setAddress(request.getParameter("address"));
customer.setCity(request.getParameter("city"));
customer.setZip(request.getParameter("zip"));
}
}
}
It would be easier to use one parameter and check the value than to manually parse the URL:
Add Customer
<br/>Add Pet
In your servlet:
String action = request.getParameter("action");
if("addCustomer".equals(action)) { ... }
else if("addPet".equals(action)) { ... }
if you are using "forms", this could be the solution to send params to servlet.
<form action="ServletName" method="POST">
<input type="text" name="paramName">
<input type="submit" value="Add">
</form>
In Servlet:
String costumerName = request.getParameter("paramName");
If you just use a link like href, you should send the param like:
<a href="ServletName?ID=12345">
In servlet, same.
String costumerName = request.getParameter("ID");

File upload using servlet returning NULL value as exception

hi i am uploading images in to data base using servlets. when i submit my form i am getting a exception "NULL" here is my code any help are accepted.And can any one suggest me which way to be used to upload files in to database such that there wont be much of load on database and lessen httprequest. thank you in advance.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="requirementlogic.*,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>
<body>
<form method="post" action="../InsertImage">
<table>
<tr><TD ><B>Upload Image</B></TD>
<td><input type="file" name="Image" size="20" value=""></TD>
</tr>
<tr>
<td><input type="submit" height="30" width="62"> </td>
</tr>
<tr>
</table>
</form>
</body>
</html>
here is my JDBC:
package requirementlogic;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DataBase {
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String dbname= "deshopa";
String driver ="com.mysql.jdbc.Driver";
String Username="root";
String Password ="";
public Connection getConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+dbname,Username,Password);
return con;
}
}
here is my servlet:
package requirementlogic;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class InsertImage
*/
#WebServlet("/InsertImage")
public class InsertImage extends HttpServlet {
private static final long serialVersionUID = 1L;
DataBase db;
/**
* #see HttpServlet#HttpServlet()
*/
public InsertImage() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
db = new DataBase();
}
/**
* #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 {
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
try
{
String strpath=request.getParameter("image");
String filepath=strpath.substring(strpath.lastIndexOf(".")+1);
pw.println(filepath);
File imgfile = new File(strpath);
FileInputStream fin = new FileInputStream(imgfile);
String sql = "insert into upload_image(image,image_name,image_length)";
PreparedStatement pre = db.getConnection().prepareStatement(sql);
pre.setBinaryStream(1,fin,(int)imgfile.length());
pre.setString(2,filepath);
pre.setLong(3,imgfile.length());
pre.executeUpdate();
pre.close();
pw.println("done");
}
catch(Exception e){
pw.println("direct exception");
pw.println("Exception is "+ e.getMessage());
}
}
}
Sql query used to create table:
CREATE TABLE `upload_image` (
`Image_id` int(11) NOT NULL AUTO_INCREMENT ,
`IMAGE` longblob NULL DEFAULT NULL ,
`Image_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
`image_length` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
PRIMARY KEY (`Image_id`)
)
change to this
String strpath=request.getParameter("Image");
as in your html form the name of the file field is Image not image
<td><input type="file" name="Image" size="20" value=""></TD>
also you are dealing with multipart request so you have to chenge your code
if(ServletFileUpload.isMultipartContent(request)){
private final String UPLOAD_DIRECTORY = "C:/uploads";
try {
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
String name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
}
}
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}
}
See the below link for further details
http://javarevisited.blogspot.in/2013/07/ile-upload-example-in-servlet-and-jsp-java-web-tutorial-example.html
You are trying this:
String strpath=request.getParameter("image");
Try this:
String strpath=request.getParameter("Image");
Error is name which you are trying. Name in capital letter.
<input type="file" name="Image" size="20" value="">
In case
File file = new File("yourPath");
file.mkdirs();
You can try this Link1 and Link2

using httpsession for session management

facing problem to manage session in servlet program. this is my servlet code.
//`SessionUsingHttpSession .java
package suprio.servlets.examples;
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;
import javax.servlet.http.HttpSession;
import org.apache.catalina.Session;
/**
* Servlet implementation class SessionUsingHttpSession
*/
public class SessionUsingHttpSession extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public SessionUsingHttpSession() {
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
response.setContentType("<html/text");
String name = request.getParameter("txtName4");
String pass = request.getParameter("txtPassword4");
if(pass.equals("12345"))
{
HttpSession session = request.getSession();
session.setAttribute("user", name);
//response.sendRedirect("SessionUsingHttpSessionRedirected");
RequestDispatcher rd = request.getRequestDispatcher("SessionUsingHttpSessionRedirected");
}
}
}
and the following code is the redirected from SessionUsingHttpSession.java
//SessionUsingHttpSessionRedirected.java
package suprio.servlets.examples;
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;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class SessionUsingHttpSessionRedirected
*/
public class SessionUsingHttpSessionRedirected extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public SessionUsingHttpSessionRedirected() {
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
response.setContentType("html/text");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String user = (String) request.getAttribute("user");
out.print("Hello"+user);
}
}
and this is for view part
// UsingHttpSession.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>Insert title here</title>
</head>
<body>
<form method="get" action="SessionUsingHttpSession">
Enter Name:<input type="text" name="txtName4"/><br/>
Password: <input type="text" name="txtPassword4"/><br/>
<input type="Submit" value="Enter">
</form>
</body>
</html>
while i am trying to run it through apache tomcat server my web browsers(mozila,chrome,IE) showing this message:
if i save and open it it is giving "hello null" as output. Now my question is that why its showing such message as i am just trying to forward this page to another.
Thank you in advance.
The content type is wrong in both servlets. It should be text/html.
Moreover is you are using SessionUsingHttpSession servlet just for redirection then there is no need for specifying the content type at all.
Your content type appears reversed, you have it as html/text, instead of text/html.
Also it's a good habbit to flush/close stream after you write.
out.print("Hello"+user);
out.flush();
out.close();

Categories