Model objects are not passed to jsps in Spring MVC - InternalResourceView - renderMergedOutputModel - java

I am using JstlView Spring Tiles in my project.
When i try to send form:errors from validator to jsp through controller,errors are not being dispayed in jsp
when i debug,
1)errors are being printed in controller class before returning modelandview , from validator class.
2)Then error are also being printed in JstlView class from controller class.
So i think, requestDispatcher.forward(request, response) in jstlview class is not returning model data to jsp.
Because when i tried HttpServletRequest or HttpServletResponse objects to retrive errors in jsp , values are being dispalyed in jsp.
Can some one help me in this used.
How can i send model data to jsp renderMergedOutputModel- RequestDispatcher , redirect method.
My code is as follows,
JstlView class:
public class JstlView extends InternalResourceView {
#Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
// Determine the path for the request dispatcher.
String dispatcherPath = prepareForRendering(request, response);
// set original view being asked for as a request parameter
request.setAttribute("partial", dispatcherPath.substring(dispatcherPath.lastIndexOf("/") + 1));
// force everything to be template.jsp
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/template.jsp");
requestDispatcher.forward(request, response);
System.out.println("**********************"+model.get("userName"));
}
}
Servlet.xml
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="com.tms.web.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
Controller:
private LoginValidator loginValidator;
#Autowired
public void setUserValidator(LoginValidator loginValidator) {
this.loginValidator = loginValidator;
}
final RequestHandler requestHandler = new RequestHandler();
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login() {
return new ModelAndView("login", "users", new users());
}
#RequestMapping(value = "/logins",method = RequestMethod.POST)
public ModelAndView validateUser(#Valid users user, BindingResult result,#ModelAttribute("users")users users,ModelMap model,RedirectAttributes redirectAttributes,HttpServletRequest req)
{
this.loginValidator.validate(user, result);
if (result.hasErrors())
{
model.putAll(result.getModel());//values not retuned to jsp
req.setAttribute("userName", result.getFieldError().getDefaultMessage().toString()); //working fine values retuned to jsp
return new ModelAndView("/login", model);
}
else
{
//succes related code
return new ModelAndView(redirect, model);
}
}
Validator
#Component
public class LoginValidator implements Validator {
#Override
public boolean supports(Class<?> clazz) {
return clazz.isAssignableFrom(users.class);
}
#Override
public void validate(Object obj, Errors errors) {
users user = (users) obj;
String userName = user.getUserName();
String password = user.getPassword();
validateuserName(userName,password, errors);
}
private void validateuserName(String userName, String password,Errors errors) {
if (!(isValidString(userName))) {
errors.rejectValue("userName", "userName.required","Username should not be blank");
}
else if(!(isValidString(password)))
{
errors.rejectValue("password", "password.required","Password should not be blank");
}
}
private boolean isValidString(String str) {
return isNotNull(str) && (str.length() > 0 ) && !(str.isEmpty());
}
private boolean isNotNull(String str) {
return str != null;
}
}
Jsp
<%# page language="java" contentType="text/html;charset=UTF-8; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" %>
<%# page isScriptingEnabled="true" isELIgnored="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<form:form method="POST" action="/TMSWeb/logins" commandName="users" modelAttribute="users">
<input name="password" type="password" align="center"/>
<form:errors path="password" cssClass="error" element="div" />
<input type="submit" class="buttonorange" value="Login"/>
</form:form>
In Spring MVC when I can access my beans in JSP without JstlView's, then, in my JSP I can write (${errors). But when the same JSP is a part of a tiles view, these properties aren't accessible.
Can someone help me in this issue?

You are extending the class org.springframework.web.servlet.view.InternalResourceView in your JstlView class and override renderMergedOutputModel method, where you are missing to expose the model object. call this method exposeModelAsRequestAttributes(model, requestToExpose); from override method as shown below. Try with below code, which is worked for me.
#Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
// Expose the model object as request attributes.
exposeModelAsRequestAttributes(model,request);
// Determine the path for the request dispatcher.
String dispatcherPath = prepareForRendering(request, response);
// set original view being asked for as a request parameter
request.setAttribute("partial", dispatcherPath.substring(dispatcherPath.lastIndexOf("/") + 1));
// force everything to be template.jsp
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/template.jsp");
requestDispatcher.forward(request, response);
System.out.println("**********************"+model.get("userName"));
}
}

Related

Unable to logout using spring 4 MVC

I have used spring 4 MVC in my project which is annotation based.
I am able to login successfully but I am not able to logout.
I have posted the configuration,initializer and controller classes below
along with the login page and welcome page.Please let me know what changes need to be done to my code so that I log out successfully.
I am currently getting the below error on logout
Feb 06, 2017 2:36:03 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/Student_Login/%3Cc:url%20value='/login'%20/%3E] in DispatcherServlet with name 'dispatcher'
AppConfig_login
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.student.login")
public class AppConfig_login {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("message");
return messageSource;
}
}
AppInitializer_login
public class AppInitializer_login extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig_login.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}}
AppController
package com.student.login.controller;
import java.util.List;
import java.util.Locale;
#Controller
#RequestMapping("/")
public class AppController_login {
#Autowired
StudentService service;
#Autowired
MessageSource messageSource;
/*
* This method will list all existing employees.
*/
#RequestMapping(value = {"/"}, method = RequestMethod.GET)
public String listStudents(ModelMap model) {
//List<Student> students = service.findAllStudents();
//model.addAttribute("students", students);
Student student = new Student();
model.addAttribute("student", student);
return "login";
}
#RequestMapping(value = { "/" }, method = RequestMethod.POST)
public String checkCredentials(#Valid Student student, BindingResult result,
ModelMap model) {
if (result.hasErrors()) {
return "login";
}
System.out.println(student.getRoll_no());
System.out.println(student.getPassword());
/*
* Preferred way to achieve uniqueness of field [ssn] should be implementing custom #Unique annotation
* and applying it on field [ssn] of Model class [Employee].
*
* Below mentioned peace of code [if block] is to demonstrate that you can fill custom errors outside the validation
* framework as well while still using internationalized messages.
*
*/
if(service.isCredentialValid(student.getRoll_no(),student.getPassword())){
FieldError login_Error =new FieldError("student","password",messageSource.getMessage("non.unique.credentials", new String[]{student.getRoll_no()}, Locale.getDefault()));
result.addError(login_Error);
return "login";
}
//service.saveStudent(student);
model.addAttribute("welcome", "Welcome Student " + student.getName() + " registered successfully");
return "welcome_student";
}
#RequestMapping(value = { "/login" }, method = RequestMethod.GET)
public String logoutPage(ModelMap model) {
Student student = new Student();
model.addAttribute("student", student);
//model.addAttribute("edit", false);
return "login";
}
/*
* This method will provide the medium to add a new employee.
*/
#RequestMapping(value = { "/registration" }, method = RequestMethod.GET)
public String newStudent(ModelMap model) {
Student student = new Student();
model.addAttribute("student", student);
model.addAttribute("edit", false);
return "registration";
}
/*
* This method will be called on form submission, handling POST request for
* saving employee in database. It also validates the user input
*/
#RequestMapping(value = { "/registration" }, method = RequestMethod.POST)
public String saveEmployee(#Valid Student student, BindingResult result,
ModelMap model) {
if (result.hasErrors()) {
return "registration";
}
if(!service.isStudentRollNoUnique(student.getRoll_no())){
FieldError roll_no_Error =new FieldError("student","roll_no",messageSource.getMessage("non.unique.roll_no", new String[]{student.getRoll_no()}, Locale.getDefault()));
result.addError(roll_no_Error);
return "registration";
}
service.saveStudent(student);
model.addAttribute("success", "Student " + student.getName() + " registered successfully");
return "login_success";
}}
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Registration Form</title>
<style>
.error {
color: #ff0000;
}
</style>
</head>
<body>
<h2>Login Form</h2>
<form:form method="POST" modelAttribute="student">
<!-- <form:input type="hidden" path="id" id="id"/>-->
<table>
<tr>
<td><label for="roll_no">Roll No:</label> </td>
<td><form:input path="roll_no" id="roll_no"/></td>
<td><form:errors path="roll_no" cssClass="error"/></td>
</tr>
<tr>
<td><label for="password">Password:</label> </td>
<td><form:input path="password" id="password"/></td>
<td><form:errors path="password" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
<br/>
<br/>
Go back to Registration
</body>
</html>
welcome_student
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>
hello user
Logout
</body>
</html>
So I finally figured out that the problem was in my jsp welcome_student
I forgot to include the below line
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

get value from a session Object

I have a User bean class with constructor and getter and setter
public class User {
private String username;
private String password;
}
i have a controller which logs in a user
#PostMapping("/login")
public String login(#ModelAttribute User user,Model model){
model.addAttribute("session", user);
return "index1";
}
Also one demo mapping for the same index1 page to check session
#GetMapping("/find")
public String find(Model model){
return "index1";
}
in the jsp page i am not able to check the user that is populated in the session object
<%# page errorPage="index.jsp" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Login</h1>
<c:if test='${sessionScope.session.user} == "user"'>
<% session.invalidate(); %>
</c:if>
<p>Hello ${sessionScope.session.password}</p>
</body>
</html>
i am using #sessionattribute of Spring to use the session values and my session object name is session .
How to invalidate the session when user is user it always comes as null please help .
How to get the values inside the object that is stored in a session
this is a demo to test session handling
Following will not work for you,
#PostMapping("/login")
public String login(#ModelAttribute User user,Model model){
model.addAttribute("session", user);
return "index1";
}
Because first of all you are not setting anything in the ModelAndView but into a model object which will be nullified once you move to index1 view.
You need to set the if as follows,
#PostMapping("/login")
public ModelAndView login(#ModelAttribute User user, Model model, HttpServletRequest request){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("session", user);
modelAndView.setViewName("index1");
return modelAndView;
}

URL Redirect in Servlet after form

In my Java web app I have a unique Front Controller which maps all the requests, and various controllers that execute the logic and return a string representing the next page the user is forwarded to.
This works, but when I submit a form with post method, the form action gets appended to the URL in the address bar. For example, if the login method in LoginController returns false (so that nextPage="/index.jsp"), it correctly redirects to that page, but in the address bar I'll have /MyAPP/app/home.jsp anyway. Is there a way to avoid this?
I took a look to the Post/Redirect/Get pattern, but I'd like to figure out how can I implement this without aggressively changing the structure.
#WebServlet("/app/*")
public class FrontController extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private Map<String, Controller> controllers = new HashMap<String, Controller>();
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
processRequest(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
processRequest(req, resp);
}
private void processRequest(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String pathInfo = req.getPathInfo();
String controllerName = pathInfo.substring(pathInfo.lastIndexOf('/'));
Controller c = controllers.get(controllerName);
String resource = c.action(req, resp);
req.getRequestDispatcher(resource).forward(req, resp);
}
#Override
public void init() throws ServletException {
super.init();
controllers.put("/index.jsp", new IndexController());
controllers.put("/home.jsp", new LoginController());
}
}
public class LoginController implements Controller {
private static final String USERNAME_PARAM = "username";
private static final String PASSWORD_PARAM = "password";
private static final String USERBEAN_ATTR = "userBean";
public String action(HttpServletRequest request, HttpServletResponse response) {
String username = request.getParameter(USERNAME_PARAM);
String password = request.getParameter(PASSWORD_PARAM);
boolean result = false;
UserBean userBean = (UserBean)request.getSession().getAttribute(USERBEAN_ATTR);
userBean.setUsername(username);
userBean.setPassword(password);
if (!username.isEmpty() && !password.isEmpty())
result = userBean.doLogin();
String nextPage = result ? "/home.jsp" : "/index.jsp";
if (!result)
request.setAttribute("error", "Login Error");
return nextPage;
}
}
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# 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=UTF-8">
<title>Welcome!</title>
</head>
<body>
<h1>Welcome</h1>
<form
action="${pageContext.request.contextPath}/app/home.jsp"
method="post">
Username: <input type="text" name="username"> <br>
Password: <input type="text" name="password"> <br> <input
type="submit" value="Log In" />
</form>
<p>${error}</p>
</body>
</html>

SpringMVC model attribute returns null on post

I was developing a SpringMVC 3 trivial application, but I got stuck somewhere. Essentially, a model attribute whose fields are filled in the GET operation are returned NULL in the POST (even if I don't make any operation on them). I've checked on this and other forums and the only answer I came up with was to implement Editors for the classes I should put into the model, an initializer that could be used to register custom editors and make it available to the application (in the servletname-servlet.xml file). All operations that I did, but definitely no luck. I was wondering if someone out there could give me a hand.
Thank you.
The following controller:
#Controller
#RequestMapping(value="/nourish")
public class NourishController {
private PetDAO pdao = new PetDAO();
private UserDAO udao = new UserDAO();
private FeedVirtualPet feedvp = new FeedVirtualPet();
#RequestMapping(method = RequestMethod.GET)
public String nourish(Model model, HttpServletRequest request){
NourishPetDTO npdto = new NourishPetDTO();
PetDTO pdto=pdao.findPetByBusinessKey((PetDTO)request.getSession().getAttribute("pet"));
npdto.setPet(pdto);
npdto.setAmt(0);
model.addAttribute("npdto", npdto);
return "nourish";
}
#RequestMapping(method = RequestMethod.POST)
public String nourishPOST(#ModelAttribute("npdto") NourishPetDTO npdto,
//BindingResult result,
HttpServletRequest request){
System.out.println("*****nourishPOST.npdto.amt: "+npdto.getAmt());
System.out.println("*****nourishPOST.npdto.pet.petname: "+npdto.getPet().getPetName());
System.out.println("*****nourishPOST.npdto.pet.hunger: "+npdto.getPet().getHunger());
PetDTO pdto = feedvp.feed(npdto.getPet(), npdto.getAmt());
request.getSession().setAttribute("user", pdto.getOwner());
return "redirect:detailPet";
}
}
has methods for both GET and POST operations, and is associated to the following jsp - in this view, all the model informations are correctly displayed through EL:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" session="true" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Nourish your pet!!</title>
</head>
<body>
Your stats for <h3>${npdto.pet.petName}</h3><br>
Please note that any value you put inside will:
<ol>
<li>Subtract value to your current hunger level</li>
<li>Add (value) to your current health level</li>
</ol>
Please note that any value you'll put will in many manners "resized":
<ol>
<li>It must be even. If not, a default 0 value will be applied</li>
<li>It can't be greater than 4. If it's greater, the maxium value of 4 will be anyway considered.</li>
<li>If it ain't a number, a default zero value will be passed</li>
</ol>
<table>
<tr><td>Health</td><td>${npdto.pet.health}</td></tr>
<tr><td>Hunger</td><td>${npdto.pet.hunger}</td></tr>
</table>
<form action="nourish" method="post" >
nourishment: <input type="text" name="amt"/>
<input type="submit" value="Nourish!"/>
</form>
</body>
</html>
(Please note how I didn't use the model attribute that's returning NULL, to be sure I wasn't doing anything to it)
The POST operations fail on the instruction
System.out.println("*****nourishPOST.npdto.pet.petname:"+npdto.getPet().getPetName());
as Tomcat returns a NullPointerException.
As aforementioned, I have been searching a solution to this problem, and everything I could find is to add Editor classes & register Editors to a binder. Result is still the same.
Anyway, these are the classes:
NourishPetEditor.java
public class NourishPetEditor extends PropertyEditorSupport {
private PetEditor pedit;
public PetEditor getPedit() {
return pedit;
}
public NourishPetEditor() {
// TODO Auto-generated constructor stub
pedit = new PetEditor();
}
#Override
public String getAsText(){
NourishPetDTO npdto= (NourishPetDTO)getValue();
return super.getAsText()+","+npdto.getAmt();
}
public NourishPetDTO makeNourishPetDTOInstance(String [] parts){
NourishPetDTO npdto = new NourishPetDTO();
npdto.setPet(pedit.makePetDTOInstance(parts));
npdto.setAmt(Integer.parseInt(parts[9]));
return npdto;
}
public void setAsText(String key){
String []parts = key.split(",");
NourishPetDTO npdto = makeNourishPetDTOInstance(parts);
setValue(npdto);
}
}
PetEditor.java
package com.virtualpet.dtoeditors;
import java.beans.PropertyEditorSupport;
import com.virtualpet.virtualpet_daos.PetDAO;
import com.virtualpet.virtualpet_dtos.PetDTO;
import com.virtualpet.virtualpet_dtos.UserDTO;
public class PetEditor extends PropertyEditorSupport{
private PetDAO pdao;
public PetEditor() {
// TODO Auto-generated constructor stub
}
public PetEditor(PetDAO pdao) {
// TODO Auto-generated constructor stub
this.pdao = pdao;
}
public String getAsText(){
PetDTO pdto = (PetDTO) this.getValue();
return pdto.getClass().getName()+","+ //0
pdto.getPetName()+","+ //1
pdto.getHealth()+","+ //2
pdto.getHunger()+","+ //3
pdto.getMood()+","+","+ //4
pdto.getOwner().getClass().getName()+","+ //5
pdto.getOwner().getUsername()+","+ //6
pdto.getOwner().getEmail()+","+pdto.getOwner().getPassword(); //7,8
}
public void setAsText(String key) throws IllegalArgumentException {
String []parts = key.split(",");
PetDTO pdto = makePetDTOInstance(parts);
setValue(pdto);
}
public UserDTO makeUserDTOInstance(String[] parts)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
UserDTO udto = (UserDTO)Class.forName(parts[5]).newInstance();
udto.setUsername(parts[6]);
udto.setEmail(parts[7]);
udto.setPassword(parts[8]);
return udto;
}
public PetDTO makePetDTOInstance(String[]parts){
try{
PetDTO pdto = (PetDTO) Class.forName(parts[0]).newInstance();
pdto.setPetName(parts[1]);
pdto.setHealth(Integer.parseInt(parts[2]));
pdto.setHunger(Integer.parseInt(parts[3]));
pdto.setMood(Integer.parseInt(parts[4]));
UserDTO udto = makeUserDTOInstance(parts);
pdto.setOwner(udto);
return pdto;
}
catch (Exception e){
throw new IllegalArgumentException();
}
}
}
I'll spare you UserEditor, as it's pretty much similar to PetEditor.
Finally, the Initializer to bind the custom editors & the Model Classes.
VirtualPetDTOInitializer.java
package com.virtualpet.dtoeditors;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;
import com.virtualpet.virtualpet_dtos.NourishPetDTO;
import com.virtualpet.virtualpet_dtos.PetDTO;
import com.virtualpet.virtualpet_dtos.UserDTO;
public class VirtualPetDTOInitializer implements WebBindingInitializer {
public void initBinder(WebDataBinder binder, WebRequest arg1) {
// TODO Auto-generated method stub
binder.registerCustomEditor(UserDTO.class, new UserEditor( ));
binder.registerCustomEditor(PetDTO.class, new PetEditor( ));
binder.registerCustomEditor(NourishPetDTO.class, new NourishPetEditor());
}
}
This class defines a property value in dispatcher-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<bean id="userDao"
class="com.virtualpet.virtualpet_daos.UserDAO"/>
<bean id="petDao"
class="com.virtualpet.virtualpet_daos.PetDAO" />
<bean class="org.springframwork.web.servlet.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="com.virtualpet.dtoeditors.VirtualPetDTOInitializer"/>
</property>
</bean>
</beans>
Being a total rookie on Spring MVC, I must tell you that this error is something I got even before I implemented these classes. So, looks like they're not a factor and yet, their implementation is everything I could find aboud model attribute returned null after POST.
Could anyone please help? Thanks in advance.
You need to do one of the following:
Store the values of npdto in hidden form fields
Store npdto in session
Re-read npdto from the database in your post handler
You probably want #2, in which case add #SessionAttributes("npdto") on top of your Controller.
You should also add a SessionStatus parameter to your post handler, and call sessionStatus.complete() to clear the item from session when you don't need it any more.
See Spring MVC: Validation, Post-Redirect-Get, Partial Updates, Optimistic Concurrency, Field Security for a reference answer.

Transmit request from jsp to java

I've got a jsp file:
... import <%# page import="classPath.ExampleClass" %>
<%
ExampleClass cl = new ExampleClass(request);
%>
The Code of ExampleClass (Java):
private HttpServletRequest req;
public ExampleClass(HttpServletRequest req) {
this.req = req;
}
So I want to receive the complete request to evaluate it in Java. But during deploying the following error appears:
Cannot process HttpRequest to Servlet
Why?
Do not messup.Use of implicit objects of JSP
JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.
just write
<%
ExampleClass cl = new ExampleClass(request);
%>
Create bean class like.
public class ExampleClass{
HttpServletRequest request;
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
}
Now pass implicit request object with jsp tag
<jsp:useBean id="exampleClass" class="classPath.ExampleClass" scope="request"/>
<jsp:setProperty name="exampleClass" property="request" value="${pageContext.request}"/>
In your jsp add the following directive:
<jsp:useBean id="bean" class="classPath.ExampleClass" scope="request">
<jsp:setProperty name="bean" property="*" />
<jsp:setProperty name="bean" property="request" value="${pageContext.request}" />
</jsp:useBean>
The property "*" means that all attributes coming from the request will be set on the bean (class) e.g. form submission with various input fields.
The property "request" will set the HttpServletRequest as the last parameter so this method can be used as an indicator to start your logic.
Your class could look like:
public class ExampleClass {
private HttpServletRequest request;
private String fieldValue;
public void doLogic() {
// do your controller logic here
}
public HttpServletRequest getRequest() {
return request;
}
public String getFieldValue() {
return fieldValue;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
doLogic();
}
public void setFieldValue(String fieldValue) {
this.fieldValue = fieldValue;
}
}
Notice that the property fieldValue is a custom field that you can add and can be set via form submission as mentioned above:
<form method="post">
<input name="feildValue" type="text" value="${bean.fieldValue}"/>
<input name="btnSubmit" type="submit" value="Submit"/>
</form>

Categories

Resources