In my UI code, i have a link to a css stylesheet with href="url for spring controller".
I want the Spring Controller to return the CSS file which the UI page uses for styling.
First i was wondering, if this was even possible?, and secondly what the Spring Controller needs to return? Do i need to return a byte[] representation of the css file and put it in a ResponseEntity, or use some kind of outputstream on the Servlet response?
Something like?
#RequestMapping(value = "/getCSS/{userId}", method= RequestMethod.GET, produces={"text/css"})
#ResponseStatus(HttpStatus.OK)
public ??? getCSS(){
}
The UI code and Spring app which has the controller are not part of the same project.
Different users have different stylings, and the Spring app, gets the users css file from a database. Therefore, the css file cannot simply be put into the /static folder or /resources folder as there will be different css files for different users.
You can put static resources (if they don't have to be secured) in your webapp folder. For example webapp/static/style.css
Your can get this file with : localhost:8080/applicationName/static/style.css
controler
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class WebController {
#RequestMapping(value = "/staticPage", method = RequestMethod.GET)
public String redirect() {
return "redirect:/static/final.css";
}
}
Webservlet.xml
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/static/" />
<property name="suffix" value=".css" />
</bean>
<mvc:resources mapping="/static/**" location="/WEB-INF/static/" />
<mvc:annotation-driven/>
Also you can return page like html,jsp
if the resources are in different project you can store the name of that project in applicationContext and refer to it like this from your view ${applicationScope.resourcesProject} like this
<link href="/${applicationScope.resourcesProject}/resources/css/style.css" rel="stylesheet" type="text/css"/>
Related
I have successfully deployed my spring boot sample web application to App Engine Standard (Java 8). This applications has some jsp pages. But i am getting blank page instead of my orginal page. And also not getting any errors.
My index page controller is
#RequestMapping(value = "/", method = RequestMethod.GET)
public String showIndexPage(Model model,HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException
{
return "index";
}
index.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<title>Index</title>
</head>
<body>
<p>Welcome</p>
</body>
</html>
application.propertoes
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
This is the documentation i have done.
https://github.com/GoogleCloudPlatform/getting-started-java/tree/master/appengine-standard-java8/springboot-appengine-standard
Any suggession?
EDIT
But /hello is working fine
#RestController
public class HelloworldController {
#GetMapping("/hello")
public String hello() {
return "Hello world - springboot-appengine-standard!";
}
}
Without being anything close to spring-boot expert, I suspect 2 things:
1: You're using #RequestMapping where most examples (some that I just tried) use #GetMapping instead. If I'm not mistaken using #RequestMapping means you'll need to define #ResponseBody as well.
2: To serve static files with GAE you'll need to include that in the appengine-web.xml too as mentioned here under <static-files>:
A sample:
<static-files>
<include path="/my_static-files" >
<http-header name="Access-Control-Allow-Origin"
value="http://example.org" />
</include>
</static-files>
GAE seems to be working fine ans serving requests as expected. It's either your spring-boot config or appengine-web.xml
I have webproject which has images inside src/main/webapp folder. I would like to place images in different folder on the disk. But I have no idea how to manage requests to reach this images.
Should I create some kind of httpServlet like shown here: http://balusc.omnifaces.org/2007/07/fileservlet.html
Or as I use Spring MVC with java configuration, there is more suitable and simpler way.
Looking forward for your suggestions.
Use the spring mvc support for static resources, its location attribute is an Spring Resource, so you could use file: prefix
<resources mapping="/resources/**" location="file:/my/external/directory/" />
or
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("file:/my/external/directory/");
}
}
#See Spring Reference Chapter 6.4 The ResourceLoader for a table that list all prefixed for resources
In my case I placed js and css resources in webapp and images in e://images/.
For this case I use two mvc:resources mapping
<mvc:resources mapping="/resources/**" location="/resources/"/>
<mvc:resources mapping="/images/**" location="file:e://images/"/>
And locate the image of e: > images > abc.jpg using ....
<img src="../images/abc.jpg"/>
You could try also <img src="/images/abc.jpg"/> or <img src="images/abc.jpg"> (If not work)
The css/js linked under webapp > resources > js > xyz.js like below.
<script type='text/javascript' src='../resources/js/xyz.js'></script>
You canimplement WebMvcConfigurer in your main Application or Main class.
#SpringBootApplication
#ComponentScan("com.your.package.controller")
#Configuration
public class ServicesApplication implements WebMvcConfigurer { // ServicesApplication is my main class
String your_drive_location = "file:///D:/upload_dir/upload/"; // my file path
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations(your_drive_location );
}
public static void main(String[] args) {
SpringApplication.run(ServicesApplication.class, args);
}
}
I am using JSTL for showing:
<c:forEach items="${ListOfBrand}" var="brand"> // ListOfBrand is a Map
<img src=" <c:out value="/images/"/>${brand.brand_image}" /> // Showing all image from brand table
</c:forEach>
I want to have references on my welcomePage.jsp page to other jsp pages - loginPage.jsp and registerPage.jsp. I tried to use simple like this:
<head>
<title>${title}</title>
</head>
<body>
<jsp:include page="header.jsp"/>
<jsp:include page="_menu.jsp" />
<h1>Welcome to the page!</h1>
Register
<p>or</p>
Log In
<p>if you already have an account</p>
<jsp:include page="footer.jsp"/>
</body>
</html>
But I keep getting HTTP Status 404 The requested resource is not available.
I also tried but as a result the contents of the pages I was referencing too just apperead on this welcomePage. Although I need them to be accessible through links only.
All the mentioned files are located in WEB-INF/pages.
This is my first project with Spring MVC so any help is welcomed.
Suppose, in your configuration, you have set the location of views e.g. /WEB-INF/view/ where you put all of your .jsp files - loginpage.jsp, registerPage.jsp etc. Now, you can simply access the location of view i.e. /WEB-INF/view/ via pageContext.servletContext.contextPath.
//For example
href="${pageContext.servletContext.contextPath}/loginpage"
I suggest you to go to a controller first, than call a ModelAndView in this controller. This also keeps the relations clear between the JSP files.
To apply this your controller class should be like this:
#Controller
public class LoginPageController {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView printLoginPage() {
ModelAndView modelAndView = new ModelAndView("loginPage");
return modelAndView;
}
}
You can also pass parameters from a JSP page to another by going through a controller method.
I am new to spring. What i want is i will be having various jsp pages and i will map user request to those JSP pages.My question is "can we map user requests to jsp pages when request url and jsp names are same using spring controller mapping".I searched and not found anything.
like without writing controller
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
Maybe I mis-read the question, but if you wanted to map a URL to a JSP directly (e.g. without having to define a controller & method) then that can be done pretty easily (as you would hope)
XML config:
<mvc:view-controller path="/help-page" view-name="helpPage"/>
or if you are using Java Config (extending WebMvcConfigurerAdapter):
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/help-page").setViewName("helpPage");
}
Using either of the above, if you visit /help-page then it will render the /WEB-INF/jsp/helpPage.jsp
By default Spring MVC registeres a DefaultRequestToViewNameTranslator which will translate the request into a view name similar to your requirements.
Simply use Map as a return type and the translation commences.
Returning a Map will expose it as the model for the view.
You can also return void but you'll have to make sure no HttpServletResponse is declared as an argument.
#RequestMapping("/registration/form")
public ModelMap form(ModelMap model) {
model.addAttribute("form", new FormObject());
return model;
}
Will translate to view name: "registration/form"
I have a basic Java EE Spring (MVC) application setup that displays a home page with dynamic content. I am completely new to Spring and am confused how to proceed at this point and add more pages to my application. Do I need to create a new controller for each url on my site? Right now I have the following mapping in my ..-servlet.xml file:
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/index.html=homeController
</value>
</property>
</bean>
So if I now have a new page at /login, would I add a mapping to /login/index.html? I get even more confused because I am trying to integrate Spring-security to handle the login page...
I would take a look at annotated Controllers:
http://static.springsource.org/spring/docs/2.5.6/reference/mvc.html
http://static.springsource.org/spring/docs/2.5.6/api/org/springframework/web/bind/annotation/RequestMapping.html
Example:
#Controller
public class TestController {
#RequestMapping(value="/login/index.html")
public String login() {
return "login";
}
#RequestMapping(value="/somethingelse/index.html")
public String login() {
return "somethingelse";
}
}
When you set up your View Resolver, the Strings that are returned would correspond to to a literal page, i.e. somethingelse could be directed to /jsp/somethingelse.jsp if that's how you've set up the resolver in your Spring config. Hint...you need to scan for annotations to auto wire.
Spring-Security is handled in a somewhat similar fashion, but has nothing to do with Spring MVC per say. If done correctly, the only resource you need to provide in order to configure security is the simple login page, which you would configure in your Spring config. Check out this security example:
http://www.mularien.com/blog/2008/07/07/5-minute-guide-to-spring-security/
If you are using spring security, you don't need a controller for showing the login form. You can use any jsp page for that purpose and as spring posts it to j_spring_secutity_check, you don't need a controller to handle it too. Check the spring documentation how you can add multiple methods in controller, You may need to use the beanNmaeMapping kind of configuration. Also the better way now is using annotation based config, which helps you configure any pojo as controller with #Controller annotation
You could use something like:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/vehicleSearch">vehicleSearchController</prop>
</props>
</property>
</bean>
If there was a file /WEB-INF/jsp/vehicleSearch.jsp it would be mapped to the vehicleSearchController. In this case JSP files are being used for the view but you could adapt it to your view technology.
Configuring it this way you would still need to write a mapping for every file. A better way (as Teja suggested) is probably to annotate the mappings in your controller and do away with the XML configuration.
e.g.
#Controller
#RequestMapping("/vehicleSearch")
public class VehicleSearchController {