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.
Related
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}.
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");
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.
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"%>