spring bean - inject Context Base URL in property - spring-mvc

On Spring 3, I got a bean in my applicationContext.xml with this definition :
<bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties">
<property name="service" value="http://www.mysite.com/my_webapp/j_spring_cas_security_check"/>
<property name="sendRenew" value="false"/>
</bean>
Instead of
"value="http://www.mysite.com/my_webapp/j_spring_cas_security_check"
Is there a way to directly and dynamically inject the "base URL" of my tomcat server + j_spring_cas_security_check
( like we can do in a jsp to set :
<base href="<%=request.getScheme() + "://" + request.getServerName()+ ":" + request.getServerPort() + request.getContextPath()+ "/"%>" />
)

Try this:
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<spring:url value="/j_spring_cas_security_check" var="baseUrl" />
<base href="${baseUrl}" />
spring:url evaluates the URL "/j_spring_cas_security_check" relative to your application path and stores it in baseUrl variable. After this, you can replace ${baseUrl} in your JSP.
It's recommended not to use base tag. Instead, you should have relative paths but this is up to you.
Hope it helps.

Related

No mapping found for HTTP request with URI [/demoApp/add] in DispatcherServlet with name 'newApp'

No mapping found for HTTP request with URI [/demoApp/index.jsp] in DispatcherServlet with name 'newApp'
I am getting this error please help.I am using Tomcat v9.0 server.
index.jsp
<html>
<body>
<form action="add">
<input type="text" name="t1"><br>
<input type="text" name="t2"><br>
<input type="submit"><br>
</form>
</body>
</html>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>newApp</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>newApp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
newApp-servlet.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:ctx="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd ">
<mvc:annotation-driven />
<ctx:annotation-config></ctx:annotation-config>
<ctx:component-scan base-package="com.newApp"></ctx:component-scan>
</beans>
AddController.java
package com.newApp;
import java.lang.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class AddController {
#RequestMapping("/add")
public void add()
{
System.out.println("I am good");
}
}
program should print "I am good" on the console but it is showing error on browser "The origin server did not find a current representation for the target resource or is not willing to disclose that one exists."
on the console it is showing "No mapping found for HTTP request with URI [/demoApp/add] in DispatcherServlet with name 'newApp'".
This error accures when i click on submit button on jsp page.
If you want to use view technology like jsp.
You could add bean definition of InternalResourceViewResolver class into your spring configuration file
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
see official docs
I got the same issue and resolved it.
Please add missing folder src/main/java [add package name (for example: com.dev) while adding a class] and then add the java class in that instead of src/main/resource folder. This is the culprit. Let me know for any issue at parixitk28#gmail.com.

How to supply hiveconf variable from hive oozie action

I want to supply variable as hiveconf namespace from my hive-oozie action, how to do that?
<action name="setupAct">
<hive xmlns="uri:oozie:hive-action:0.2">
<job-tracker>maprfs:///</job-tracker>
<name-node>maprfs:///</name-node>
<script>
XYZ.hql
</script>
<!--how to add variable to hiveconf-->
<param>DB_NAME=test</param>
</hive>
<ok to="ok" />
<error to="error" />
</action>
The values inside param element are supplied as --hivevar namespace to hive.
Below is application log, the param element gets added as hivevar:
------------------------
DB_NAME=test
------------------------
Hive command arguments :
--hivevar
DB_NAME=test
-f
test.hql
For hiveconf in Oozie, Use the configuration element.
<hive xmlns="uri:oozie:hive-action:0.2">
<job-tracker>maprfs:///</job-tracker>
<name-node>maprfs:///</name-node>
<script>
XYZ.hql
</script>
<!--how to add variable to hiveconf-->
<configuration>
<property>
<name>hive.default.fileformat</name>
<value>Parquet</value>
</property>
</configuration>
<param>DB_NAME=test</param>
</hive>

Spring mvc: css does not work when adding slash at the end of URL

I am new to Spring MVC and i am having a problem with CSS. When the URL ends with slash CSS does not work.
link goes like this
<link rel="stylesheet" href="themes/style.css">
mvc:resources mapping
<mvc:resources mapping="/themes/**" location="/WEB-INF/themes/"/>
and requestMapping goes like this
#RequestMapping("/login")
public ModelAndView loginPage() {
ModelAndView model = new ModelAndView("login");
return model;
}
So the problem is when i enter a URL like ../login the css loads normally, but when i enter ../login/ with ending slash, then the css does not load.
Well there are many similar questions in here, but none of them is for Spring MVC.
Instead of
<link rel="stylesheet" href="themes/style.css">
try this:
<link rel="stylesheet" href="/themes/style.css">
When you use href="themes/style.css" then for url like: .../login/ the request url for css file looks like:
.../login/themes/style.css
which is incorrect. When you use href="/themes/style.css" then it always should result with:
.../themes/style.css
Update:
If it is jsp page, then add
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> on top of the page
and change:
<link rel="stylesheet" href="themes/style.css">
into
<link rel="stylesheet" href="<c:url value="/themes/style.css" />">
it will work 100%
step 1
<mvc:resources location="/WEB-INF/assets/" mapping="/resources/**"></mvc:resources>
setp 2
<spring:url var="css" value="/resources/css/"/>
<spring:url var="js" value="/resources/js/"/>
<spring:url var="image" value="/resources/image/"/>
add a slash after value
step 3
add your style sheet like this
<link rel="stylesheet"
href="${css}/common/bootstrap.min.css">

sec:authorize and sec:authentication annotations don't work

I have a Spring + Thymeleaf project with the following view code.
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring3-3.dtd">
<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Contacts</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div id="content">
<h1>Welcome to the site!</h1>
<p th:if="${loginError}">Wrong user or password</p>
<form th:action="#{/j_spring_security_check}" method="post">
<label for="j_username">Email address</label>:
<input type="text" id="j_username" name="j_username"/> <br/>
<label for="j_password">Password</label>:
<input type="password" id="j_password" name="j_password"/> <br/>
<input type="submit" value="Log in"/>
</form>
</div>
<div sec:authorize="isAuthenticated()">
User: <span sec:authentication="name">miquel</span>
</div>
</body>
</html>
The sec:authorize and sec:authentication attributes don't work as expected - the div is always shown, even if no user is logged in, and the span always reads "miquel".
Follows a relevant snippet from my controller class.
#RequestMapping(value = "/welcome.html")
public String wellcome() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
System.out.println("username: " + auth.getName());
return "home";
}
The println statement works as expected - if no user is logged in, it prints "anonymousUser", otherwise the username.
What am I doing wrong?
After comparing my application closely to the Thymeleaf & Spring Security demo applicaiton, I discovered the source of the error.
Apparently, in order for Thymeleaf to process the sec:authorize and sec:authentication attributes, you need to register SpringSecurityDialect as an additional dialect of the template engine bean.
<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
<property name="additionalDialects">
<set>
<bean class="org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect" />
</set>
</property>
</bean>
This is surprising as there is no mention of that fact on the related Thymeleaf documentation page. I hope this helps others who will face the same issue in future.
In Spring Boot I just had to add the following dependency:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
For the java config version, it worked for me too by adding the spring security dialect:
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.addDialect(new TilesDialect());
templateEngine.addDialect(new SpringSecurityDialect());
return templateEngine;
}
Also, you may wish to clear the template cache after an authentication event, so your template is re-processed with new authentication data. Or, set the templates which are sensitive to a login session to non-cached (this is what I did), using ServletContextTemplateResolver.setNonCacheablePatterns().

Spring MVC Static Resources partially work

I have a basic directory app that works fine except that it seems to only sometimes find the static resources that I’ve configured using the mvc:resources tag. My search of the board found problems related to handler mappings, but my problem seems to be different.
Specifically, when the PersonController is called via a method mapping to “/person”, it returns personlist.jsp using the view resolver and correctly finds and uses the static css and js files. No problems.
When the same controller is called via another method mapping to “/person/{familyid}” ( narrows the person list to a particular family), it returns the same personlist.jsp…but now it fails to find or use the css and js files (though it does display the correct data).
I don’t understand why there is a behavior difference since both scenarios use the same Controller, the same return String (return “personlist”), and resolve to the same JSP (ie. with the same Head section links for the css, js).
I looked at what came back in the browser for each case using ‘view source’, and both pages return the same head tag rendering for the css and js linking:
<link href="resources/css/directory.css" rel="stylesheet" type="text/css"></link>
<script type="text/javascript" src="resources/scripts/jquery-1.7.min.js"></script>
<script type="text/javascript" src="resources/scripts/directory.js"></script>
I thought the problem could be with my tag mapping, so I also tried this:
<resources mapping="**/resources/**" and
resources mapping="resources/**"
but no help.
Am I approaching the use of static resources properly here (and what is the right resources tag mapping if that’s the problem)? Thanks.
I am using Spring 3.0.6 and my css and js files are located under /WebContent/resources/css and /WebContent/resources/scripts respectively, which are mapped using the mvc:resource tag (see below).
PersonController:
#Controller
public class PersonController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
List<Person> personList;
Boolean familyCalled = false;
#Autowired
PersonService personService;
#RequestMapping(value="/people", method=RequestMethod.GET)
public String people(Model model) {
logger.debug("Received request to show peoplelist page");
System.out.println("Running inside people() method of PersonController");
personList = personService.getPersons();
familyCalled = false;
model.addAttribute("personList", personList);
return "personlist";
}
#RequestMapping(value="/people/{familyId}", method=RequestMethod.GET)
public String familyMembers(#PathVariable("familyId") String fid, Model model) {
System.out.println("Running inside familyMembers() method of PersonController");
personList = personService.getPersonsInFamily(fid);
familyCalled = true;
model.addAttribute("personList", personList);
return "personlist";
}
Servlet-Context.xml (without namespaces):
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- for transactions -->
<tx:annotation-driven/>
<!-- Needed for #PreAuthorize security on methods -->
<aop:aspectj-autoproxy/>
<context:annotation-config />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="resources/" />
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven/>
<!-- 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="com.c3works.preps" />
</beans:beans>
personlist.jsp (Head section):
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</meta>
<title>XXXXXXXXXXXXXXXXXXX</title>
<link href="resources/css/directory.css" rel="stylesheet" type="text/css">
</link>
<script type="text/javascript" src="resources/scripts/jquery-1.7.min.js">
</script>
<script type="text/javascript" src="resources/scripts/directory.js">
</script>
</head>
Your URLs are relative and therefore the browser is looking for the resources in the wrong place. (Check the resulting HTML code)
One solution is to use the <spring:url> tag to build the urls of the resources.
<spring:url var="banner" value="/resources/images/banner-graphic.png" />
<img src="${banner}" />

Resources