Why cannot I display user List? - java

I have a Person.class with parameters: name, age, email and I have a jsp form for adding new user into ArrayList
#WebServlet(urlPatterns = "/addclientform.jsp")
public class AddClientServlet extends HttpServlet {
private PersonStorage personlist1 = new PersonStorage();
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
int age = Integer.parseInt(req.getParameter("age"));
String email = req.getParameter("email");
Person person = new Person(name, age, email);
personlist1.addPerson(person);
req.setAttribute("list", personlist1);
req.getRequestDispatcher("clientList.jsp").forward(req,resp);
}
}
<html>
<head>
<title>Clien Page</title>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Email</th>
</tr>
<c:forEach items="${list}" var="personlist">
<tr>
<td>${personlist.name}</td>
<td>${personlist.age}</td>
<td>${personlist.email}</td>
</tr>
</c:forEach>
</table>
<form name="home" action="home.jsp" method="post">
<input type="submit" value="back">
</form>
</body>
</html>
but when I want to see all users I cannot do this.
Where I made a mistake?

You need to add the following directive at the top of the page:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

Related

How to redirect jsp

I have LoginServlet like this:
package servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username.equals("gogikole") && password.equals("1234")) {
response.sendRedirect("mainMenu.jsp");
return;
}
}
}
And login.jsp like this:
<%# 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>Login page</title>
</head>
<body>
<form method="post" action="LoginServlet"></form>
<table>
<tr>
<td>User name</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</body>
</html>
For some reason when I input correct username: (gogikole) and password: (1234) and click on submit button it won't to redirect me to mainMenu.jsp
When I click on button, nothing happen it just stay on login page like I didn't even click or type anything.
How to fix that problem and redirect when I click on submit button (Login)?
I created mainMenu.jsp and, for now that is one allmost blank page only with message "Welcome".
Your submit button is not submitting the form.
i.e., you have closed the form immediately:
<form method="post" action="LoginServlet"></form>
The problem is that your form inputs and submit button are outside the form You have to enclose as below.
<form method="post" action="LoginServlet">
<table>
<tr>
<td>User name</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>

Pass data to JSP page using spring

I am using a spring(not mvc), servlet, jsp for my web app, I wanted to display the list of users on jsp page, how it can be done? here is my code
LoginService.java
#Service
public class LoginService {
#PersistenceContext
EntityManager em;
public User getUserByUserName(String userName, String password) {
User user = null;
try {
user = em.createQuery("from User u where u.userName = :userName and u.password = :password", User.class)
.setParameter("userName", userName)
.setParameter("password", password)
.getSingleResult();
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
public List<User> getListOfUsers() {
return em.createQuery("from User u", User.class).getResultList();
}
}
LoginServlet.java
#Component
public class LoginServlet extends HttpServlet {
#Autowired
LoginService loginService;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
EntityManagerFactory emf = (EntityManagerFactory) request.getServletContext().getAttribute("emf");
String userName = request.getParameter("userName");
String password = request.getParameter("password");
User user = loginService.getUserByUserName(userName, password);
if(user != null){
request.getSession().setAttribute("user", user);
response.sendRedirect("home.jsp");
}
else{
response.sendRedirect("login.jsp");
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
Login.jsp
<%#page contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form id="form" name="form" method="post" action="login">
<h1>Login</h1>
Please enter your login information
<br/>New User? Register
Enter your user ID
<input type="text" name="userName" id="userId"/>
Password
<input type="password" name="password" id="password"/>
<button type="submit">Sign-in</button>
</form>
</body>
</html>
Home.jsp
<%#page import="demo.spring.entity.User" %>
<%#page import="java.util.Date" %>
<%# page import="java.util.List" %>
<%#page contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>User</h1>
<form id="form" name="form" method="post" action="update">
<p>
<%=new Date()%></br>
<%
User user = (User) session.getAttribute("user");
%>
<b>Welcome <%= user.getFirstName() + " " + user.getLastName()%>
</b>
<br/>
Logout
</p>
<table>
<thead>
<tr>
<th>User ID</th>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>email</th>
</tr>
</thead>
<%--<tbody>
<%
LoginService loginService = new LoginService();
List<User> list = loginService.getListOfUsers();
for (User u : list) {
%>
<tr>
<td><input type="text" name="firstName" id="firstName" value="<%=u.getUserName()%>"/></td>
<td><%=u.getFirstName()%></td>
<td><%=u.getMiddleName()%></td>
<td><%=u.getLastName()%></td>
<td><%=u.getEmail()%></td>
</tr>
<%}%>
<tbody>--%>
</table>
<br/>
</form>
</body>
</html>
please tell me what is the correct way? And also please suggest if my code is correct or any modification is needed in terms of design or is it correct practice?
Previously I used to create a LoginService object in home.jsp but that is not the right way, I need to autowire the service in jsp, or rather I think Its good if I pass data to the view layer rather than fetching it in view layer?
Java code in jsp pages is considered bad practice. Using Spring, you should create a use Controllers to interact with other components, and add the information to be displayed to the model passed to the jsp for rendering. See the Spring MVC reference documentation for detailed information.

How to send selected rows in JSP to Java controller?

I have a success.jsp page which displays multiple rows and columns with an Edit button and a checkbox for each row. If the user clicks on Edit button, the checkbox is selected.
Below is success.jsp :
<%#page import="mymvc.model.TableColumns"%>
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.Iterator"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%--
Document : success
Created on : Jul 8, 2014, 1:43:17 PM
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Success</title>
<script type="text/javascript">
function validate(n) {
v = document.getElementById("check"+n)
v.checked = !v.checked;
x = document.getElementById("typeId"+n).removeAttribute('readonly');
y = document.getElementById("paramSeq"+n).removeAttribute('readonly');
z = document.getElementById("paramName"+n).removeAttribute('readonly');
}
</script>
</head>
<body>
<form action="DBController" method="post">
Welcome ${requestScope['user'].username}.
<table>
<tr style="background-color:#f0a64e;">
<th class="border">ID</th>
<th class="border">Param Sequence</th>
<th class="border">Param Name</th>
</tr>
<c:forEach var="element" items="${requestScope['listData']}" varStatus="status">
<tr>
<td><input id="typeId${status.index}" value="${element.typeId}" readonly="true"</td>
<td><input id="paramSeq${status.index}" value="${element.paramSeq}" readonly="true"</td>
<td><input id="paramName${status.index}" value="${element.paramName}" readonly="true"</td>
<td>
<input id="edit${status.index}" type="button" value="Edit" name="edit" onclick="validate(${status.index})"</input>
</td>
<td><input type="checkbox" id="check${status.index}" name="selectedItems" value="<c:out value="${status.index}"/>"</td>
</tr>
</c:forEach>
</table>
<input type="submit" value="Update" name="update" />
</form>
</body>
</html>
I don't know how to send the whole row data to my servlet if more than one row is selected. I am able to get all the indexes of the checkboxes which are selected. But I am unable to extract other related values like typeId, paramSeq and paramName. My servlet is as follows :
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String[] edited = request.getParameterValues("selectedItems");
//String pName = request.getParameter("paramName"+edited[1]);
Enumeration<String> paramName = request.getParameterNames();
String[] param = new String[10];
int i=0;
while(paramName.hasMoreElements()){
param[i]=paramName.nextElement();
}
RequestDispatcher rd = null;
rd = request.getRequestDispatcher("/update.jsp");
request.setAttribute("param", param);
request.setAttribute("edited", edited);
rd.forward(request, response);
}
In the above code, currently, I am trying to get all the parameters passed and the rows which are selected. I want to modify this servlet and access the selected row along with other data like typeId, etc. to create UPDATE statements for every row. I referred this and this but not much help.
I think what you are missing is that you are giving each input type a unique id but you are not specifying the name of the input types, and in the servlet you are trying to get values by name.
So please add names along with the id's in order to get them in the servlet
<c:forEach var="element" items="${requestScope['listData']}" varStatus="status">
<tr>
<td><input name="typeId${status.index}" value="${element.typeId}" readonly="true"</td>
<td><input name="paramSeq${status.index}" value="${element.paramSeq}" readonly="true"</td>
<td><input name="paramName${status.index}" value="${element.paramName}" readonly="true"</td>
<td>
<input id="edit${status.index}" type="button" value="Edit" name="edit" onclick="validate(${status.index})"</input>
</td>
<td><input type="checkbox" id="check${status.index}" name="selectedItems" value="<c:out value="${status.index}"/>"</td>
</tr>
</c:forEach>
</table>

JavaBean not being remembered throughout the session

I'm currently learning JSP/Servelets. The following is code containing 2 JSP pages and a servlet, which works as follows:
JSP #1 requests user info, & passes it into a servlet.
The servlet Instantiates a JavaBean class, and passes it to the 2nd JSP, using the Session Object.
The 2nd JSP then displays the info that th user entered in the 1st JSP; the user can then hit the Return button to return to the 1st JSP.
My Question is: I've read in various Tutorials (notably Murach's JSP, which this code is based on) that if the Javabean attributes are passed to the session object rather than the request object, the JavaBean's values should be maintained throughout the session. However when I return to the first page, the JB fields are empty. Am i doing anything wrong? I would appreciate any help!
The following is the code:
1st JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Email Application</title>
</head>
<body>
<h1>Join our Email list</h1>
<p>To join our email list, enter your name and email address below.<br>
Then, click on the Submit button</p>
<form action="addToEmailList" method="post">
<jsp:useBean id="user" scope="session" class="business.User"/>
<table cellspacing="5" border="0">
<tr>
<td align="right">First name:</td>
<td>
<input type="text" name="firstName"
value = "<jsp:getProperty name="user" property="firstName"/>">
</td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><input type="text" name="lastName"
value = "<jsp:getProperty name="user" property="lastName"/>">
</td>
</tr>
<tr>
<td align="right">Email address:</td>
<td><input type="text" name="emailAddress"
value = "<jsp:getProperty name="user" property="emailAddress"/>">
</td>
</tr>
<tr>
<td>I'm interested in these types of music:</td>
<td><select name="music" multiple>
<option value="rock">Rock</option>
<option value="country">Country</option>
<option value="bluegrass">Bluegrass</option>
<option value="folkMusic">Folk Music</option>
</select>
</td>
</tr>
<tr>
<td ></td>
<td><input type="submit" name="Submit"></td>
</tr>
</table>
</form>
</body>
Servlet:
public class AddToEmailListServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
private HttpServletResponse response;
private String firstName;
private String lastName;
private String emailAddress;
private String[] musicTypes;
private Music music;
private User user;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
this.request = request;
this.response = response;
setInstanceVariables();
writeDataToFile();
forwardResponseToJSPpage();
System.err.println("Hello!");
}
private void setInstanceVariables()
{
this.firstName = getFirstName();
this.lastName = getLastName();
this.emailAddress = getEmailAddress();
this.musicTypes = request.getParameterValues("music"); //getMusic();
this.user = new User(firstName,lastName,emailAddress);
}
private String getFirstName()
{
return request.getParameter("firstName");
}
private String getLastName()
{
return request.getParameter("lastName");
}
private String getEmailAddress()
{
return request.getParameter("emailAddress");
}
private void writeDataToFile() throws IOException
{
String path = getRelativeFileName();
UserIO.add(user,path);
}
private String getRelativeFileName()
{
ServletContext sc = getServletContext();
String path = sc.getRealPath("/WEB-INF/EmailList.txt");
return path;
}
private void forwardResponseToJSPpage() throws ServletException, IOException
{
if(this.emailAddress.isEmpty()||this.firstName.isEmpty()||this.lastName.isEmpty())
{
String url = "/validation_error.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request,response);
}
else
{
music = new Music(musicTypes);
HttpSession session = this.request.getSession();
session.setAttribute("music", music);
session.setAttribute("user", user);
String url = "/display_email_entry.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request,response);
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
doPost(request,response);
}
}
2nd JSP:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# include file="/header.html" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Email Application</title>
</head>
<body>
<h1>Thanks for joining our email list</h1>
<p>Here is the information that you entered:</p>
<jsp:useBean id="user" scope="session" class="business.User"/>
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<td align="right">First name:</td>
<td><jsp:getProperty name="user" property="firstName"/></td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><jsp:getProperty name="user" property="lastName"/></td>
</tr>
<tr>
<td align="right">Email Address:</td>
<td><jsp:getProperty name="user" property="emailAddress"/></td>
</tr>
</table>
<p>We'll use the Email to otify you whenever we have new releases of the following types of music:</p>
<c:forEach items="${music.musicTypes}" var="i">
<c:out value="${i}"></c:out><br/>
</c:forEach>
<p>To enter another email address, click on the Back <br>
button in your browser or the Return button shown <br>
below.</p>
<form action="join_email_list.jsp" method="post">
<input type="submit" value="Return">
</form>
</body>
<%# include file="/footer.html" %>
</html>

forward from servlet to jsp causes form submission errors

I'm forwarding to a jsp that shows a table and a form for comments populated by jstl sql tags.
The problem is that the form works fine if I use response.sendRedirect("comments.jsp");
But since I need to retain session info between pages I want to use request.getRequestDispatcher("comments.jsp").forward(request, response);
which triggers the post form and redirects subsequent posts to the servlet url.
LoginServlet
public class LoginServlet extends HttpServlet {
Connection connection = null;
PreparedStatement ptmt = null;
ResultSet resultSet = null;
User user = null;
boolean fail = true;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String email = request.getParameter("email");
String password = request.getParameter("password");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
if (null != email && null != password) {
try {
connection = ConnectionFactory.getInstance().getConnection();
user = new User();
String queryString = "SELECT * FROM USERINFO WHERE EMAIL=?";
ptmt = connection.prepareStatement(queryString);
ptmt.setString(1, email);
resultSet = ptmt.executeQuery();
resultSet.next();
user.setEmail(resultSet.getString("EMAIL"));
...
user.setSecret3(resultSet.getString("SECRET3"));
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
}
}
if (null != user.getPassword() && user.getPassword().equals(password)) {
request.setAttribute("user",user);
request.getRequestDispatcher("comments.jsp").forward(request, response);
// response.sendRedirect("comments.jsp");
}
comments.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Comments</title>
</head>
<body>
<sql:setDataSource var="dataSource" driver="org.apache.derby.jdbc.ClientDriver"
url="jdbc:derby://localhost:1527/mp1"
user="app" password="app"/>
<sql:setDataSource var="dataSource2" driver="org.apache.derby.jdbc.ClientDriver"
url="jdbc:derby://localhost:1527/mp1"
user="app" password="app"/>
<H2>Comments</H2>
<sql:query dataSource="${dataSource}" sql="SELECT * FROM COMMENTS" var="comments" />
<table border=1>
<c:forEach var="row" items="${comments.rows}">
<tr>
<c:forEach var="col" items="${row}">
<td><c:out value="${col.value}" /></td>
</c:forEach>
</tr>
</c:forEach>
</table>
<form method="post">
<table>
<tr>
<td>Enter Email</td>
<td><input type="text" name="EMAIL"></td>
</tr>
<tr>
<td>Enter Comment</td>
<td><input type="text" name="COMMENT"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
<c:if test="${pageContext.request.method=='POST'}">
<c:catch var="exception">
<sql:update dataSource="${dataSource2}" var="updatedTable">
INSERT INTO
COMMENTS (EMAIL,COMMENT)
VALUES (?, ?)
<sql:param value="${param.EMAIL}" />
<sql:param value="${param.COMMENT}" />
</sql:update>
<c:if test="${updatedTable>=1}">
<c:redirect url="/comments.jsp"/>
</c:if>
</c:catch>
<c:if test="${exception!=null}">
<c:out value="Unable to add comment." />
</c:if>
</c:if>
</body>
</html>
BTW, this is a homework assignment were the teacher wants us learn how it was done the old way. So security and better technologies to use are not real concerns.
PS. I've solved this by separating the comments and add comment into separate pages. Perhaps a better solution would be to use the session instead of the request for object transfer.
Both redirect and forward should retain session since session is supported by cookies (in most cases).
Your form doesn't have action parameter thus its behavior depends on the browser current URL (form gets posted to current URL instead of defined in action), and current URL is different in case of redirect and forward.

Categories