I am writing a jsp file to call a controller with some parameters. And from this controller i want to call a servlet by passing the values from the controller. And with in the servlet i should get access to the parameters. Is it possible to forward values from jsp to servlet via controller?
Yes it's possible in Spring controller,
Try this in Spring controller:
public void requestedURL(HttpServletRequest req, HttpServletResponse res){
String jspParameter = request.getParameter("param_name");
req.getRequestDispatcher("your servlet url pattern?param1="+jspParameter)
.forward(req, res);
}
Related
I need to implement a servlet with java and a tomcat server. I also need to use the MVC pattern.
So the model part is clear to me. But how do I seperate view and controler in this case? I thought my httpServlet class is my view, but how do I then implement the controller?
Model is your business data that you deal with. and finally you sent it to client to render in view(JSP)
View is your Jsp Pages which controller sends to the client, based on client request.
Controller is your Servlet which accept the client request and execute your business logic and select appropriate view(JSP) and return it to client.
see the below Example where TestServlet is your Controller, Index.jsp is you view.
public class TestServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//business logic that deal with the your Model
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
}
The httpServlet is the controller, The servlet needs to forward request to a JSP(Jsp is termed as view).
This question already has answers here:
How do I execute multiple servlets in sequence?
(2 answers)
Closed 6 years ago.
I am using net beans 7.1 and I create one JSP file with two servlet files.
like:
index.jsp --->servlet1.java --->servlet2.java
I give some value from index.jsp file and send to servlet1.java.
In this servlet1.java file I call servlet2.java file.
Then it throws NullPointerException. How can I solve this?
My code like this:
index.jsp
<form action="servlet1" method="post">
servlet1.java
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
..................
..................
..................
servlet2 ob=new servlet2();
ob.doPost(request, response);
..................
..................
..................
}
Then it throws NullPointerException.
Use RequestDispatcher
RequestDispatcher rd = request.getRequestDispatcher("servlet2");
rd.forward(request,response);
RequestDispatcher
Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server.
Update
No need to create an object of servlet manually, just simply use RequestDispatcher to call servlet because web container controls the lifecycle of servlet.
From Oracle JavaEE docs Servlet Lifecycle
The lifecycle of a servlet is controlled by the container in which the servlet has been deployed.
When a request is mapped to a servlet, the container performs the following steps.
If an instance of the servlet does not exist, the web container
Loads the servlet class.
Creates an instance of the servlet class.
Initializes the servlet instance by calling the init method. Initialization is covered in Creating and Initializing a Servlet.
Invokes the service method, passing request and response objects. Service methods are discussed in Writing Service Methods.
What are you trying here,
servlet2 ob=new servlet2();
ob.doPost(request, response);
Its not necessary to create an object explicitly for a servlet, Web container creates an instance for a servlet and shares it during the app's lifetime . Though you have created an object here, it will return the existing object only.
You can is instead go for Request Dispatcher or page Redirect.
#Controller
public class CentralizedExceptionController extends DefaultHandlerExceptionResolver {
#Override
protected ModelAndView handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException ex, HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("working?!");
return new ModelAndView();
}
I have this in my code, but in case of a 404 its never called.
(I dont have an error-page defined in my web.xml, and i dont want to)
Take a look at this jira issue: https://jira.springsource.org/browse/SPR-8837?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=72648#comment-72648
If your Spring dispatcher servlet is configured to process all/most URLs, then you are probably getting the 404 error along with this DispatcherServlet log message from console:
No mapping found for HTTP request with URI [xxx]
This indicates that Spring's DispatcherServlet is processing the request but do not have an appropriate #RequestMapping to dispatch to.
A simple solution would be to limit requests processed by dispatcher servlet by reconfiguring web.xml's servlet-mapping > url-pattern to only URLs specified by your application's #RequestMappings. However, this is NOT very practical (so don't do this).
One way to overcome this would be to create a #RequestMapping that handles all "unhandled" request mappings - some kind of fallback request mapping.
#RequestMapping("**")
#ResponseBody
public String fallbackRequestMapping() {
return "do something useful...";
}
Note that this answer is similar in approach to Dani's answer but written with annotation based development in mind. Therefore, it is useful to understand the associated Spring issue.
plz check. Your controller class name should not be Controller.java.
You need to use #ExceptionHandler annotation to your method:
#ExceptionHandler(NoSuchRequestHandlingMethodException.class)
public ModelAndView handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException ex, HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
...
}
I have a HashMap of custom objects being passed to a JSP using RequestDispatcher and I am able to access the object and its properties using JSTL.
However the code fails in case the parameter is sent using response.sendRedirect() .
I am not sure what the reason is and how to make it work?
The response.sendRedirect() basically instructs the client (the webbrowser) to send a new request on the given URL. You'll also see this being reflected by a change in the browser address bar.
A new request does of course not contain the attribtues of the previous (or any other) request. That would otherwise have broken the whole concept of "request scope".
To preprocess a GET request, you need to do the job in doGet() method of a servlet and then redirect to the URL of that servlet instead.
E.g.
response.sendRedirect(request.getContextPath() + "/foo");
and
#WebServlet("/foo")
public class FooServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, Foo> foos = fooService.map();
request.setAttribute("foos", foos);
request.getRequestDispatcher("/WEB-INF/foo.jsp").forward(request, response);
}
}
Note that this problem is in no way related to having a hashmap of custom objects in the request scope.
See also:
Our servlets wiki page
You can not share a request attribute in response.sendRedirect as it creates a new request.
But, if you want that HashMap, in response.sendRedirect, you can put that in session like
request.getSession().setAttribute("myMap", [HashMap object]);
and can share between the servlet and JSP. This works in both RequestDispatcher and sendRedirect.
I have ajax calls that have the url http://localhost:80/Push/GetContacts?id=23 and the following servlet mapping:
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/GetContacts*</url-pattern>
</servlet-mapping>
The servlet does not get invoked on ajax calls. It returns a HTTP 404 not found response. What is the right URL pattern for my ajax calls?
Here is the ajax call that is not working because of the servlet.
jQuery.getJSON('http://localhost:8080/Push/GetContacts&callback=?', function(data) {
alert(data.data);
});
The servlet:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
try{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.write("{data: helloworld}");
out.close();
}
catch(Exception e){
e.printStackTrace();
}
The url pattern needs to be just /GetContacts without the star. The parameters are not part of the servlet mapping and are ignored when finding the correct servlet. If you wanted to support an URL like /GetContacts/23 you could use a servlet mapping for /GetContacts/* and retrieve the id using request.getPathInfo.
Edit: as BalusC just noticed, the url in your ajax call is incorrect. The parameter callback should be separated by a question mark, not an ampersand: GetContacts?callback=...
Also, {data: helloworld} is invalid according to the json spec, both data and helloworld should be enclosed in quotes. But that is also independent from the 404 problem.