I am new to spring framework. Currently, I am doing spring validations using annotations.
So look at my DAO Class:
public class Spitter {
private Long id;
#NotNull(message = "Username cannot be null")
#Size(min = 10, max = 14, message = "Username must be between 10 and 14 characters long")
private String username;
SETTERS AND GETTERS }
This is my controller:
#Controller
#RequestMapping("/spitters")
public class SpitterController {
#RequestMapping(value = "/edit", method=RequestMethod.GET)
public String createSpitterProfile(Model model) {
model.addAttribute("spitter", new Spitter());
return "spitters/edit";
}
#RequestMapping(value = "/edit/createAccount", method = RequestMethod.POST)
public String addSpitterFromForm(Model model, #Valid #ModelAttribute("spitter")Spitter spitter, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "spitters/edit";
} else {
// spitterService.addSpitter(spitter);
return "redirect:/home";
}
}
}
And JSP file:
<%--suppress XmlDuplicatedId --%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="s" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Spitter</title>
</head>
<body>
<h2>Create free Spitter account</h2>
<sf:form action="/spitters/edit/createAccount"
method="post" commandName="spitter">
<table class="formtable">
<tr>
<td class="label">User Name</td>
<td><sf:input class="control" name="username" path="username"
type="text"></sf:input></br>
<sf:errors path="username"></sf:errors></td>
</tr>
<td class="label"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</sf:form>
</body>
</html>
However, Spitter Controller can receive data from jsp form. But constraints(#NotNull and #Size) added in DAO Class don't work and I don't know why.
Please be more spceific about the non-working constraints. An example
would help
Maybe your bean data is valid and username is just empty string. I think you use Hibernate Validator, if so try to add #NotEmpty constraint to username field
I believe you need to register bean MethodValidationPostProcessor. See Spring Docs
Related
This way is not greatest. I'm looking for a better way. Is it possible to do without Lists?
My PageController:
public class CreateUserPageController {
#Autowired
private UserServiceImpl userServiceImpl;
#RequestMapping(value = "/create-user", method = RequestMethod.GET)
public ModelAndView showForm() {
ModelAndView model = new ModelAndView("admin/create-user");
model.addObject("user", new User());
UserRoleDTO[] roles = UserRoleDTO.values();
List<String> roleNames = new ArrayList<>();
for (UserRoleDTO role : roles) {
roleNames.add(role.getName());
}
model.addObject("roleNames", roleNames);
return model;
}
#RequestMapping(value = "/create-user", method = RequestMethod.POST)
public ModelAndView submitForm(#ModelAttribute("user") User user) {
userServiceImpl.create(user);
return showForm();
}
}
My JSP:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>Create test</title>
</head>
<body>
<h1>Create Test</h1>
<form:form method="POST" action="/create-test" modelAttribute="topicTestDTO">
<form:input path="topic.name" type="text" list="topic_list" placeholder="choose or create topic"/>
<datalist id="topic_list">
<c:forEach items="${topicList}" var="topic">
<option>${topic}</option>
</c:forEach>
</datalist>
<br>
<form:input path="test.name" type="text" placeholder="create test name"/>
<input type="submit">
</form:form>
</body>
</html>
Thanks for help.
If you need more information, tell me which one and I'll complete the code.
Here the problem is for every request it goes to Database to retrieve the data, even data is not changing also it reduces the performance of application.
By using local cache we can achieve performance, so while application loading it self data will be queried from database and store it in cache,then we can reuse the data from cache.
My controller. When I open the browser, the start page starts.jsp and create model User, which haves one field(String name) and set,get method. In start.jsp haves field of text and submit "LOGIN".
#Controller
public class HomeController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView start() {
return new ModelAndView("start", "user", new User());
}
#RequestMapping(value = "/input", method = RequestMethod.POST)
public ModelAndView input(#ModelAttribute("user") User user) {
return new ModelAndView("input", "userName", user);
}
}
My start page. Have text field and submit.
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>start</title>
</head>
<body>
<h1>TEST</h1>
<form:form method="post" commandName="user" action="input">
<input type="text" name="name"><br>
<input type="submit" value="LOGIN">
</form:form>
</body>
</html>
My problem: I open localhost:8080/webapp and input name. In the moment there is creating examplar of model User. I push "LOGIN" and I turn in localhost:8080/input, where "input.jsp" is two page, which output "Hello world, {name}". But if I replace action="input" in start.jsp with action="webapp\input" then everything is good. But I think it's bad idea.
I don't see any issues with your code. I tried to set this example and works fine for below configuration.
webapp-servlet.xml:
<context:component-scan base-package = "com.test" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
JSP locations :
\WEB-INF\jsp\input.jsp
\WEB-INF\jsp\start.jsp
sample input.jsp:
<%# page import="com.test.*" %>
<html>
<head>
<title>start</title>
</head>
<body>
<h1>TEST</h1>
<%
User user = (User)request.getAttribute("userName");
%>
Hello - <%=user.getName() %>
</body>
</html>
No changes required in start.jsp and HomeController
I am trying to map productId to URL in my jsp page, but the value is wrong.
The URL is returning TÃtulo 1 but the response is returning the right value:
HTML Mapping
My jsp code:
<%# 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 uri="http://www.springframework.org/tags" prefix="spring"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>Insert title here</title>
</head>
<body>
<div>
${success}
</div>
<table>
<tr>
<td>Id</td>
<td>Titulo</td>
<td>Valores</td>
</tr>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.id}</td>
<td>${product.title}</td>
<td>
<c:forEach items="${product.prices}" var="price">
[${price.value} - ${price.bookType}]
</c:forEach>
</td>
</tr>
</c:forEach>
</table>
My Java Controller Code:
#RequestMapping(method=RequestMethod.GET)
public ModelAndView list() {
ModelAndView modelAndView = new ModelAndView("products/list");
modelAndView.addObject("products", productDAO.list());
return modelAndView;
}
My Java DAO Code:
public List<Product> list() {
return manager.createQuery("select distinct(p) from Product p join fetch p.prices", Product.class).getResultList();
}
Unfortunately I cannot see your method 'show'.
I guess you have a misprint in the path:
#RequestMapping("/show{/id}")
//--------------------^^ WRONG
public String show(#PathVariable("id") long id) {
...
}
instead
#RequestMapping("/show/{id}")
//--------------------^^ RIGHT
I am getting values from DAO its stored in varaible editVal and page return to edit.jsp now how to get varaible editVal values in edit.jsp page..
Controller page:
#RequestMapping(value="edit", method=RequestMethod.GET)//String
public ModelAndView callgetSuccess(#ModelAttribute("id")String Id, BindingResult result, ModelMap model) {
ModelAndView shop=new ModelAndView();
shopModel shModel=new shopModel();
if(result.hasErrors()){
System.out.println("error");
return new ModelAndView("edit","shopModel",editVal);//"edit"
}else{
shModel = shopService1.editshop(Id);
model.addAttribute("shopModel",shModel);
shop.addObject("shopModel", shModel);
return new ModelAndView("edit","shopModel",shModel);
}
edit.jsp
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<html>
<body>
<h2>Hello World!</h2>
<form>
<h1>Success</h1>
edit page
<c:out value="${id}" />
</form>
</body>
</html>
Edit.jsp Page Imge
edit jsp page image
As editVal is a string, you can access it <c:out value="${shopModel}" />
If its a list of string, then the following can be used
<c:forEach var="shop" items="${shopModel}">
<c:out value="${shop}" />
</c:forEach>
If its a list of objects, then var.<object attribute name> as follows
<c:forEach items="${shopModel}" var="shop">
<tr>
<td>${shop.name}</td>
<td>${shop.number}</td>
...
</tr>
</c:forEach>
I have designed a Login page using Spring MVC,JPA(Hibernate) and Jsp.
Please find the login.jsp :-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# 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>
<body>
<h2>Login page</h2>
<form:form method="POST" modelAttribute="loginBean" action="showProfile">
<table>
<tr>
<td>UserName :<form:input path="userName"/></td>
</tr>
<tr>
<td>Organization Id :<form:input path="OrgId" /></td>
</tr>
<tr>
<td>Password : <form:input path="password" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
profilePage.jsp:-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# 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="2" width="70%" cellpadding="2">
<tr>
<th>UserName</th>
<th>Password</th>
</tr>
<c:forEach var="staff" items="${staffData}">
<tr>
<td>${staff.userName}</td>
<td>${staff.password}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
LoginController.java:-
#Controller
public class LoginController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String showLoginPage(Model model) {
model.addAttribute("loginBean", new LoginBean());
return "login";
}
#RequestMapping(value = "/showProfile", method = RequestMethod.POST)
public ModelAndView redirectToprofile(#ModelAttribute("loginBean") LoginBean loginBean) {
StaffServiceImpl staffServiceImpl = new StaffServiceImpl();
Staff staff = staffServiceImpl.authenticateStaff(loginBean);
if (null != staff) {
return new ModelAndView("redirect:/profilePage","staffData",staff);
}
return new ModelAndView("profileNotFound");
}
#RequestMapping(value = "/profilePage", method = RequestMethod.GET)
public String showProfilePage() {
return "profilePage";
}
After giving the valid details in the Login.jsp page it is redirecting to profilePage.jsp but the data in profilePage.jsp is not correct. Please help me to understand where i am doing the mistake.
The profilePage.jsp is displayed a below:-
UserName Password
${staff.userName} ${staff.password}
The Value of this variable is not getting displayed.
profilePage.jsp : Add isELIgnored="false" in page directive.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false"%>
Update your controller with the following :
#Controller
public class LoginController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String showLoginPage(Model model) {
model.addAttribute("loginBean", new LoginBean());
return "login";
}
#RequestMapping(value = "/showProfile", method = RequestMethod.POST)
public String redirectToprofile(#ModelAttribute("loginBean") LoginBean loginBean , Model model) {
StaffServiceImpl staffServiceImpl = new StaffServiceImpl();
Staff staff = staffServiceImpl.authenticateStaff(loginBean);
if (null != staff) {
model.addAttribute("staffData",staff);
return "profilePage";
}
return "profileNotFound";
}
the above answer is correct, and this is an explination:
The isELIgnored attribute gives you the ability to disable the evaluation of Expression Language (EL) expressions which has been introduced in JSP 2.0.
The default value of the attribute is true, meaning that expressions, ${...}, are evaluated as dictated by the JSP specification. If the attribute is set to false, then expressions are not evaluated but rather treated as static text.
Source :enter link description here