Restart Servlet after form submit - java

I'm fairly new to using servlets with JSP and I am having trouble trying to redirect back to the start of the servlet home page JSP after submitting my form jsp and I'm not sure how to accomplish this task or whether it's even possible to do that, the methods i try have at best returned the home page jsp but without the servlet default function called to fetch the data from jdbc. i've tried sendredirect() and request dispatcher to no avail and any help to where i'm going wrong would be appreciated.
i have one single servlet code for handling all operations including the insert and update which are giving problems in redirecting/reloading
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private StudentDao studentDao;
public StudentServlet() {
this.studentDao = new StudentDao();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sPath = request.getServletPath();
//switch statement to call appropriate method
switch (sPath) {
case "/new":
try {
showNewForm(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
break;
case "/insert":
try {
insertStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/delete":
try {
deleteStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/update":
try {
updateStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/edit":
try {
editStudent(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
break;
case "/StudentServlet":
try {
listAllStudents(request, response);
} catch (ServletException | IOException | SQLException e) {
e.printStackTrace();
}
break;
default:
try {
listAllStudents(request, response); //home page = .../week04/StudentServlet
} catch (ServletException | IOException | SQLException e) {
e.printStackTrace();
}
break;
}
}
// functions to fetch data from studentDao and display data on appropriate jsp
private void listAllStudents(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
List<Student> allStudents = studentDao.selectAllStudents();
request.setAttribute("listStudents", allStudents);
RequestDispatcher dispatch = request.getRequestDispatcher("student-list.jsp");
dispatch.forward(request, response);
}
private void showNewForm(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatch = request.getRequestDispatcher("student-form.jsp");
dispatch.forward(request, response);
}
private void insertStudent(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException{
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String email = request.getParameter("email");
Student newStudent = new Student(firstname, lastname, email);
studentDao.insertStudent(newStudent); //student object inserted to table
response.sendRedirect("/StudentServlet"); //redirect to home page
}
private void deleteStudent(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
studentDao.deleteStudent(id); //student object deleted
response.sendRedirect("/StudentServlet");
}
private void updateStudent(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException{
String sId = request.getParameter("id");
int id = Integer.parseInt(sId);
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String email = request.getParameter("email");
Student updateStudent = new Student(id, firstname, lastname, email);
studentDao.updateStudent(updateStudent); //student object updated
response.sendRedirect("/StudentServlet");
}
private void editStudent(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
Student currentStudent = studentDao.selectStudent(id);
RequestDispatcher dispatch = request.getRequestDispatcher("student-form.jsp"); //student form called with current student info loaded
request.setAttribute("student", currentStudent);
dispatch.forward(request, response);
}
}
here is my xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd http://java.sun.com/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee" id="WebApp_ID" version="2.4">
<servlet>
<servlet-name>StudentServlet</servlet-name>
<servlet-class>week04.web.StudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/</url-pattern>
<url-pattern>/StudentServlet</url-pattern>
<url-pattern>/new</url-pattern>
<url-pattern>/update</url-pattern>
<url-pattern>/insert</url-pattern>
<url-pattern>/delete</url-pattern>
<url-pattern>/edit</url-pattern>
</servlet-mapping>
</web-app>
here is my home page JSP i named it student-list.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.util.*" import="week04.model.Student"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, intial-scale=1 shink-to-fit=yes">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
integrity="sha38-...." crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-dark bg-primary pd-8">
<a class="navbar-brand"> XYZ University</a>
</nav>
<div class="container-fluid">
<div class="container">
<div class="form container-fluid p-4">
<a href="<%=request.getContextPath()%>/new" class="btn btn-success" >Add
Student</a>
</div>
<br>
<!--Assigning ArrayList object containing student data to the local object -->
<% ArrayList<Student> studentList = (ArrayList) request.getAttribute("listStudents"); %>
<table class="table table-bordered">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<%
if(request.getAttribute("listStudents") != null) {
Iterator<Student> iterator = studentList.iterator();
while(iterator.hasNext()) {
Student studentDetails = iterator.next();
%>
<tr><td><%=studentDetails.getFirstname()%></td>
<td><%=studentDetails.getLastname()%></td>
<td><%=studentDetails.getEmail()%></td>
<td>Update
Delete</td>
</tr>
<%
}
}
%>
</tbody>
</table>
</div>
</div>
</body>
</html>
and here is my form file that handles inserting and updating data:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, intial-scale=1 shink-to-fit=yes">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
integrity="sha384-...">
</head>
<body>
<nav class="navbar navbar-dark bg-primary pd-8">
<a class="navbar-brand"> XYZ University</a>
</nav>
<div class="container col-md-5 p-4">
<div class="card">
<div class="card-body">
<% System.out.println(request.getAttribute("student") + "hello"); %>
<% if (request.getAttribute("listStudents") != null || request.getAttribute("student") != null) { %>
<form action="<%=request.getContextPath()%>/update" method="post">
<% } else { %>
<form action="<%=request.getContextPath()%>/insert" method="post">
<% } %>
<div>
<h2>
<% if (request.getAttribute("student") != null) { %>
Edit Student
<% } else { %>
Add New Student
<% } %>
</h2>
</div>
<% if (request.getAttribute("student") != null) { %>
<input type="hidden" name="id" value="${student.id}" />
<% } %>
<fieldset class="form-group">
<legend> First Name</legend>
<% if (request.getAttribute("student") != null) { %>
<input type="text" value="${student.firstname}" class="form-control"
name="fistname" required="required">
<% } else { %>
<input type="text" value="" class="form-control" name="firstname" required="required">
<% } %>
</fieldset>
<fieldset class="form-group">
<legend>Last Name</legend>
<% if (request.getAttribute("student") != null) { %>
<input type="text" value="${student.lastname}" class="form-control"
name="lastname" required="required">
<% } else { %>
<input type="text" value="" class="form-control" name="lastname" required="required">
<% } %>
</fieldset>
<fieldset class="form-group">
<legend>Email</legend>
<% if (request.getAttribute("student") != null) { %>
<input type="text" value="${student.email}" class="form-control" name="email">
<% } else { %>
<input type="text" value="" class="form-control" name="email">
<% } %>
</fieldset>
<button type="submit" class="t-3 btn btn-success">Save</button>
</form>
</div>
</div>
</div>
</body>
</html>
Any help would be appreciated, i dont know if i'm going wrong with my servlet configuration, xml or my form page configuration.

You're receiving the exception
SQLIntergrityConstraintViolation: column firstname cannot be null
because you have a small typo in your first name form group.
<% if (request.getAttribute("student") != null) { %>
<input type="text" value="${student.firstname}" class="form-control"
name="fistname" required="required">
<% } else { %>
<input type="text" value="" class="form-control" name="firstname" required="required">
<% } %>
In the if block, the <input> text field's name="fistname" has been misspelled, while the name="firstname" is correct in the else block.
This is why your insert works with if-else only as it goes through the else block which has the correct field name. Once you fix this typo, the insert should start working without the if-else too as prescribed before.

Related

How to get a value from JSP's drop down into a servlet?

I have a drop down list in a JSP which I am reading the values from and pass it into my servlet to perform actions based on the value received.
Below is my JSP:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<form action="getdata.do" method="post">
<div align='left' >
<div align='left' >
<label class="text-white mb-3 lead">Which report do you want to generate?</label>
<select id="reportSelection" data-style="bg-white rounded-pill px-5 py-3 shadow-sm " class="selectpicker w-100" name="reportselection">
<option>Outage</option>
<option>DataQuality</option>
<option>Latency</option>
</select>
</head>
<p id = "demo"> </p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</div>
</div>
<hr class="colorgraph">
<div class="row">
<div class="row">
<div class="col-xs-12 col-md-6"><input type="submit" value="Submit" class="btn btn-primary btn-block btn-lg register" tabindex="7"></div>
</div>
</div>
</form>
</body>
</html>
I gave the drop down list an ID: reportSelection
In my servlet class, I tried to read it as below:
#WebServlet("/getdata.do")
public class DataServlet extends HttpServlet {
String message;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("In POST Method");
getTableColumn gt = new getTableColumn();
String issue = request.getParameter("reportSelection");
System.out.println("Drop Down Message: " + issue);
try {
System.out.println("In Try");
if (issue.equals("Latency")) {
message = gt.cruise("latency");
} else if (issue.equals("DataQuality")) {
message = gt.cruise("DataQuality");
System.out.println("Data quality");
} else if (issue.equals("Outage")) {
message = gt.cruise("Outage");
}
} catch (SQLException s) {
s.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I also printed the values of it just to see I am receiving any values from it.
But once I click on submit button, I see null pointer exception as
String issue = request.getParameter("reportSelection");
is receiving NULL from JSP
Could anyone let me know what is the mistake I am doing here & how do I correct it ?

How to fill camp in a jsp form before updating

I am trying to show the data of the user that I intend to update.
In my structure I enter a dni that is extracted when consulting a list, to then show the user's data in particular in another form. When this form is sent, the data will be permanently updated.
The problem I have is that I do not know how to show the user's data that I have previously searched for.
P.E: I am looking for a user called Jhon Doe with DNI 11111111E, in the second form I will have a new form with name and surname Jhon Doe, now I write in those fields of the form Mike Doe and press submmit.
The problem: I don, t know how to show the old name in my form (i don, t know hot to show Jhon Doe).
Here is my code, now i am stuck in that part, the update itseld is ok, but the name is not showed)
I have add my jsp web page to see how they works, but anyway my problem is about the way i manage to show the date from the user who will be updated.
My first jsp page here(V2formModificarUsuario1.jsp)
<%#page import="java.util.List"%>
<%#page import="Entidades.Usuario"%>
<%#page import="DAO.DAOUsuario"%>
<%#page import="Conexion.DBConnection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="usuario" class="Entidades.Usuario" />
<jsp:setProperty name="usuario" property="*"/>
<%
String message = "";
List<Usuario> usuarios = null;
DAOUsuario dao = new DAOUsuario();
try {
//usuarios = dao.selectUsuario("si","nombre");
usuarios = dao.selectAllUsuarios();
} catch (Exception ex) {
message = ex.toString();
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>V2formListarUsuariosAltaNombre</title>
<link href="../css/estilos.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="titulo">
<h1>BIBLIOTECA - LISTADOS USUARIOS</h1>
<div id="menu">
<div id="opciones">
<h2>Menu inicial</h2>
<h2>Atras</h2>
</div>
<form id="formulario" action="V2formModificarUsuario2(en obras).jsp" method="POST">
<label for="DNI">Intruduzca DNI del usuario</label><br>
DNI: <input type="text" name="DNI" required="">
<input type="submit" value="buscar">
</form>
<form>
<%if (!message.isEmpty()) {%>
<input name="status_initial" type="text" style="width:400px" value="<%=message%>"/>
<%} else { %>
<br/><br/>
<table border="1">
<tr>
<th>DNI</th>
<th>nombre</th>
<th>apellidos</th>
<th>de alta</th>
</tr>
<%for (int i = 0; i < usuarios.size(); i++) {%>
<tr>
<td><%=usuarios.get(i).getDNI()%></td>
<td><%=usuarios.get(i).getNombre()%></td>
<td><%=usuarios.get(i).getApellidos()%></td>
<td><%=usuarios.get(i).getDeAlta()%></td>
</tr>
<%}%>
</table>
<%}%>
</form>
</div>
</div>
</body>
My second jsp page here(V2formModificarUsuario2.jsp)
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.List"%>
<%#page import="Entidades.Usuario"%>
<%#page import="DAO.DAOUsuario"%>
<%#page import="Conexion.DBConnection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="usuario" class="Entidades.Usuario"></jsp:useBean>
<jsp:setProperty name="usuario" property="*"/>
<%
String message = "";
// String nameToChange = "";
String surnameToChange = "";
try {
if ((usuario.getDNI() != null) && (!usuario.getDNI().isEmpty())) {
DAOUsuario dao = new DAOUsuario();
// nameToChange=dao.selectByDNI(request.getParameter("DNI")).getNombre(); comentado por ahora
surnameToChange=dao.selectByDNI(request.getParameter("DNI")).getApellidos();
Usuario usuarios = dao.selectByDNI(usuario.getDNI());
if (usuarios != null) {
if ((usuario.getNombre() != null) && (!usuario.getNombre().isEmpty())
&& (usuario.getApellidos() != null) && (!usuario.getApellidos().isEmpty())) {
dao.update(usuario.getDNI(), usuario.getNombre(), usuario.getApellidos());
message = "User correctly updated.";
} else {
if (request.getParameter("updating") == "1") {
message = "Los campos name, surname and deAlta are required .";
}
}
} else {
message = "user do not exists.";
}
} else {
message = "DNI must not be null.";
}
} catch (Exception ex) {
message = ex.getMessage();
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSPformModificarUsuario2(en obras)</title>
<link href="css/estilos.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="titulo">
<h1>BIBLIOTECA - USUARIO</h1>
<div id="menu">
<div id="opciones">
<h2>Inicio</h2>
</div>
<form method="POST" action="V2formModificarUsuario2(en obras).jsp">
<input name="updating" type="hidden" value="1"/>
<%if (!message.isEmpty()) {%>
<input name="message" type="text" style="width:400px" value="<%=message%>"/>
<%} else { %>
<br/><br/>
DNI:
<input name="DNI" type="text" style="width:200px" value="<jsp:getProperty property="DNI" name="usuario"/>" readonly=""/>
<br/><br/>
nombre:
<input name="nombre" type="text" style="width:200px" placeholder="<%=apellidoActualizar%>" value="<jsp:getProperty property="nombre" name="usuario"/>"/>
<br/><br/>
apellidos:
<input name="apellidos" type="text" style="width:200px" value="<jsp:getProperty property="apellidos" name="usuario"/>"/>
<br/><br/>
<input type="submit" value="Actualizar"/>
<%}%>
</form>
</div>
</div>
</body>
And finally, My DAO here.
public Usuario update(String DNI, String nombre, String apellidos) throws Exception {
if ((DNI == null) || (DNI.isEmpty())) {
throw new Exception("DNI must not be null");
}
if ((nombre == null) || (nombre.isEmpty())) {
throw new Exception("name must not be null");
}
if ((apellidos == null) || (apellidos.isEmpty())) {
throw new Exception("surname must not be null");
}
Usuario usuario = selectByDNI(DNI);
if (usuario == null) {
throw new Exception("user do not exist");
}
try (Connection connection = DBConnection.get()) {
if (connection == null) {
throw new Exception("Connection is null");
}
String query = "UPDATE usuario SET nombre=?, apellidos=? WHERE DNI=?";
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, nombre);
statement.setString(2, apellidos);
statement.setString(3, DNI);
statement.execute();
} catch (Exception ex) {
throw ex;
} finally {
DBConnection.close();
}
usuario = selectByDNI(DNI);
return usuario;
}
public Usuario selectByDNI(String DNI) throws Exception {
if ((DNI == null) || (DNI.isEmpty())) {
return null;
}
Usuario usuario = null;
try (Connection connection = DBConnection.get()) {
if (connection == null) {
throw new Exception("Connection is null");
}
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM usuario WHERE DNI = '" + DNI + "'");
if (rs.next()) {
usuario = new Usuario(rs.getString("DNI"), rs.getString("nombre"),
rs.getString("apellidos"), rs.getString("deAlta"));
}
} catch (Exception ex) {
throw ex;
} finally {
DBConnection.close();
}
return usuario;
}
I have resolved, the response was qualified as repeated, but i am not agree, my solution is different:
I have created 3 forms, the first one search the DNI, the second one create an user object and fill the camps in a form(with a placeholder and a value for each one), and the last one is where i have made the updating for the user.
The code here.
the second form in a jsp page
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.List"%>
<%#page import="Entidades.Usuario"%>
<%#page import="DAO.DAOUsuario"%>
<%#page import="Conexion.DBConnection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="usuario" class="Entidades.Usuario"></jsp:useBean>
<jsp:setProperty name="usuario" property="*"/>
<%
String message = "";
String nombreActualizar = "";
String apellidoActualizar = "";
try {
if ((usuario.getDNI() != null) && (!usuario.getDNI().isEmpty())) {
DAOUsuario dao = new DAOUsuario();
nombreActualizar = dao.selectByDNI(request.getParameter("DNI")).getNombre();
apellidoActualizar = dao.selectByDNI(request.getParameter("DNI")).getApellidos();
} else {
message = "El DNI de actualización no puede ser nulo.";
}
} catch (Exception ex) {
message = ex.getMessage();
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSPformModificarUsuario2(en obras)</title>
<link href="../css/estilos.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="titulo">
<h1>BIBLIOTECA - USUARIO</h1>
<div id="menu">
<div id="opciones">
<h2>Menu inicial</h2>
<h2>Atras</h2>
</div>
<form method="POST" action="V2formModificarUsuario3(en obras).jsp">
<input name="updating" type="hidden" value="1"/>
<%if (!message.isEmpty()) {%>
<input name="message" type="text" style="width:400px" value="<%=message%>"/>
<%} else {%>
<br/><br/>
DNI:
<input name="DNI" type="text" style="width:200px" value="<jsp:getProperty property="DNI" name="usuario"/>" readonly=""/>
<br/><br/>
nombre:
<!-- <input name="nombre" type="text" style="width:200px" value="<<!--jsp:getProperty property="nombre" name="usuario"/>"/>-->
<input name="nombre" type="text" style="width:400px" placeholder="<%=nombreActualizar%>" value="<%=nombreActualizar%>"/>
<br/><br/>
apellidos:
<!--<input name="apellidos" type="text" style="width:200px" value="<<!--jsp:getProperty property="apellidos" name="usuario"/>"/>-->
<input name="apellidos" type="text" style="width:400px" placeholder="<%=apellidoActualizar%>" value="<%=apellidoActualizar%>"/>
<br/><br/>
<input type="submit" value="Actualizar"/>
<%}%>
</form>
</div>
</div>
</body>
The third form in a new one jsp page
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.List"%>
<%#page import="Entidades.Usuario"%>
<%#page import="DAO.DAOUsuario"%>
<%#page import="Conexion.DBConnection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="usuario" class="Entidades.Usuario"></jsp:useBean>
<jsp:setProperty name="usuario" property="*"/>
<%
String message = "";
DAOUsuario dao = new DAOUsuario();
String DNIActualizado="";
String nombreActualizado ="";
String apellidoActualizado = "";
if (
((request.getParameter("DNI") == null) || (request.getParameter("DNI").isEmpty()))
|| ((request.getParameter("nombre") == null) || (request.getParameter("nombre").isEmpty()))
|| ((request.getParameter("apellidos") == null) ||(request.getParameter("apellidos").isEmpty()))
) {
message = "Ningún campo del formulario debe estar vacio.";
}else{
DNIActualizado=request.getParameter("DNI");
nombreActualizado=request.getParameter("nombre");
apellidoActualizado=request.getParameter("apellidos");
usuario=dao.update(DNIActualizado, nombreActualizado, apellidoActualizado);
message = "usuario con DNI "+request.getParameter("DNI")+" actualizado";
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSPformModificarUsuario3(en obras)</title>
<link href="../css/estilos.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="titulo">
<h1>BIBLIOTECA - USUARIO</h1>
<div id="menu">
<div id="opciones">
<h2>Menu inicial</h2>
<h2>Atras</h2>
</div>
<form method="POST" action="V2formModificarUsuario3(en obras).jsp">
<input name="updating" type="hidden" value="1"/>
<%if (!message.isEmpty()) {%>
<input name="message" type="text" style="width:400px" value="<%=message%>"/>
<%} else {%>
<br/><br/>
DNI:
<input name="DNI" type="text" style="width:200px" value="<jsp:getProperty property="DNI" name="usuario"/>" readonly=""/>
<%}%>
</form>
</div>
</div>
</body>

The page you tried to access (/manager/projects) does not exist - intellij 13.1 under tomcat7

I want to run web project on intellij 13.1 under tomcat 7.0.52.
This application has 3 roles - admin / manager / user.
And when I want to access manager role it shows - 404 Not found:
here is snippet of LoginServlet
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
HttpSession session = request.getSession();
String email = request.getParameter("email");
String password = MD5Utils.getMD5String(request.getParameter("password"));
User user = null;
try {
user = new UserService().getByEmail(email);
} catch (DAOException e) {
log.error(e);
}
if (user != null) {
if (!ValidationUtils.isNullOrEmpty(user.getEmail()) && user.getPassword().equals(password)) {
session.setAttribute("user", user);
log.info("Logged in: " + user.getFirstName() + " " + user.getLastName());
if (session.getAttribute("waitUrl") != null) {
String url = session.getAttribute("waitUrl").toString();
response.sendRedirect(url);
} else {
String contextPath = request.getContextPath();
if (user.getRoleId().equals(1)) { // 1=user role
response.sendRedirect(contextPath + "/user/tasks");
} if (user.getRoleId().equals(2)) { // 2 manager role
response.sendRedirect(contextPath + "/manager/projects");
} if (user.getRoleId().equals(3)) { // 3 admin role
response.sendRedirect(contextPath + "/admin/users");
}
}
} else {
request.setAttribute("loginErrors", "Wrong email or password");
request.getRequestDispatcher("/pages/login.jsp").forward(request, response);
}
}
}
From Login it's renderer to:
#WebServlet("/manager/projects")
public class OutProjects extends HttpServlet {
private static Logger log = Logger.getLogger(OutProjects.class);
private ProjectService projectService;
private List<Project> projects;
#Override
public void init() throws ServletException {
projectService = new ProjectService();
updateTable();
}
private void updateTable() {
try {
projects = projectService.getListOfObjects();
} catch (DAOException e) {
log.error(e);
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().setAttribute("projects", projects);
request.getRequestDispatcher("/pages/manager/projects.jsp").forward(request, response);
}
and next jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="language"
value="${not empty param.language ? param.language : not empty language ? language : pageContext.request.locale}"
scope="session"/>
<fmt:setLocale value="${language}"/>
<fmt:setBundle basename="com.java.task11.i18n.text"/>
<html lang="${language}">
<head>
<title>Projects</title>
<jsp:include page="header.jsp" />
</head>
<body>
<div class="container">
<div id="tableContainer-1">
<TABLE class="table table-bordered" >
<thead>
<tr>
<th>#</th>
<th><fmt:message key="project.name"/></th>
<th><fmt:message key="project.description"/></th>
<th><fmt:message key="project.notes"/></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<c:forEach var="project" items="${sessionScope.projects}">
<form action="${pageContext.request.contextPath}/pages/manager/updateprojects" name="updateProject" method="post">
<tr>
<td>${project.id}</td>
<td>${project.projectName}</td>
<td>${project.description}</td>
<td>${project.notes}</td>
<td><button class="btn btn-inverse" type="submit" name="update" value="${project.id}">
<fmt:message key="button.update"/></button></td>
<td><button class="btn btn-danger" type="submit" name="delete" value="${project.id}">
<fmt:message key="button.delete"/></button></td>
<td><button class="btn btn-info" type="submit" name="project_id" value="${project.id}">
<fmt:message key="project.tasks"/></button></td>
</tr>
</form>
</c:forEach>
<fmt:message key="button.addProject"/>
</tbody>
</TABLE>
</div>
</div>
</body>
</html>
I couldn't figure out why this happen?
I looked into tomcat-users.xml:
<role rolename="admin" />
<role rolename="tomcat" />
<role rolename="developer" />
<role rolename="customer" />
<role rolename="user" />
<user username="admin" password="admin" roles="admin,tomcat,user,customer" />
<user username="nazar" password="nazar" roles="admin,tomcat,developer,customer,user" />
<user username="developer" password="developer" roles="admin,tomcat,developer,customer,user" />
How to solve this trouble?
You have Tomcat's Manager application deployed at the context path /manager so any request that starts with /manager is routed to that application. It looks like you need to undeploy Tomcat's manager application to allow your application to handle URLs starting with /manager.

I want to automatically increase table row after clicking button

Hi, my problem is increasing the table row automatically. Actually, when I click GET button the product type and product name values are getting from database. Here, after getting those values, I will give another id based on that id again for values will come. But it was not setting in another row. Here is my java code and jsp:
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver loaded");
System.out.println("Driver is loaded");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/charms?user=root&password=root");
System.out.println("Connection created");
Statement st =con.createStatement();
String query="select * from product where ProductType_v='"+a+"' and ProductId_v='"+b+"'";
ResultSet rs = (ResultSet)st.executeQuery(query);
int i=0;
while(rs.next())
{
i++;
request.getSession().setAttribute("edit","success");
request.getSession().setAttribute("proType ", rs.getString("ProductType_v"));
request.getSession().setAttribute("proId", rs.getString("ProductId_v"));
request.getSession().setAttribute("strength", rs.getString("Strength_v"));
request.getSession().setAttribute("proName", rs.getString("ProductName_v"));
request.getSession().setAttribute("brand", rs.getString("BrandName_v"));
request.getSession().setAttribute("generic", rs.getString("GenricName_v"));
request.getSession().setAttribute("uom", rs.getString("UOM_v"));
request.getSession().setAttribute("formE", rs.getString("FormE_v"));
request.getSession().setAttribute("presReqd", rs.getString("PresReqd_v"));
}
if(i==0)
{
request.getSession().setAttribute("edit", "fail");
}
}
catch(Exception e)
jsp code
<tr>
<td>
<input class="textfield-form-date-req" type="text" id="pro_type">
</td>
<%
if(editStatus =="success")
{
%>
<script type="text/javascript">
document.getElementById("pro_type").value='<%=session.getAttribute("proType")%>';
</script>
<%
}
<td>
<input class="textfield-form-date-req" type="text" id="pro_id">
</td>
<%
if(editStatus =="success")
{
%>
<scripttype="text/javascript">
document.getElementById("pro_id").value='<%=session.getAttribute("proName")%>';
</script>
<%
}
%>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
I have created a sample for you with ajax. It gets the data from the server side and append it , in the existing table.
The jar files I have used is ,
jackson-all-1.9.0.jar - to convert the java object to json format
servlet-api-2.4.jar - for servlet
My TableAppend.jsp will be,
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
//alert("DOM is ready");
});
function sendData() {
$.ajax({
type : 'POST',
url : "TableAppend",
data : "name=" + $('#name').val() + "&age=" + $('#age').val()
+ "&sid=" + new Date(),
dataType : 'html',
success : function(result) {
//alert("Result ::::>>> "+result);
if(result != null && $.trim(result) != "" && result != undefined){
var json = JSON.parse(result);
//alert(json.name);
//alert(json.age);
appendToTable(json.name, json.age);
}
},
error : function(e) {
alert('Error in Processing');
}
});
}
function appendToTable(name, age) {
var tr = "<tr><td>" + name + "</td><td>" + age + "</td></tr>"
$('#mytable').append(tr);
}
</script>
</head>
<body>
Name :
<input type="text" id="name" name="name" /> Age :
<input type="text" id="age" name="age" />
<input type="button" value="Append to table" onclick="sendData()">
<br></br>
<br></br>
<br></br>
<table id="mytable" border="1">
<tbody>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>HumanBeing</td>
<td>25</td>
</tr>
<tr>
<td>Saideep</td>
<td>26</td>
</tr>
</tbody>
</table>
</body>
</html>
My TableAppend.java servlet will be,
public class TableAppend extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public TableAppend() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("UTF-8");
response.setContentType("UTF");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String age = request.getParameter("age");
String json ="";
System.out.println("-----------------");
if(name != null && age != null){
TableAppendPojo obj = new TableAppendPojo();
obj.setName(name);
obj.setAge(age);
ObjectMapper mapper = new ObjectMapper();
json = mapper.writeValueAsString(obj);
System.out.println("json : "+json);
}
out.println(json);
}
}
Then java class will be,
public class TableAppendPojo {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
Note : Please apply the above logic in your code . In your case , you don't need to give the data from the UI. You retrieves the data from the database in the servlet.So please convert the retrieved data from the database to the json format and append it to the table.
Hope this helps.

JSP + Ajax not working

Objective: If I type an email id, in the html form it has to send the request to jsp where it does the logic and has to print(in the html form) whether the email is available or not. I have the following code. Please do help me which part I am doing wrong.
CreateAccount.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">
<script type="text/javascript" src="emailStore.js"></script>
</head>
<body onload="process()">
<form name="login">
<table align="center">
<tr>
<td>Email*</td>
<td><input type="text" name="userinput" id="userinput"/></td>
<td><div id = "underInput"></div></td>
</tr>
<tr>
<td>Password*</td>
<td><input type="password" name="pswrd" /></td>
</tr>
<tr>
<td>Repeat Password*</td>
<td><input type="password" name="pswrd1" /></td>
</tr>
<tr>
<td>First Name*</td>
<td><input type="text" name="userid" /></td>
</tr>
<tr>
<td>Last Name*</td>
<td><input type="text" name="userid" /></td>
</tr>
<tr>
<td>Phone Number</td>
<td><input type="text" name="userid" /></td>
</tr>
</table>
<div style="text-align: center">
<input type="submit" value="Create Account"/>
</div>
</form>
</body>
</html>
The ajax part in a javascript file. emailStore.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequest()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new ActiveXObject();
}
catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
{
alert("can't create that object");
}
else
{
return xmlHttp;
}
}
function process()
{
if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
{
email = encodeURIComponent(document.getElementById("userinput").value);
xmlHttp.open("GET", "emailStore.jsp?email=" + email, true);
xml.onreadystatechange = handle.ServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()', 1000);
}
}
function handleServerResponse()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML = '<span style = "color:blue">' + message + '</span>';
setTimeout('process()',1000);
}
else
{
alert('Something went Wrong');
}
}
}
And the logic part in a jsp file- emailStore.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>
<%
String email = request.getParameter("userinput");
ArrayList<String> emails = new ArrayList<String>();
emails.add("something#gmail.com");
if (emails.contains(email)) {
out.println("Email already taken!");
} else {
out.println("Email available");
}
%>
</body>
</html>
I would advise you of the following:
Use library JQuery;
Use Servlet instead of the JSP;
Keep a list in the session;
Do not use a tabular layout. Instead, use div- layers, and cascading style sheets.
Here is a simple example, front- end part is ..
<head>
...
<script>
$(document).ready(function() {
$('#submit').click(function(event) {
var input=$('#userinput').val();
$.get('ActionServlet',{userinput:input},function(responseText) {
$('#underInput').text(responseText);
});
});
});
</script>
...
</head>
<body>
...
<form id="form1">
...
Email
<input type="text" id="userinput"/>
<input type="button" id="submit" value="Submit"/>
<br/>
<div id="underInput">
</div>
...
</form>
...
</body>
</html>
..and server side -
...
public class ActionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ActionServlet() {
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String answer = "Something went Wrong";
String userinput = request.getParameter("userinput").toString();
HttpSession httpSession = request.getSession(true);
if(httpSession.isNew()) {
httpSession.setAttribute("sessionVar", new ArrayList<String>());
}
List<String> arrayList = (ArrayList<String>)httpSession.getAttribute("sessionVar");
if(userinput != null && !userinput.equals("")) {
if(arrayList.contains(userinput)) {
answer = "Email already taken!";
} else {
arrayList.add(userinput);
answer = "Email available";
}
}
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(answer);
}
...

Categories

Resources