data is not print on tabe - java

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>

Related

How can i get the data of the input hidden field whose name equals to a method and a string in java

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

Why can't I retrieve an attribute from the Model but I'm able to from JSP?

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}.

Spring redirect is not working when i have path parameters in method signature

The below is the code to display all employees
#RequestMapping(value = "/displayAllEmps")
public ModelAndView displayAllEmps() {
ModelAndView modelAndView = new ModelAndView("dispAllEmps");
List<Employee> employees = employeeService.fetchAllEmps();
modelAndView.addObject("employees", employees);
modelAndView.addObject("listMsg", "<br>Employees List!!!");
return modelAndView;
}
the below method is successfully redirecting me to the employee list page
#RequestMapping(value="/updateEmployee",method = RequestMethod.POST)
public String updateEmployeeUsingObject(#ModelAttribute("employee") Employee employee, Model model){
employee.setFirstName("Changes TEsting");
employeeService.updateEmployee(employee);
List<Employee> employees = employeeService.fetchAllEmps();
model.addAttribute("employees", employees);
model.addAttribute("listMsg", "<br>Employees List --- After updating Employee");
return "redirect:displayAllEmps";
}
but when I am redirecting from the below method its not working. URL is also little bit strange in the browser
#RequestMapping(value="/deleteEmployee/{empId}")
public String deleteEmployee(#PathVariable("empId") int empId,Model model){
boolean result = employeeService.deleteEmployee(empId);
List<Employee> employees = employeeService.fetchAllEmps();
model.addAttribute("employees", employees);
model.addAttribute("listMsg", "<br>Employees List --- After Deleting Employee");
return "redirect:displayAllEmps";
}
URL: http://localhost:9876/SpringAnnotationDemo_Tomcat/deleteEmployee/displayAllEmps?listMsg=%3Cbr%3EEmployees+List+---+After+Deleting+Employee
The below is my jsp code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jstl/core_rt" 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>
Welcome!!! ${myMap.DisMsg } ${listMsg}
Context Path: <c:out value="${pageContext.request.contextPath}"/>
<br/>
requestURI: <c:out value="${pageContext.request.requestURI}"/>
<br/>
servletPaht: <c:out value="${pageContext.request.servletPath}"/>
<%-- Context Path: <c:out value="${pageContext.request.contextPath}"/>
Context Path: <c:out value="${pageContext.request.contextPath}"/>
--%>
<br>---------------------------------------
<br>
<table border="1">
<tr>
<!-- td>ID</td> -->
<td>First Name</td>
<td>Last Name</td>
<td>Telephone</td>
<td>Email</td>
<td></td>
<td></td>
</tr>
<c:forEach var="emp" items="${employees}">
<tr>
<!-- td>${emp.id}</td> -->
<td>${emp.firstName}</td>
<td>${emp.lastName}</td>
<td>${emp.telephone}</td>
<td>${emp.email}</td>
<td>Update</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
</body>
</html>
In the above code i have doubt that when i am redirecting from my controller method. why "deleteEmployee" is still there in the URL?
I think the URL should be like below.
http://localhost:9876/SpringAnnotationDemo_Tomcat/displayAllEmps?listMsg=%3Cbr%3EEmployees+List+---+After+Deleting+Employee
Please let me know what is the best practice to edit an existing record in the DB using spring MVC.

request.getAttribute is null when I call it in jsp

It calls Servlet by click a href.
<li >privilegeManagement</li>
this code is include in the navigation.jsp which is included in the main.jsp.
then it's my servlet.
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
ProviderDao pd = new ProviderDao();
List<ProviderArchives> list = pd.getArchives();
String str = "chenfeng";
req.setAttribute("list", list);
req.setAttribute("hu" , str);
getServletContext().getRequestDispatcher("/jsp/main.jsp").forward(req,resp);
}
then it's my main.jsp.
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#page import="java.util.*"%>
<%#page import="com.chenfeng.javabean.ProviderArchives"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>main</title>
</head>
<body>
<%# include file="navigation.jsp"%>
<div>
<%# include file="management.jsp"%>
</div>
<div>
<%
String k = (String)request.getAttribute("hu");
out.println(k);
%>
<c:forEach items="${list}" var="item">
<tr>
<td>${item.provideID() }</td>
<td>${item.GID }</td>
<td>${item.Gname }</td>
<td>${item.PID }</td>
<td>${item.TEL }</td>
<td>${item.ADDR }</td>
<td>
Modify
Delete
</td>
</tr>
</c:forEach>
</div>
</body>
</html>
then when I run this on server,it shows like this
thank in advance for any help!
Actually,there is no reason for this code.But the eclipse run into problem.The real problem log output after I delete class file in build directory and build it again.
It's quite clear. You set attribute of Request Object while you're forwarding Servlet Context Object.
Instead of:
getServletContext().getRequestDispatcher("/jsp/main.jsp").forward(req,resp);
Write:
req.getRequestDispatcher("/jsp/main.jsp").forward(req,resp);

HashMap display in JSP from Controller Springs

I am newbie to Springs and currently stuck at displaying HashMap Value to JSP page . All I need is to do is specify the key of hashmap to get the corresponding My page is a listing page. Here is My Controller Code that returns data succesfull
#Controller
public class GetUserController {
#Autowired
private AddUserServiceImpl aus;
#RequestMapping(value="/getUser.do",method=RequestMethod.GET)
public ModelAndView getUser()
{
HashMap<String,String> listMap = new HashMap<String,String>();
List<User> u = (List<User>) aus.getUser();
System.out.println("List Size "+u.size());
for(User ux : u)
{
listMap.put("userId", String.valueOf(ux.getUser_id()));
listMap.put("userName", String.valueOf(ux.getUserName()));
listMap.put("firstName", String.valueOf(ux.getFirstName()));
listMap.put("lastName", String.valueOf(ux.getLastName()));
listMap.put("email", String.valueOf(ux.getEmail()));
}
return new ModelAndView("listingView","listMapView",listMap);
}
}
MY JSP is as Follows
<%# 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 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 align="center" style="padding-top: 30px; border: 0.5px;">
<tr>
<th bgcolor="#2E64FE">USERNAME</th>
<td> </td>
<th bgcolor="#2E64FE">FIRSTNAME</th>
<td> </td>
<th bgcolor="#2E64FE">LASTNAME</th>
<td> </td>
<th bgcolor="#2E64FE">EMAIL</th>
<td> </td>
</tr>
<c:forEach var="listMapview" items="${listMapView.listMap}" varStatus="status">
<tr>
<td>${listMapview.key}</td>
<td>${listMapview.key.userName}</td>
<td>${listMapview.key.firstName}</td>
<td>${listMapview.key.lastName}</td>
<td>${listMapview.key.email}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
Controller calls the JSP succesfully returning the data
For jsp code,
<c:forEach items="${listMap}" var="mapItem">
${mapItem.key} ${mapItem.value}
</c:forEach>
In your case, if you durectly want to get value using specific key
<c:forEach items="${listMap}" var="mapEntry">
${mapEntry['userId']}
</c:forEach>
Try like this
<c:forEach items="${listMapView.listMap}" var="listMapview" varStatus="status">
<tr>
<td>${listMapview.key}</td>
<td>${listMapview.value}</td>
</tr>
</c:forEach>
Don't forget to include this
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

Categories