Pass data to JSP page using spring - java

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.

Related

Why cannot I display user List?

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"%>

Update password from database using JavaServlet

Hello, im working on a project in the university, and im stuck on an error.
Im working on a mypage feature, where you can update your old password, when you are looged in. The problem is that ChangepasswordServlet is not doing what it is supposed to do.
Here you can see my servlet, the problem is probably somewhere in the IF sentence. (Manager=Entitymanager)
#WebServlet(name = "ChangePasswordServlet", urlPatterns = {"/ChangePassword"})
public class ChangePasswordServlet extends HttpServlet {
#EJB
UserManagerLocal manager;
private void changePassword(HttpServletRequest request, HttpServletResponse response) throws IOException {
String loggedInUsersUsername = request.getRemoteUser();
/* PrintWriter writer = response.getWriter(); */
User userFromTheDB = manager.getUser(loggedInUsersUsername);
String oldPasswordFromDB = userFromTheDB.getPassword();
String oldPasswordFromForm = (String) request.getAttribute("theOldPW");
;
String newPasswordFromForm = (String) request.getAttribute("theNewPW");
String newPasswordToCheckFromForm = (String) request.getAttribute("theNewPWCheck");
try {
if (oldPasswordFromDB.toLowerCase().equals(oldPasswordFromForm.toLowerCase()) && newPasswordFromForm.toLowerCase().equals(newPasswordToCheckFromForm.toLowerCase())) {
userFromTheDB.setPassword(newPasswordFromForm);
manager.updateUser(userFromTheDB);
response.sendRedirect("/Slit/MyPage/PasswordSucsess.jsp");
} else {
response.sendRedirect("Slit/Error/error.jsp");
}
}
catch (NullPointerException en) {
PrintWriter print = response.getWriter();
print.println("nullpointeryes");
print.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
changePassword(request, response);
}
#Override
protected void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
changePassword(request, response);
}
so
Here is my JSP with the form
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<head>
<title>Her kan du endre ditt nåværende passord</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css"
href="/Slit/Templates/CSS/MainPageTemplate.css">
</head>
<body>
<title>Slit</title>
<div>
<div class="form">
<form method="post" action="/Slit/ChangePassword">
<input type="Password" name="theOldPW" placeholder="Gammelt
Password"/>
<input type="Password" name ="theNewPW" placeholder="Nytt
Password"/>
<input type="Password" name ="theNewPWCheck" placeholder=" Nytt
Password på nytt"/>
<input type="submit" name="ByttePassord" value="Trykk her for å bytte
passord!"/>
</form>
</div>
</div>
</body>
</html>
</head>
<body>
</body>
So im getting nullpointer after i have filled in the form with the old and the new password.
If im running the code now, im getting the "nullpointeryes" error.
Edit:
This is the console error after filling in the form:
12:39:37,194 INFO [stdout] (default task-12) Hibernate: select
user0_.username as username2_3_0_, user0_.fName as fName3_3_0_, user0_.lName
as lName4_3_0_, user0_.password as password5_3_0_, user0_.DTYPE as
DTYPE1_3_0_ from User user0_ where user0_.username=?
Thanks for any answers
After hours i figured that i used get.attribute instead of parameter :/
String newPasswordFromForm = (String) request.getParameter("theNewPW");
String newPasswordToCheckFromForm = (String)
request.Paramter("theNewPWCheck");

Multiple servlet communication

I have a simple servlet 'Login' deployed in Server A tomcat
Index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Login</h1>
<form method="post" action="Validate">
User: <input type="text" name="user" /><br/>
Password: <input type="text" name="pass" ><br/>
<input type="submit" value="submit">
</form>
</body>
Validate.java
doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("1234"))
{
//creating a session
HttpSession session = request.getSession();
session.setAttribute("user", name);
response.sendRedirect("Welcome");
}
else
{
PrintWriter out = response.getWriter();
out.println("Wrong password!!!");
}
}
Welcome.Java
doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String user = (String)session.getAttribute("user");
out.println("Welcome"+user);
}
This set up works fine.
Now what I want to try is to create another Servlet 'Validate' which would be deployed in another Server B tomcat with a different IP. I need to pass the parameters from Servlet 'Login' to Servlet 'Validate' which will then validate the credentials and send back the validation message, a String, to the Servlet 'Login' which will then display the same on its index.jsp page.
Please provide some help on this. Let me also add that I have no prior experience in servlets.

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