Default Jsp in Spring mvc 4 - spring

In Spring mvc how we can set a default jsp page i.e., as soon as we run the project on server a default jsp page should show up in the browser, just like in jsf we can achieve it using below code in web.xml :
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

It is same in spring also ,
<welcome-file-list>
<welcome-file>/abc.jsp</welcome-file>
</welcome-file-list>
you can set in the web.xml.but you should have abc.jsp outside the web-inf to make it visible to the browser.
see also :
How to configure welcome file list in web.xml

While using spring also u can mention the same in web.xml
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

How about adding default controller pointing to index.jsp?
#RequestMapping(value = "/", method = GET)
public String index() {
return "index";
}
p.s. Did you specified a view resolver?

Related

Creating a route with Spring in Netbeans

I know this is a pretty basic issue, but I struggle hard with it...
I'd like to create a bunch of routes with the Spring framework in the Netbeans IDE, I have created a test #Controller class:
#Controller
public class HelloController {
#RequestMapping("/test")
public ModelAndView thisIsATest(HttpServletRequest request) {
return (new ModelAndView("myTestPage.jsp"));
}
}
myTestPage.jsp is a JSP file in the WEB-INF/jsp/ folder, and the HelloController class is in the Source Packages/ folder within a controller java package.
When I start the server, I can acces the root '/index.htm' that displays the index.jsp page (from the redirect.jsp file), but when I try to access '/test' or '/test.htm' I get a 404 error...
I really don't know how to make a Spring controller to work, and I did many tutorials without success.
In your applications web.xml make sure you have something like this. This will allow access to all your jsp pages. Add any other filters you may need here too.
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>myapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet-mapping>
<servlet-name>myapp</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
</web-app>

spring rest project with client side in angular js - how to approach the rest service with ajax

So I have a spring rest project that includes client side app.
I can run the service on a local tomcat and get responses querying "http://:8080/books" for example.
I can set app an apache server and go to "http://" to see my client app (the apache htdocs dir points to the project client app dir).
What I can't manage to do is send ajax rest queries to the service.
I'm using angular js so it looks like:
$http.get("http://:8080/books").success(...).error(...);
and it always enters the error callback method.
In the debugger/network tab I see that the request status is "canceled". Looking at the request's details I see next to the "Request headers" title the message: "CAUTION: Provisional headers are shown".
Here is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Library Application</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.library.application</param-value>
</context-param>
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>prod</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>BooksServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.library.service.config.ControllerConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>BooksServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
My project structure is:
src
main
java
resources
webapp
resources
WEB-INF
test
Is it because the origin is different (mainly the port)?
Should I add some code to my web.xml to serve the client through tomcat? If so how?
thanks.
I guess you have a problem with cross-domain requests(yes, different port is another domain for the browser and it will cancel the request for security purposes if server will not include cross-domain headers). Try to add this headers to your REST response:
responseHeaders.add("Access-Control-Allow-Origin", "*");
if you need cookies you might need this as well:
responseHeaders.add("Access-Control-Allow-Credentials", "true");
in the second case you have to set an origin, '*' will not work in this case
more info here
Angular http uses relative urls.
For example using : www.stackoverflow.com
And
$http.get('/api/search?'
would call : www.stackoverflow.com/api/search
You can tests your rest api using your browser for gets requests, and one of the many plugins for post/put/delete.
(they are jsut made up urls btw)
Found it.
Thanks for all the answers, I was looking for the spring solution.
+1 JohnnyAW for your answer.
In my controller config class I've extended WebMvcConfigurerAdapter and overridden an addResourceHandlers method pointing to my client web app dir:
#Configuration
#EnableWebMvc
#ComponentScan("com.library.service")
public class ControllerConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
Note that it works because configuration is annotated with #EnableWebMvc.

How to get a trivial case of Spring MVC view (JSP) resolving to work?

My app uses Spring MVC (latest; 3.2.2) to create a RESTful API returning JSON, and so far I haven't needed a view layer at all. But now, besides the API, I need a simple utility page (plain dynamic HTML) and wanted to use JSP for that.
I want requests to http://localhost:8080/foo/<id> to go through a controller (Java) and end up in a JSP. Should be simple, right? But I'm getting 404; something is not right in resolving the view.
HTTP ERROR 404
Problem accessing /jsp/foo.jsp. Reason:
Not Found
Controller:
#RequestMapping(value = "/foo/{id}")
public String testing(#PathVariable String id, ModelMap model) {
model.addAttribute("id", id);
return "foo";
}
Defining controllers and mapping requests works; this method gets called just fine.
Spring config:
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/jsp/" p:suffix=".jsp"/>
The problem is probably here. I've experimented with slightly different prefixes and putting the JSPs under WEB-INF, as well as stuff like <mvc:view-controller path="/*" /> but no luck yet.
(Do I even need to specify InternalResourceViewResolver, or should default view resolvers take care of this?)
JSP files. Under src/main/webapp/jsp (the project uses Maven conventions) I obviously have the JSPs.
Is there something wrong with this location?
web.xml:
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
I have browsed through Spring MVC documentation, but my problem is probably too trivial and obvious to easily find help there. :-P
Can anyone enlighten me on what I'm doing wrong?
I think what you need to do is changing
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
to
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
/* won't match if there is another folder in the path, like /jsp/foo.jsp. On the other hand / will match everything.

servlet mapping is shown as the project name on the URL. do i need ibm-web-bnd.xmi?

I have created a servlet mapping as /reskilling in my Servlet class. When I run the application the url contains the project name instead. This is a WebSphere Web application which is part of my EAR project. Do i need ibm-web-bnd.xmi to fix this?
here's my web.xml
<display-name>HibernateReskillingWeb</display-name>
<servlet>
<description>Paid Up Plan List</description>
<display-name>PaidUpPlanServlet</display-name>
<servlet-name>PaidUpPlanServlet</servlet-name>
<servlet-class>za.co.test.PaidUpPlanServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PaidUpPlanServlet</servlet-name>
<url-pattern>/reskilling</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
The erros information is shown below ...
HTTP Error Code: 404
Error Message:JSPG0036E: Failed to find resource /HibernateReskillingWeb/views/PaidUpPlan.jsp
Root Cause:java.io.FileNotFoundException: JSPG0036E: Failed to find resource /HibernateReskillingWeb/views/PaidUpPlan.jsp at com.ibm.ws.jsp.webcontainerext.AbstractJSPExtensionProcessor.findWrapper(AbstractJSPExtensionProcessor.java:395)...
What is the context root for this web application? From the error message it is HibernateReskillingWeb
If you haven't done anything to the Context Root, the default value is the Dynamic Web project's name.
You can see this value in the application.xml and you can change that to anything that you want.
Is there a directory called views under which your JSPs are stored? That is where the Container is looking for your JSP.
The servlet mapping (that you have shown) has got no role to play here as you are trying to access a JSP.
HTH

Spring MVC but without a view resolver?

is it possible to use Spring 3.1 MVC without using a view resolver?
The reason why i ask is because i simply want to build and create a Web service, not a Website so i do not need to render any JSP or html pages at all. I want to build a RESTful Web service using Spring 3.1.
Is this possible?
this is how my servlett looks like which is taken from a tutorial:
Here is my mvc-config.xml
Here is my Web.xml
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>FreedomSpring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>FreedomSpring</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.xml</param-value>
</context-param>
<welcome-file-list>
<welcome-file>
index.jsp
</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
</web-app>
And here is my controller java class that simply want to return a String from a specific http REST request and not a "ModelAndView" object so to speak
package com.jr.freedom.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class Hello {
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String helloWorldInJson() {
return "hello";
}
}
Also, How can i capture a requests Parameters that a client may send me? is that possible using springs annototations? i know that i can in previous Spring 2.x use HttpServletRequest and HttpServletResponse to get any parameters sent from a client and also return a object back to the user as well such as a JSON object.
i am just looking for a simple example that does this:
Get parameters and possibly HTTP headers from a clients Request on my controller class and map them to some Java object "example, a client sends me details of a new user object registering to my backend service(username, password etc etc) and i want to be able to map this to my Java class Called User"
Return a response of any kind of object such as a String, json or xml data to a client.
Im quite new to Spring 3.0. i did a bit of work on Spring 2.0 long ago but annotations seems the way to go now and do not know how to do it via annotations.
Thanks
Also, To execute the above controller method of helloWorldInJson() do i simply call http://localhost/FreedomSpring/hello ?
You generally use #ResponseBody for this.
See 16.3.3.5 Mapping the response body with the #ResponseBody annotation.
This bypasses the view resolver stuff altogether.
use #RestController instead of #Controller.
This page shows what you want to achieve.
You would use the #PathVariable annotation to inject parameters encoded in the url as method parameter. If the parameters are in the post or the get, then you would use #RequestParam instead.
This doc also explain how to use a view resolver to marshall your model (set by your controller) into any format.
Yes, you can do. I just created spring mvc showcase project. you can find source code here.
https://github.com/mohansaravanan/spring/tree/master/springmvc-3.2.2
You may like this project!

Resources