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"%>
Related
I made a form submit application via Spring MVC. After submitting the form, all values of input fields are visible in url.
let's suppose that after submitting the generated URL is this:
SpringTuto/successA?name=FirstUser&designation=Student&country=XYZ&dob=2018%2F01%2F16&skills=paragliding&address.street_name=avenue+Road&address.city=New+City&address.district=New+District&address.pin_code=322343
From the above url, I want to encode name, designation, country and all other parameters in some encrypted code.
After reading a few articles, i came to an understanding that I will use the URIeditor(org.springframework.beans.propertyeditors.URIEditor) to encode. But I don't know how to use it. If anyone has another way to do this please share it.
Thanks in advance.
Here is my Controller Class.
#Controller
public class SpgController {
#ModelAttribute("header")
public Model addHeader(Model view) {
int a = 10;
return view.addAttribute(a);
}
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/mm/dd");
binder.registerCustomEditor(Date.class, "dob", new CustomDateEditor(dateFormat, false));
binder.registerCustomEditor(String.class, "name" , new NamepropertyEditor());
}
#RequestMapping("/main")
public ModelAndView go() {
ModelAndView view = new ModelAndView("main");
return view;
}
#RequestMapping(value = "/successA", method = RequestMethod.GET)
public ModelAndView method(#Valid #ModelAttribute("bean") Bean bean, BindingResult result ) {
if (result.hasErrors()) {
ModelAndView view = new ModelAndView("main");
return view;
}
ModelAndView view = new ModelAndView("successAnother");
return view;
}
}
Here is the successAnother.jsp page
<%# 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>
</head>
<body>
<form >
Name: ${bean.name}<br/>
Designation: ${bean.designation}<br/>
DoB: ${bean.dob}<br/>
Skills: ${bean.skills}<br/>
Street: ${bean.address.street_name}<br/>
City: ${bean.address.city}<br/>
District: ${bean.address.district}<br/>
PinCode: ${bean.address.pin_code}<br/>
Country: ${bean.country}<br/>
</form>
</body>
</html>
Here is main.jsp(Application form)
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://www.springframework.org/tags" prefix = "spring" %>
<!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>Spring</title>
</head>
<body>
English|French|Hindi
<h3>${msg}</h3>
<form:errors path = "bean.*"/>
<form action="successA" method="get">
<table>
<tr>
<td><spring:message code = "label.userName"/><input type="text" name="name">
</td>
</tr>
<tr>
<td><spring:message code = "label.userDesignation"/><input type="text" name="designation">
</td>
</tr>
<tr>
<td><spring:message code = "label.userCountry"/><input type="text" name="country">
</td>
</tr>
<tr>
<td>
<spring:message code = "label.userDoB"/><input type= "text" name = "dob" >
</td>
</tr>
<tr>
<td>
<spring:message code = "label.Skils"/><select name = "skills" multiple >
<option value= "driving">Driving</option>
<option value = "diving">Diving</option>
<option value = "swimming">Swimming</option>
<option value = "paragliding">Paragliding</option>
</select>
</td>
</tr>
<tr>
<td>
<h5><spring:message code = "label.userAddress"/></h5>
<spring:message code = "label.userStreetname"/><input type = "text" name = "address.street_name">
<spring:message code = "label.userCity"/> <input type = "text" name = "address.city">
<spring:message code = "label.userDistrict"/><input type = "text" name = "address.district">
<spring:message code = "label.userPin"/><input type = "text" name = "address.pin_code">
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td><input type="submit" value=<spring:message code = "label.userSubmit"/>></td>
</tr>
</table>
</form>
</body>
</html>
If your application supports HTTPS, then it can be achieved easily using spring security by doing some configuration as follows.
<http>
<intercept-url pattern="/**" access="ROLE_USER" requires-channel="https"/>
...
</http>
Integrating spring security with spring mvc is very simple.
I have an application where in a JSP page i am displaying a drop down list but i am getting an exception in my code.
public class ExpenseCreationBean {
private String color;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
Controller Class:-
#RequestMapping(value = "/addDetails", method = RequestMethod.GET)
public String getExpenseEntryPage(Model model) {
ExpenseCreationBean expenseCreationBean = new ExpenseCreationBean();
model.addAttribute("expenseCreationBean", expenseCreationBean);
List<String> coloursList = new ArrayList<String>();
coloursList.add("red");
coloursList.add("green");
coloursList.add("yellow");
coloursList.add("pink");
coloursList.add("blue");
model.addAttribute("colours", coloursList);
System.out.println("I was here!!");
return "addDetails";
}
addDetails.jsp Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<html>
<head>
<title>Add Details</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function() {
$("#datepicker").datepicker({
showOn : "button",
buttonImage : "images/calendar.png",
buttonImageOnly : true,
buttonText : "Select date"
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<h1>Expense Entry Details</h1>
<form:form method="post" action="savedata" modelAttribute="expenseCreationBean">
<table border="6px" cellspacing="10px" cellpadding="10px">
<tr>
<td>Date Of Purchase: <input type="text" id="datepicker"
name="date_of_purchase"></td>
<td>Item Name:<input type="text" name="description"></td>
<td>Please select:</td>
<td><form:select path="color">
<form:option value="" label="...." />
<form:options items="${colours}" />
</form:select>
</td>
<td>Paid By: <select name="paid_by"></td>
<td>Amount Paid:<input type="text" name="total_price"
id="total_price"></td>
<td>Quantity:<input type="text" name="quantity_purchased"></td>
<td>Unit:<input type="text" name="unit"></td>
</tr>
<tr>
<tr>
<tr>
<tr>
<td>Exclude:</td>
<td><input TYPE="checkbox" name="exclude">
</tr>
<tr>
<td>Comments:<textarea rows="3" cols="25" name="comments"></textarea>
</td>
</tr>
<tr>
<td><input type="submit" value="Save" align="middle"></td>
</table>
</form:form>
</body>
</html>
I am getting the below exception :-
javax.servlet.jsp.JspException: Type [java.lang.String] is not valid for option items
org.springframework.web.servlet.tags.form.OptionWriter.writeOptions(OptionWriter.java:143)
org.springframework.web.servlet.tags.form.OptionsTag.writeTagContent(OptionsTag.java:157)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
It is just a Spring MVC Web application where i am trying to display the drow down list pre-populated with the colors data.
Any help is highly appreciated.
I added the below line on teh top of addDetails.jsp file and it worked:-
Try to add into Map, instead of ArrayList.
Map<String,String> coloursList = new HashMap<String,String>();
coloursList.put("R","red");
coloursList.put("R","green");
coloursList.put("Y","yellow");
coloursList.put("P","pink");
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>
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.
I am getting an error that says:
/WEB-INF/jsps/createoffer.jsp (line: 29, column: 67) quote symbol expected
from what I read in the java spring documentations the below is correct. The app runs until I select the link to the form on the index.jsp page.
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<!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">
<link href="${pageContext.request.contextPath}/static/css/main.css"
rel="stylesheet" type="text/css" />
<title>My form</title>
</head>
<body>
<sf:form method="post"
action="${pageContext.request.contextPath}/docreate" commandName="offer">
<table class="formtable">
<tr>
<td class="label">Name:</td>
<td><sf:input class="control" path="name" name="name" type="text" /></td>
</tr>
<tr>
<td class="label">email:</td>
<td><sf:input class="control" path="email" name="email" type="text" /></td>
</tr>
<tr>
<td class="label">your offer:</td>
<td><sf:textarea class="control" path="text" name="text" rows=10 cols=10 /></td>
</tr>
<tr>
<td></td>
<td><input name="Create Offer" type="submit" /></td>
</tr>
</table>
</sf:form>
</body>
</html>
from OffersController.java
#RequestMapping("/createoffer")
public String createOffer(Model model) {
model.addAttribute("offer", new Offer());
/*List<Offer> offers = offersService.getCurrent();
model.addAttribute("offers", offers);
*/
return "createoffer";
}
Offer Bean
#Component
public class Offer {
private int id;
#Size(min = 5, max = 25, message = "Name is not vaild")
private String name;
#NotNull
#Email(message = "Is not a vaild email address")
private String email;
private String text;
public Offer() {
}
I don't have enough points to add comment. Can you double check that row=10 is same with row="10" in that jsp file? The error message seems like a syntax problem in the jsp.