how to get Spring MVC in intellij to run HTML - java

I have a basic spring MVC project (the basic mold they create) and am trying to get it to run a html instead of a JSP (JSP works perfect)
my controller
#Controller
#RequestMapping("/")
public class HelloController {
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("message", "Hello world!");
return "index";
}
}
my mvc dispatcher service
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.springapp.mvc"/>
<!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
<!--<property name="prefix" value="/WEB-INF/pages/"/>-->
<!--<property name="suffix" value=""/>-->
<!--</bean>-->
<mvc:resources mapping="/WEB-INF/pages/" location="/WEB-INF/pages/" />
I've tried numerous things, such as mapping to /WEB-INF/pages/** , removing the InternalResourceViewResolver completely (W/ the previous mappings,) leaving the suffix empty, with html, etc but to no avail. I've looked at the other questions similar to this but no luck. Also read about static folder for the htmls, but was confused... What am I doing wrong?
the file structure for webpages
webapp
--WEB-INF
----pages
------hello.jsp, index.html

<mvc:resources mapping="/WEB-INF/pages/" location="/WEB-INF/pages/" />
Mapping value stands for URL mapping. So give here for example "/pages/**"
<mvc:resources mapping="/pages/**" location="/WEB-INF/pages/" />
Now you can access to static files like html page by localhost:8080/app/pages/index.html for example.
In Java Controller instead of return "index"; there should be return "redirect:/pages/index.html";
Read this example to get all detailed informations. Hope i could help.

Related

Java Spring-MVC application doesn't send CSS and JS files. Error 404

Problem is common, I've tried a lot of solutions but nothing works for me.
I am quite new in Spring so I may not understand some things.
I've got next files structure:
My link inside page is templated by Thymeleaf like this:
<link rel="stylesheet" th:href="#{css/bootstrap.css}" type="text/css"/>
Also, there is attribute in head of html.
Ok, and my spring-context.xml is:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--to pick up all annotation in the package-->
<context:component-scan base-package="langquiz"/>
<mvc:annotation-driven />
<mvc:resources mapping="/css/**" location="/css/"/>
</beans>
I've tried some manipulations with mapping (like writing location="/templates/css/" or location="css/"), also tried resource handler in configuration class. But nothing helps.
Thank you!
UPD:
Changed
<mvc:resources mapping="/css/**" location="/css/"/>
to
<mvc:resources mapping="/css/**" location="/templates/"/>
and also tried
<mvc:resources mapping="/css/**" location="/"/>
but still have no result.
Use
<mvc:resources mapping="/css/**" location="/templates/css/"/>
Or adding a resource handler,
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/templates/css/");
}
}
Your mapping is incorrect in which location should include your templates directory as well as shown below:
<mvc:resources mapping="/css/**" location="/templates/css/"/>
You can refer here from the spring doc on this:
For example, to serve resource requests with a URL pattern of
/resources/ from a public-resources directory within the web
application root you would use:
<mvc:resources mapping="/resources/**" location="/public-resources/"/>
Changed to to make it work.
Still wondering if there is a way to see web site not on http://localhost:8080/project-name-snapshot but on http://localhost:8080

How to correctly configure a static resource handler into a Spring application?

I am pretty new in Spring and I have the following problem.
In a tutorial I found this configuration class example:
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = { "com.mycompany.myproject.web.controller" })
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
.................
..............
}
How exactly works the addResourceHandlers() method in the previous code snippet? Looking on the official documentation it seems to understand that it add handlers to serve static resources such as images, js, and, css files from specific locations under web application root, the classpath, and others.
In the previous case it is used to add static resources related to Twitter BootStrap framework (something like CSS files and JavaScript files).
The problem is that the project on which I am working don't use Java configuration but use XML configuration and I have some problem to understand how can I do the same thing of the previous code snippet into my XML configuration.
In particular I have a servlet-context.xml file that contains the MVC configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="it.hp.miur" />
</beans:beans>
I think that I have to put this configuration into this file but I don't know how do it. Can you help me?
Tnx

Spring 4 MVC REST (json response) - works on localhost, getting “Circular view path” on deployed host

I've created a simple Spring-based web application, with a #RestController annotation for a class that one of its mappings returns a JSON response.
It works perfectly when I run it on localhost, but I get the following error when I try to call the url on the host it is deployed to (Bluemix). I got this exception on the localhost version, when I didn't define the class as #RestController (or it's parallel - #Controller & #ResponseBody):
'Exception thrown by application class 'org.springframework.web.servlet.view.InternalResourceView.prepareForRendering:205'
javax.servlet.ServletException: Circular view path [nextStep]: would dispatch back to the current handler URL [/nextStep] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)'
These are my definitions:
RestController
#Controller
#ResponseBody
public class InterviewRESTController {
#Autowired
private transient InterviewFlowLogic interviewFlowLogic;
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/nextStep")
public ServiceRESTResponse nextStep(#RequestParam(value="name", defaultValue="World") String name){
return new ServiceRESTResponse(counter.incrementAndGet(),
String.format(template, name));
}
}
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="il.intervyo.client.controller"></context:component-scan>
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="defaultContentType" value="application/xml" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
</map>
</property>
</bean>
</beans>
Again, it is important to stress out that this code works when I run it localhost and the url returns the Json format response, but fails only on the deployed version - I saw the few questions-and-answers that are already on the site, non of them refers to this specific issue.
I'd gladly supply with any additional info needed (pom.xml, web.xml, etc.)

How to properly return an image in the response in Spring app?

I 'm using Spring 3.0.1.RELEASE for my webapp (and i have no way for upgrading it) and i'm trying to render some images from database on web-page.
I have following simple Spring configs:
spring-application.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<task:annotation-driven />
<context:annotation-config />
<context:spring-configured />
<context:component-scan base-package="com.me" />
<bean id="hibernateSessionFactory" class="com.me.dbaccess.HibernateSessionFactory">
<constructor-arg ref="sessionFactory"/>
</bean>
</beans>
spring-mvc.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven/>
<bean id="tilesViewResolver" class="com.me.util.TilesExposingBeansViewResolver">
<property name="viewClass" value="com.me.util.TilesExposingBeansView"/>
<property name="exposeContextBeansAsAttributes" value="true"/>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/config/tiles-defs.xml</value>
</list>
</property>
</bean>
</beans>
I have following controller:
#Controller
public class PhotoController {
#RequestMapping("/carPhoto.html")
#ResponseBody
public byte[] getCarPhoto(
#RequestParam(UrlParameters.PHOTO_ID) Integer photoId,
#RequestParam(UrlParameters.PHOTO_TYPE) String photoType) {
//return image's bytes array from db by photo Id and Type;
}
}
And finally, I have simple jsp-page:
<%#page contentType="text/html; charset=utf-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<img id="photoImage" src="<c:url value="/carPhoto.html?photoType=1&photoId=22556793"/>" />
If I open this page - I can see this image without any problems.
But if I copy image "src" attribute and paste it in browser's address bar (Firefox 19.0.2) - then browser offers me to save carPhoto.html, instead of just render the image.
Should I perform some additional setup?
The problem is, that you have to specify the mime type (and if your image is larger you will need to specify its length too).
An other solution () is to return a Spring ResponseEntity or HttpEntity (HttpEntity is enough if you always return http status code 200, ResponseEntity (a subclass of HttpEntity) is for example needed if you want to return other http status codes, like not found).
#Controller
public class PhotoController {
#RequestMapping("/carPhoto.html")
#ResponseBody
public HttpEntity<byte[]> getCarPhoto(
#RequestParam(UrlParameters.PHOTO_ID) Integer photoId,
#RequestParam(UrlParameters.PHOTO_TYPE) String photoType) {
byte[] image = image's bytes array from db by photo Id and Type;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG); //or what ever type it is
headers.setContentLength(image.length);
return new HttpEntity<byte[]>(image, headers);
}
}
There are several ways. Easiest is to use #ResponseBody with a byte[] as your return type, set your Content-Type and such, the write the bytes to the output stream using the HttpServletResponse.
A more elegant solution (IMO) would be to return a ModelAndView, then set the View on that to a custom view that sets the proper headers (Content-Type and such) and writes out the bytes to the HttpServletResponse's output stream.

Spring mvc controller issue

I'm trying to learn spring MVC, so far so good but I'm kind of stuck now. I'm trying to learn how to create json and get it with javascript(jquery).
But for testing purposes I tried to create something just so I can see that is displayed properly trough http request, then I'll try to create json and get it, but so far I can't even get the request to work. Here is my controller :
#Controller
#RequestMapping(value="/")
public class IndexController {
#RequestMapping(method=RequestMethod.GET)
public String index() {
return "index";
}
Map<Long,Item> itemMap = createItemMap();
#RequestMapping(value="item/{itemId}", method=RequestMethod.GET)
public #ResponseBody Item get(#PathVariable Long itemId) {
Item item = itemMap.get(itemId);
if (status == null) {
throw new ResourceNotFoundException(itemId);
}
return item;
}
private Map<Long,Item> createItemMap(){
//omitted because its irrelevant
//I created 2 item objects , with id 1 and 2 for testing purposes
}
}
This is content of my servlet-context.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<!-- Imports user-defined #Controller beans that process client requests -->
<beans:import resource="controllers.xml" />
</beans:beans>
And controllers.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Scans within the base package of the application for #Components to configure as beans -->
<context:component-scan base-package="com.testing.mvc.controller" />
<!-- Application Message Bundle -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages/messages" />
<property name="cacheSeconds" value="0" />
</bean>
</beans>
My war is called Test.war, when I try localhost:8080/Test I get index view which is OK. But regardless of what I try:
localhost:8080/Test/item/1
localhost:8080/Test/item?itemId=1
localhost:8080/item?itemId=1
I end up with some kind of error, the most interesting is this one :
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ().
I've googled alot found these to be interesting :
http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/
https://src.springframework.org/svn/spring-samples/mvc-ajax/trunk/
Mapping restful ajax requests to spring
Spring's Json not being resolved with appropriate response
Nothing helped so far, any idea what I'm missing. Sorry for providing too much info.
As far as I can tell you are missing this resolver like this in your dispatcher serlet:
<bean name="jsonViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="order" value="1"/>
</bean>
Take look at this:
http://spring-json.sourceforge.net/quick_simpleform.html
You have to create file views.xml in yoru WEB-INF direcotry with this content:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView"/>
</beans>

Categories

Resources