I want to add another user in registration JSP file to my HashMap which is created in my homepage, but it seems the another HashMap is being created when I'm trying to register user.
How to access the HashMap from homepage JSP file in another?
This is my base class:
package com.jakub.spring;
import java.util.HashMap;
public class registeredUsers {
public HashMap<String, String> userSource;
public registeredUsers() {
userSource=new HashMap<String, String>();
}
public void register(String name, String password) {
userSource.put(name, password);
}
public String userExists(String user) {
String passwordFromSource = userSource.get(user);
if(passwordFromSource != null) {
return passwordFromSource;
}else
return "";
}
}
This is my homepage:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="true" %>
<html>
<head>
<title>Home</title>
</head>
<body bgcolor="#CCCFFF">
<form method="post" action="validate.jsp">
<p align="left">Podaj login:</p>
<input type="text" name="name" />
<p align="left">Podaj haslo:</p>
<input type="text" name="password" />
<input type="submit" value="Zaloguj" />
</form>
Rejestracja
<jsp:useBean id="registeredUsers"
class="com.jakub.spring.registeredUsers" scope="application"></jsp:useBean>
<%
out.println("Dostepni uzytkownicy w systemie: \n");
out.print(registeredUsers.userSource.keySet());
%>
</body>
</html>
This is my registration page:
<%# page language="java" contentType="text/html; charset=ISO-8859-2"
pageEncoding="ISO-8859-2"%>
<!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-2">
<title>Konto utworzone</title>
</head>
<body>
<jsp:useBean id="registeredUsers"
class="com.jakub.spring.registeredUsers" scope="application"></jsp:useBean>
<%
registeredUsers.register(request.getParameter("name"),request.getParameter("password"));
out.print("Konto zostało utworzone");
out.print(registeredUsers.userSource.keySet());
%>
Powrót do strony glownej
</body>
</html>
Use ConcurrentHashMap instead of HashMap because it's in Application scope and that can be accessed simultaneously by multiple threads at a time and it results in ConcurrentModificationException.
Please have a look at Thread Safe JSP-Servlet Q&A
Related
This question already has an answer here:
Servlet send response to JSP
(1 answer)
Closed 3 years ago.
how do i set the jsp file as response in my servlet ?And what kind of expression do i need to use in the jsp page?
this is the form
<html>
<head>
<title>Select your Hobby</title>
</head>
<body>
<form method="POST" action="SelectHobby">
<p> Choose a Hobby:
</p>
<select name="hobby" size="1">
<option>horse skiing
<option>extreme knitting
<option>alpine scuba
<option>speed dating
</select>
<br><br>
<center>
<input type="SUBMIT">
</center>
</form>
</body>
</html>
the servlet
package com.example.web;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HobbyServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
String hobby = request.getParameter("hobby");
}
}
and this is the jsp in wich i want to see the hobby in the body
<html>
<head>
<title>These are your hobbies</title>
</head>
<body>
<%
</body>
</html>
I recomend you to read this post. JSTL will help you. I suppose you mapped your servlet. Here is a quick example:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<form method="POST" action="testservlet">
<p> Choose a Hobby:
</p>
<select name="hobby" size="1">
<option>horse skiing
<option>extreme knitting
<option>alpine scuba
<option>speed dating
</select>
<br><br>
<center>
<input type="SUBMIT">
</center>
</form>
</body>
</html>
The servlet:
#WebServlet(name = "test", urlPatterns = { "/testservlet" })
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String hobby = request.getParameter("hobby");
request.setAttribute("theHobby", hobby);
request.getRequestDispatcher("hobbypage.jsp").forward(request, response);
}
I defined an attribute called theHobby to hold the value from the selected hobby in the first page. I also created a page called hobbypage.jsp where I want to send the value to.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Hobby: ${theHobby}
</body>
</html>
With JSTL you can call the attribute through the name you defined like this ${nameOfAttribute}.
Here is a sample jsp page with a form.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="h.abc" %>
<%
abc p = new abc();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="abcd.jsp" method="POST">
<input type="hidden" name="<%=p.getName()%>+'Name'" value='y'>
<input type='text' name='<%=p.getName()%>' >
<input type='submit' value='submit'>
</form>
</body>
</html>
Here is the abc class in the 'h' package.Please pardon the naming.It's only for illustration purposes.
public class abc {
public String name="abc";
public abc()
{
}
public String getName()
{
return name;
}
}
And this is the abcd.jsp target page.Here i am trying to get the value of the input field.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="h.abc" %>
<%
abc p = new abc();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String s = p.getName();
out.println(request.getParameter(s+"Name"));
out.println(request.getParameter(s));
%>
</body>
</html>
I am unable comprehend why the input field is not returning 'y' as its value.rather it is returning null.
change the code in first jsp
<input type="hidden" name="<%=p.getName()%>Name" value='y'>
you need put your abc instance in HttpServletRequest'attributes by calling setAttribute("you_key", abcInstance) method. And then you can get abc instance in your jsp pages by calling req.getAttribute("your_key") or using el expression
I'm learning spring mvc and understand the use of the Model and ModelAttribute. However, I can't retrieve the Model's attribute so I resorted to using the JSP param value. What am I doing wrong? I checked the model still had a value for the attribute using #ModelAttribute("username") User user / user.username and sure enough it does.
Controller
package login.user;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class LoginUser {
#RequestMapping("/")
public String showMenu()
{
return "menu";
}
#RequestMapping("login")
public String loginUser(Model model)
{
User newUser = new User();
model.addAttribute("user", newUser);
return "login-user";
}
#RequestMapping("processUser")
public String processUser(Model model)
{
Option newOption = new Option();
model.addAttribute("option", newOption);
return "process-login";
}
}
User
package login.user;
public class User {
private String username;
private char password[];
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public char[] getPassword() {
return password;
}
public void setPassword(char[] password) {
this.password = password;
}
}
login-user.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<link href="<c:url value="/resources/css/style.css" />" rel="stylesheet" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login User</title>
</head>
<body>
<div>
<form:form action="processUser" modelAttribute="user">
<table>
<tr>
<td>Username:</td>
<td>
<form:input path="username" />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<form:input type="password" path="password" />
</td>
</tr>
<tr>
<td>
<input type="submit" name="Login" />
</td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
process-login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form modelAttribute="option">
<h3>Welcome ${param.username}. Please choose an activity below</h3> <---- changed from ${user.username}
<div>
<form:select path="option">
<form:option value="Email" label="Email"></form:option>
<form:option value="Enter Recipe" label="Enter Recipe"></form:option>
<form:option value="Retrieve Recipe" label="Retrieve Recipe"></form:option>
</form:select>
</div>
</form:form>
</body>
</html>
Just change your last #RequestMapping method as follows:
#RequestMapping("processUser")
public String processUser(#ModelAttribute("user") User user, Model model)
{
Option newOption = new Option();
model.addAttribute("user", user);
model.addAttribute("option", newOption);
return "process-login";
}
Now use ${user.username} in jsp.
The spring model data is stored in the standard Java request scope. If you are trying to get the username, you need to add it in the request scope again. So, you can write the processUser method as follows.
#RequestMapping("processUser")
public String processUser(#ModelAttribute("user") User user,Model model)
{
Option newOption = new Option();
// do stuff with user data
newOption.setUsername(user.getUsername());
model.addAttribute("option", newOption);
return "process-login";
}
So, you should be able to get it in the jsp as ${option.username}.
Data is not printed in the table
Bean class name is address and user_id_fk is retrieved from user_id with the help of session
#RequestMapping("/address")
public ModelAndView address(HttpServletRequest request , HttpServletResponse response ,ModelAndView modelAndView){
HttpSession session=request.getSession();
String user_id_fk = (String)session.getAttribute("user_id");
UMService a = new UMserviceimp();
address ad=new address();
ad.setUser_id_fk(Integer.parseInt(user_id_fk));
ad=a.addr(ad);
modelAndView.addObject("studentbean",ad);
modelAndView.setViewName("address");
return modelAndView;
}
When we use this then the data is printed to the console:
System.out.println("address" +ad.getUser_id_fk());
System.out.println("line_1"+ad.getLine_1());
System.out.println("line_2"+ad.getLine_2());
System.out.println("line_3"+ad.getLine_3());
System.out.println("city"+ad.getCity());
System.out.println("state"+ad.getState());
System.out.println("pincode"+ad.getPin_code());
System.out.println("country"+ad.getCountry());
System.out.println("address_type"+ad.getAddress_type());
<!--address.jsp-->
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding``="ISO-8859-1"%>
<%#page import="com.cms.org.um.bean.address"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>
<table border="1" align="left">
<tr>
<th>line_1</th>
<th>line_2</th>
<th>line_3</th>
<th>city</th>
<th>state</th>
<th>country</th>
<th>pin_code</th>
<th>address_type</th>
</tr>
<c:forEach items="${studentbean}" var="u">
<tr>
<td>${u.line_1}</td>
<td>${u.line_2}</td>
<td>${u.line_3}</td>
<td>${u.city}</td>
<td>${u.state}</td>
<td>${u.country}</td>
<td>${u.pin_code}</td>
<td>${u.address_type}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
<!-- end snippet -->
To get field value from object "u" you must do something like this:
<c:forEach items="${studentbean}" var="u">
<tr>
<td><%${u.line_1}%></td>
<td><%${u.line_2}%></td>
<td><%${u.line_3}%></td>
<td><%${u.city}%></td>
<td><%${u.state}%></td>
<td><%${u.country}%></td>
<td><%${u.pin_code}%></td>
<td><%${u.address_type}%></td>
</tr>
</c:forEach>
I'm trying to make a list of members of type Party, and linking their memberID to an update page which automatically gets the memberID of the one which was clicked.
I've already written code in the servlet to display a view of all of the members, with each of their IDs linked to a page called UpdateParty.jsp however what I want is for the ID clicked to be passed on with the request so that it can be used in the UpdateParty.jsp as a parameter so that the user does not have to enter it.
I'm using postgres for my SQL if anyone wants to know.
Servlet code which produces a list of all party members:
else if (request.getParameter("listallmembers") != null) {
try {
User sessionuser = (User) session.getAttribute("User");
String u = sessionuser.getUsername();
ArrayList<Party> p = new ArrayList<Party>();
ResultSet rs = this.findAllMembers(u);
while (rs.next()) {
Party party = new Party();
party.setMemberID(rs.getString("memberID"));
party.setPartyFirstname(rs.getString("partyFirstname"));
party.setPartySurname(rs.getString("partySurname"));
party.setUsername(rs.getString("username"));
p.add(party);
}
request.setAttribute("members", p);
request.getRequestDispatcher("ViewPartyMembers.jsp").forward(request, response);
} catch (Exception e) {
out.print(e);
e.printStackTrace(out);
}
Code for ViewPartyMembers.jsp:
<%#page import="HolidayExchange.Party"%>
<%#page import="HolidayExchange.User"%>
<%#page import="java.util.List"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Party Members</title>
</head>
<body>
<h1>View Party Members</h1>
<%
List<Party> l = (List<Party>) request.getAttribute("members");
if(l!=null){
out.println("<table>");
out.println("<tr><th>Member ID</th><th>Firstname</th><th>Second Name</th><th>Associated User</th></tr>");
for(int i = 0; i < l.size();i++){
out.println("<tr><td>"+ l.get(i).getMemberID() +
"</td><td><a href='UpdateParty.jsp'>"+ l.get(i).getPartyFirstname() +
"</a></td><td>"+ l.get(i).getPartySurname() +
"</td><td>" + l.get(i).getUsername() + "</td>");
out.println("</tr>");
}
out.println("</table>");
}else{
%>
<form action="PartyServlet" method="get">
<input type="hidden" name="listallmembers" value="1" /><br />
<input type="submit" value="Show all Members" />
</form>
<%
}
%>
</body>
</html>
Here's something a little more sane for you. It uses the JSTL Expression Language and tag library.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Party Members</title>
</head>
<body>
<h1>View Party Members</h1>
<c:if test="${!empty members}">
<table>
<tr><th>Member ID</th><th>Firstname</th><th>Second Name</th><th>Associated User</th></tr>
<c:forEach items="${members}" var="member">
<tr><td>${member.memberID}</td>
<c:url value="link" value="UpdateParty.jsp">
<c:param name="memberId" value="${member.memberID}"/>
</c:url>
<td>${member.partyFirstname}</td>
<td>${member.partySurname}</td>
<td>${member.username}</td>
</tr>
</c:forEach>
</table>
</c:if>
<c:if test="${empty members}">
<form action="PartyServlet" method="get">
<input type="hidden" name="listallmembers" value="1" /><br />
<input type="submit" value="Show all Members" />
</form>
</c:if>
</body>
</html>
If you want the ID to be available on the UpdateParty.jsp your link should look like:
<a href='UpdateParty.jsp?id=" + l.get(i).getMemberID() + "'>"+ l.get(i).getPartyFirstname()"</a>
So the id property will be available in the JSP as a request parameter.
Anyway, I recommend you not use scriptlet in your JSP and instead point directly to a JSP point to a Controler/Action