I am new to Java and spring.I need to know how we can achieve URL rewriting in Java and Spring. For example in .NET environment we can achieve this by using following code:
Global.asax.cs:
protected void Application_BeginRequest(object sender, EventArgs e) {
try {
string fullOrigionalpath = Request.Url.ToString();
if (fullOrigionalpath.Contains("/Home-Page")) {
Context.RewritePath("~/home.aspx"); return;
}
}
}
Similarly,we need to achieve in Java and Spring.
Can we have anything related to this in Java and Spring?
If we cannot do using above code,How we can achieve URL Rewriting?
Help would be appreciated.
I would recommend using OCPsoft Rewrite (beta) or OCPsoft PrettyFaces (final), which are newer and more evolved tools for doing Java Servlet URL-rewriting.
Rewrite also has support for your tuckey configuration, if you want to take advantage of your existing configuration, and add in more powerful Java-based Rewrite configuration.
It is very stable and well tested.
package com.example;
public class ExampleConfigurationProvider extends HttpConfigurationProvider
{
#Override
public int priority()
{
return 10;
}
#Override
public Configuration getConfiguration(final ServletContext context)
{
return ConfigurationBuilder.begin()
.defineRule()
.when(Direction.isInbound().and(Path.matches("/some/{page}/.*/")))
.perform(Redirect.permanent("/new-{page}/"));
}
}
If you're using Spring >= 3, you can use #RequestMapping. See the official documentation
Related
I'm inquiring about the need to proceed with the development of Spring boot 1.X version, but one part is blocked.
I use Embedded Tomcat, so I have to register with #Bean for ErrorReportValue.
I'm working on moving 400 Bad Request to Custom Error page, but I found a way.
However, they are classes that can be applied from Spring 2.X or higher, so they are not applied to Spring 1.4 version.
The replaceable code was similar but failed. What are some ways to get that function to 1.4 as well?
If you look at the code below, there are codes available from Spring 2.X and above. "TomcatWebSocketServletWebServerCustomizer" and "TomcatServletWebServerFactory" .
Because of these two codes, it is not possible to proceed in version 1.X. It would be nice to upgrade the version, but it will be difficult due to the circumstances.
Among the replaceable codes, "TomcatWebSocketContainerCustomizer" and "Tomcat EmbeddedServletContainerFactory" were available, but were not compatible with "StandardHost".
Help me.
Thank you.
#Bean
public TomcatWebSocketServletWebServerCustomizer errorValveCustomizer() {
return new TomcatWebSocketServletWebServerCustomizer() {
#Override
public void customize(TomcatServletWebServerFactory factory) {
factory.addContextCustomizers((context) -> {
Container parent = context.getParent();
if (parent instanceof StandardHost) {
((StandardHost) parent).setErrorReportValveClass("com.java.lmh.errors.CustomError");
}
});
}
#Override
public int getOrder() {
return 100; // needs to be AFTER the one configured with TomcatWebServerFactoryCustomizer
}
};
}
}
In my Java app that based on Spring Boot, I am trying to implement a caching mechanism for the following service method:
#Override
public List<EmployeeDTO> findAllByCountry(Country country) {
final Map<Pair<UUID, String>, List<CountryTranslatable>> valueList
= countryRepository...
// code omitted for brevity
}
After several examples regarding to this issue, I decided on the approach mentioned on A Guide To Caching in Spring.
However, I am a little bit confused as it contains Spring and Spring Boot implementations and uses different annotation examples. I think I should start from 3.1. Using Spring Boot section as I use Spring Boot, but I am not sure about which Caching Annotation I should use (4.1. #Cacheable seems to be ok but I am not sure).
So, where should I put SimpleCacheCustomizer and how can I apply that approach for my service method above (findAllByCountry)? Any simple example would really be appreciated as I am new in Spring.
You don't need any customizations if you are a starter, and you want only the basics then do the following
#Configuration
#EnableCaching
public class CachingConfig {
#Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager();
}
}
The provided article states, return new ConcurrentMapCacheManager("addresses"); but you can use the default constructor and the relevant cache for adresses will be created later with #Cacheable("addresses"). So no need for this to be in configuration.
You also need
#Cacheable("employeesList")
#Override
public List<EmployeeDTO> findAllByCountry(Country country) {
final Map<Pair<UUID, String>, List<CountryTranslatable>> valueList
= countryRepository...
// code omitted for brevity
}
ready to go, that is the basic setup
If you want to customize the autoconfigured cachemanager then only you should implement CacheManagerCustomizer interface.
In usual cases you don't need to customize the autoconfigured cachemanager. The example has been given in the link you attached.
Your understanding on the cacheable annotation is also correct and it should work fine for you.
You can put that component class with other classes in the component scan range.
You should put your SimpleCacheCustomizer along with your others Spring configuration class. That way, your component will be scanned and loaded by Spring.
#Component
public class SimpleCacheCustomizer
implements CacheManagerCustomizer<ConcurrentMapCacheManager> {
#Override
public void customize(ConcurrentMapCacheManager cacheManager) {
cacheManager.setCacheNames(asList("employeesList", "otherCacheName"));
}
}
To use the cache with your service, add the annotation #Cacheable("employeesList")
#Cacheable("employeesList")
#Override
public List<EmployeeDTO> findAllByCountry(Country country) {
final Map<Pair<UUID, String>, List<CountryTranslatable>> valueList
= countryRepository...
// code omitted for brevity
}
If you want to verify the cache is working, just enable sql_query in your Spring configuration and check that findAllByCountry is no longer making any request to the DB.
To use jamon in spring, it's described to use JamonPerformanceMonitorInterceptor and put it to springs AOP-mechanism via a applicationContext.xml. It's explained, and there's an example within the tests in it's sources. Unfortunately, I want to build a spring-boot application without any xml-configuration.
Is it possible to use some annotations to include the JamonPerformanceMonitorInterceptor to spring?
Better late than never...
I had the very same situation: I needed to configure JAMon without any XML configuration. Most of the examples online (including the comments in the JAMon source code) advertise XML configuration flexibility, but I couldn't find any examples with annotation based configuration. Also annotation-based configs are not necessarily less flexible, they just need to be conceptually separated and not confused with functional parts of the application. I think such advisor can be a good example:
#Component
public class MonitoringAdvisor extends AbstractPointcutAdvisor {
private final StaticMethodMatcherPointcut pointcut = new StaticMethodMatcherPointcut() {
#Override
public boolean matches(Method method, Class<?> targetClass) {
return targetClass.isAnnotationPresent(RestController.class);
}
};
#Override
public Pointcut getPointcut() {
return this.pointcut;
}
#Override
public Advice getAdvice() {
return new JamonPerformanceMonitorInterceptor(true, true);
}
}
This advisor would let Spring/AOP know to run JAMon monitoring advice on any method of Spring bean annotated with #RestContrller. This advisor should be configured/added to the same Spring context as rest controllers.
Note, that in my case I specifically wanted to monitor my rest controllers. One can adapt the advisor according to his/her own needs. (In my code I use a more advanced/configurable version of the presented advisor)
Is this Spring Boot sample application helpful?
Here is the relevant part of the Spring AOP manual.
How may I secure single eventhandlers by annotations?
I know how to secure Complete pages, but i have no idea how to check before invocation if a a method has an annotation.
Is this possible?
I dont want to use Spring-security
Thanks
ChenillKit access is a nice module.
There is also the tapestry-security module based on the security framework Apache Shiro which provides annotation like
#RequiresPermissions("news:delete")
public void onActionFromDeleteNews(EventContext eventContext) {
...
}
With the Chenillekit access module you can use the #Restricted annotation on an Event method as well like so:
#Restricted(role = YOUR_ROLE_CONSTANT)
#OnEvent(value="eventName")
private Object handleEvent() throws Exception {
... your event code ....
}
In order to get GWT RequestFactory running with Grails, I am using the following approach:
class GwtController extends RequestFactoryServlet {
public GwtController() {
super()
}
def index = {
doPost request, response
}
#Override
public ServletContext getServletContext() {
return ServletContextHolder.servletContext
}
#Override
public ServletConfig getServletConfig() {
return new DummyServletConfig(getServletContext(),"grails");
}
}
where DummyServletConfig is a simple implementation of ServletConfig
This is working when deploying the app to tomcat. However, using testing or development mode, it is not. I was required to adjust the GWT Servlet in order to prevent it from using the wrong Class Loader:
In line 46 I changed
private static final RequestFactoryInterfaceValidator validator =
new RequestFactoryInterfaceValidator(log,
new RequestFactoryInterfaceValidator.ClassLoaderLoader(
ServiceLayer.class.getClassLoader()));
to
private static final RequestFactoryInterfaceValidator validator = new RequestFactoryInterfaceValidator(
log, new RequestFactoryInterfaceValidator.ClassLoaderLoader(
Thread.currentThread()
.getContextClassLoader()));
Otherwise, it wouldn't find my Domain classes (which apparently do not reside in the GrailsRootLoader but in the Thread's class loader).
Now I would like to revert my GWT servlet to the official binary released by Google and I wonder how I can fix the incorrect ClassLoader in Grails or make the RequestFactoryServlet work correctly without altering the GWT source.
I hope that GWT 2.3 will fix your problem:
http://code.google.com/p/google-web-toolkit/issues/detail?id=6092