Transmit request from jsp to java - 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>

Related

Variables not making it from one JSP to the other when using HttpSession

I am having trouble retrieving any type of parameter from one jsp page to the other using doPost, and a form where my method is post. Note below is a minimal example.
First, I have two pages:
Here is search.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html>
<html>
<head>
<title>search</title>
<body>
<form name="search" method="post" action="search_results.jsp">
<p>
<input type="text" class="inputTitle" id="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
<button type="submit">Search</button>
<p>
</form>
</body>
</html>
And my search_results.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<title>search results</title>
<body>
<p>Title: ${movie.title}</p>
</body>
</html>
Now I have a class called SearchServlet.java:
#WebServlet("/search")
public class SearchServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
request.getRequestDispatcher("search.jsp").forward(request,response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
String title = request.getParameter("inputTitle");
String searchTitle;
try {
if(title != null && !title.isEmpty()) {
searchTitle = "hello";
} else {
searchTitle = "world";
}
session.setAttribute("movie.title", searchTitle);
request.getRequestDispatcher("search_results.jsp").forward(request, response);
} catch(ServletException e) { e.printStackTrace(); }
}
}
No matter what I enter the result (movie.title) always ends up being empty and so I get world on search_results.jsp. Why is my parameter not being passed to search_results.jsp?
It will not happen if you bypass the servlet
Look at your form action
<form name="search" method="post" action="search_results.jsp">
You are sending the post request directly to the search_results.jsp: you should send it to the servlet instead (mapped # /search)
<form name="search" method="post" action="search">
Then from the servlet you should forward the request to the search_result.jsp, which you actually did.
In addition to that when you call request.getParameter you have to keep in mind that what counts is the name of the input field, not the id. You should change the id attribute to name
<input type="text" class="inputTitle" name="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
Lastly, hopefully :) the '.' (dot) might cause issues:
session.setAttribute("movie.title", searchTitle);
When you retrieve the attribute the dot notation indicates that you are accessing a field in a object called movie
<p>Title: ${movie.title}</p> <!-- you are accessing the title property of a movie object !-->
but you do not have that...you have a movietitle, a String presumably. Change the attribute name to something like movietitle without the dot and retrieve it in the jsp the same way. the above lines will become:
session.setAttribute("movietitle", searchTitle);
<p>Title: ${movietitle}</p>
That should solve the issue.

thrown exception AS-WEB-CORE-00089 on forwarding to a different servlet path

I was trying to forward from doPost to doGet of the ControllerServlet urlPattern = "/remove_person", so I can re-update findAll query inside my doGet method of the ControllerServlet class, and then forward to remove_person.jsp from doGet method, but AS-WEB-CORE-00089 exception is thrown
WARNING: StandardWrapperValve[ControllerServlet]: Servlet.service() for servlet ControllerServlet threw exception
javax.servlet.ServletException: AS-WEB-CORE-00089
at org.apache.catalina.core.ApplicationDispatcher.doInvoke(ApplicationDispatcher.java:863)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:739)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:575)
at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:546)
at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:428)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:378)
at server.ControllerServlet.doPost(ControllerServlet.java:130)
where ControllerServlet.java:130 line is in doPost() method:
request.getRequestDispatcher(url).forward(request, response);
Here is the code of servlet class:
#WebServlet(
name = "ControllerServlet",
loadOnStartup = 1,
urlPatterns = {
"/index",
"/search_person",
"/add_person",
"/remove_person"})
public class ControllerServlet extends HttpServlet {
#PersistenceUnit
private EntityManagerFactory emf;
#Resource
private UserTransaction utx;
private EntityManager em;
#Override
public void init() throws ServletException {
assert emf != null;
em = emf.createEntityManager();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String servletPath = request.getServletPath();
if (servletPath.equals("/index")) {
}
else if (servletPath.equals("/search_person")) {
List persons = em.createNamedQuery("Person.findAll").getResultList();
request.setAttribute("findByNameAndYearBirth", persons);
}
else if (servletPath.equals("/add_person")) {
}
else if (servletPath.equals("/remove_person")) {
List persons = em.createNamedQuery("Person.findAll").getResultList();
request.setAttribute("findAll", persons);
}
String url = servletPath + ".jsp";
request.getRequestDispatcher(url).forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String servletPath = request.getServletPath();
if (servletPath.equals("/index")) {
}
else if (servletPath.equals("/search_person")) {
String name = request.getParameter("name");
String yearBirth = request.getParameter("yearBirth");
Query query = em.createNamedQuery("Person.findAll");
if (!name.isEmpty() && !yearBirth.isEmpty()) {
query = em.createNamedQuery("Person.findByNameAndYearBirth");
query.setParameter("name", name);
query.setParameter("yearBirth", Short.parseShort(yearBirth));
}
else if (!name.isEmpty()) {
query = em.createNamedQuery("Person.findByModel");
query.setParameter("name", name);
}
else if (!yearBirth.isEmpty()) {
try {
Short sYearBirth = Short.parseShort(yearBirth);
query = em.createNamedQuery("Person.findByYearBirth");
query.setParameter("yearBirth", sYearBirth);
} catch (NumberFormatException nfe) {}
}
List persons = query.getResultList();
request.setAttribute("findByNameAndYearBirth", persons);
}
else if (servletPath.equals("/add_person")) {
String name = request.getParameter("name");
String hobby = request.getParameter("hobby");
String yearBirth = request.getParameter("yearBirth");
int personsLen = em.createNamedQuery("Person.findAll").getResultList().size();
Person newPerson = new Person(
++personsLen, name, hobby, Short.parseShort(yearBirth)
);
try {
utx.begin();
em = emf.createEntityManager();
em.persist(newPerson);
utx.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
else if (servletPath.equals("/remove_person")) {
String id = request.getParameter("id");
Person person = null;
try {
utx.begin();
person = em.find(Person.class, Integer.parseInt(id));
em.remove(person);
utx.commit();
} catch (Exception e) {
e.printStackTrace();
}
servletPath = "/remove_person";
}
String url = servletPath;
request.getRequestDispatcher(url).forward(request, response);
}
}
Problem is, my line inside doPost method
String url = path;
does not contain a ".jsp" part.
But if I add ".jsp" part to a string url, then how I will update findAll query data inside remove_person.jsp if i don't go to servlet doGet first to collect new data after adding or deleting entities?
remove_person.jsp
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Remove Person</h1>
<form action="remove_person" method="post">
<table border="3">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<c:forEach var="person" begin="0" items="${findAll}">
<tr>
<td>${person.id}</td>
<td>${person.name}</td>
</tr>
</c:forEach>
</table>
<strong>Remove person: </strong>
<select name="id">
<c:forEach var="person" items="${findAll}">
<option value="${person.id}">${person.id}. ${person.name} </option>
</c:forEach>
</select>
<input type="submit" id="remove_person" value="Remove" />
</form>
<br>
Home page
</body>
</html>
Actually, is it even possible to forward from doPost to doGet method of the same servlet ? The reason I was trying to do this is because, inside doGet I already use this code:
List persons = em.createNamedQuery("Person.findAll").getResultList();
request.setAttribute("findAll", persons);
So why should I duplicate this code inside doPost method, when I can forward from doPost to doGet method and invoke that code?
UPDATE:
Bad approach:
String url = servletPath;
request.getRequestDispatcher(url).forward(request, response);
Correct approach:
String url = request.getContextPath() + servletPath;
response.sendRedirect(url);
Use redirect instead of forward. The pattern (called Post/Redirect/Get) is:
1) the client calls the post url, which does your update
2) the servlet sends a redirect to the client with the url for the get.
3) the client calls the url from the redirect.
When the response from the GET comes back the browser has the GET url, so the browser ends up with a url that's bookmarkable. Also this way the user can't repost the same data by hitting f5 or clicking multiple times.
For when to use forward vs redirect see this advice:
Forward
a forward is performed internally by the servlet
the browser is completely unaware that it has taken place, so its original URL remains intact
any browser reload of the resulting page will simple repeat the original request, with the original URL
Redirect
a redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the
original
a browser reload of the second URL will not repeat the original request, but will rather fetch the second URL
redirect is marginally slower than a forward, since it requires two browser requests, not one
objects placed in the original request scope are not available to the second request
In general, a forward should be used if the operation can be safely repeated upon a browser reload of the resulting web page; otherwise, redirect must be used. Typically, if the operation performs an edit on the datastore, then a redirect, not a forward, is required. This is simply to avoid the possibility of inadvertently duplicating an edit to the database.

Sending a variable from Servlet to JSP

I got a question about servlets and jsp.
Servlet:
public class Servlet extends javax.servlet.http.HttpServlet {
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
Integer i = new Integer(15);
request.setAttribute("var", i);
RequestDispatcher Dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
Dispatcher.forward(request, response);
}
JSP page:
<html>
<head>
<title></title>
</head>
<body>
<form id="id" method="get" action="servlet">
<%= (request.getAttribute("var")) %>
</form>
</body>
</html>
As a result I expect to see 15, but I see null. Why does it happen?
Request parameters are sent from the view to the controller, request attributes are used to pass data in the current request to help build the new response. So, you should not use scriplets and access to the request attributes by using Expression Language:
<body>
<!-- No need to use a form for this page -->
The request attribute: ${var}
</body>
Note that by your current request, you should perform a GET request on your servlet. Since your servlet name is servlet (which I suggest your to change it immediately), you should access to this URL: http://yourServerName/yourApplicationName/servlet
Use request.getAttribute("var");
I don't know in the servlet but in struts 2 you need getter and setter method to sent data from jsp, you try this:
public class Servlet extends javax.servlet.http.HttpServlet
{
private Integer i;
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
i = new Integer(15);
request.setAttribute("var", i);
RequestDispatcher Dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
Dispatcher.forward(request, response);
}
public Integer getI()
{
return i;
}
public void setI(Integer i)
{
this.i = i;
}
}//also lacked this

The requested resource is not available, Glassfish [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I have tried to look for answers else where on this website but i have not been able to find anything that helps me. When ever press the create actor button to send the information to a controller i always get "HTTP 404 Status - not found: The requested resource is not available" I was just wondering if any could help me sort out this frustrating problem
This is the code for my index.jsp where i submit the information
<!DOCTYPE html>
<html>
<head>
<meta charset= "UTF-8" >
<title>Index Page</title>
</head>
<body>
<h1>Movie Example Index Page</h1>
<!--submit button goes to the controller-->
<form action="Controller" method="post">
<p>
ID <input TYPE = "text" name = "actorID"/>
Name <input TYPE ="text" name ="name"/>
Birth Year <input TYPE ="text" name ="birth_year"/>
<input TYPE="submit" value="Create Actor" />
</p>
</form>
</body>
</html>
And this is my Controller code
package MVC_Movie_Example;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// Class definition
public class Controller extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
// Make an instance of a new actor
int id = Integer.parseInt(request.getParameter("actorID"));
String name = request.getParameter("name");
int birthYear = Integer.parseInt(request.getParameter("birth_year"));
Actor actor = new Actor(id, name, birthYear);
// Set the actor attribute within the request
request.setAttribute("theActor", actor);
// Send it on to a different View
request.getRequestDispatcher("outputView.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
The actor class code is
package MVC_Movie_Example; // Package declaration
// Class definition
public class Actor {
private int id;
private String name;
private int birthYear;
public Actor() {
} // Default constructor
// Value based constructor
public Actor(int externId, String externName, int externBirthYear) {
this.id = externId;
this.name = externName;
this.birthYear = externBirthYear;
}
// Actor id getter method
public int getId() {
return this.id;
}
// Actor id setter method
public void setId(int externId) {
this.id = externId;
}
// Actor name getter method
public String getName() {
return this.name;
}
// Actor name setter method
public void setName(String externName) {
this.name = externName;
}
// Other methods follow, including birthYear getter and setter
} // End of class definition
And finally this is the code for where the controller sends the output
<!DOCTYPE html>
<html>
<head>
<meta charset= "UTF-8" >
<title>Movie View Example - Output View</title>
</head>
<body>
<h1>Movie View Example – Out View Page</h1>
<jsp:useBean id="actor" type="MVC_Movie_Example.Actor" scope="request" />
<table border="1">
<tr>
<th>ID</th>
<th>Actor Name</th>
<th>Year of birth</th>
</tr>
<tr>
<td><jsp:getProperty name= "theActor" property="id" /></td>
<td><jsp:getProperty name= "theActor" property="name" /></td>
<td><jsp:getProperty name= "theActor" property="birthYear" /></td>
</tr>
</table>
</body>
</html>
WebServlet annotation above Controller class is missing
#WebServlet(name="Controller" urlPatterns={"/Controller"} )
public class Controller extends HttpServlet
{
//To-DO
}
You can also manually configure the web.xml file by adding the tags:
<servlet>
<servlet-name>Controller</servlet-name> //a name to be used for mapping requests.
<servlet-class>MVC_Movie_Example.Controller</servlet-class> //the servlet's package and class name.
</servlet>
and ....
<servlet-mapping>
<servlet-name>Controller</servlet-name> //must be the same as in tag <servlet-name> above
<url-pattern>mycontoller</url-pattern> //now..this is the name to use in the action attribute of your form.
</servlet-mapping>
The <servlet-mapping> tag will map the any url pattern matching what is specified in between the <url-pattern> tag to the servlet class specified in <servlet-name>.
This is an alternative to the annotation based solution. Hope it helps someone.

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

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

Categories

Resources