I followed the micronaut-servlet guide using Jetty Server and everything worked as expected (micronaut 2.0.0.M3, micronaut-servlet 1.0.0.M3).
However, for our Proof-of-Concept we need to migrate several classic HttpServlet (v3.1) based implementations to micronaut. Example:
#WebServlet(name = "Hello",
urlPatterns = {"/hello/*"},
initParams = {#WebInitParam(name = "name", value = "World")})
public class HelloServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().format("<h1>Hello %s!</h1><p>session=%s</p>",
getInitParameter("name"), request.getSession(true).getId()
).flush();
}
}
However, this is not picked up by Micronaut. Is this not supported? If not, what is the best way to migrate this to idiomatic micronaut?
#Controller
#RequestMapping(value = {"user"})
public class UserController {
...
#RequestMapping(value = {"dashboard"})
public String index(HttpServletRequest req, ModelMap map) {
this.objSession = req.getSession(false);
try {
System.out.println(this.objSession.getAttribute("userid"));
I am using Spring 4.2.
Suppose I have this class and I want to check the session object having the attribute userid=1 or not.
I am doing this checking in every methods under this "/user" request.
My query is that if I can avoid this same coding which i am doing before executing any codes of any methods.
Is there any way round to increase code resuability for checking ?
In advance thanks for your time.
You can make use of interceptors by matching the request path.
<mvc:interceptors path-matcher="/someRequest/*">
<bean class="className" autowire="constructor"/>
</mvc:interceptors>
In path-mathcer you can specify one type of url,so that it will execute whatever you require.
Controller:
#Controller
#RequestMapping(value = {"someRequest/user"})
public class UserController {
Interceptor: Before processing someRequest/user you can use a interceptor like below, in 3 ways you can use->afterCompletion ,preHandle,postHandle.
In you case code would be written in preHandle method
public class SomeRequestIntercept implements HandlerInterceptor {
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object,
Exception exception) throws Exception {
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
throws Exception {
}
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
System.out.println("before processing someRequest/**");
return true;
}
}
When I use request.getRequestDispatcher(myurl).forward(request, response) in servlet to jump to another HTML page, I find it doesn't work. A response can be seen in web browser but the page just doesn't change.
I tried response.sendRedirect(myurl) then, and it also doesn't work.
Here is my code:
public class ServletDemo extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) {
System.out.println("get");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.sendRedirect("/ForwardTest/new.html");
// request.getRequestDispatcher("/new.html").forward(request, response);
System.out.println("success");
}
}
Each time I run this, just get a "success" output in console. That means getRequestDispatcher had run, but not correctly.
I have some Spring RESTful (RestControllers) web services with no web.xml and I am using Spring boot to start the services.
I want to add authorization layer for the web services and wanted to route all the http requests to one front controller before actually calling the web service itself. (I have a code to simulate sessions behavior at the autherisation layer, to validate a user based on a generated key that I send with each of the httpRequest from the client).
Is there any Standard Spring solution on routing all the requests to a filter /front controller?
Thanks in advance,
Praneeth
Edit:
Adding my code
Controller:
`
#RestController
public class UserService {
UserDAO userDAO = new UserDAO();
#RequestMapping(value="/login", method = RequestMethod.POST)
#LoginRequired
public String login(#RequestParam(value="user_name") String userName, #RequestParam(value="password") String password, HttpServletRequest request){
return userDAO.login(userName, password);
}
}`
Interceptor:
`
public class AuthenticationInterceptor implements HandlerInterceptor {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("In Interceptor");
//return super.preHandle(request, response, handler);
return true;
}
#Override
public void postHandle( HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("---method executed---");
}
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
System.out.println("---Request Completed---");
}
}
`
Interface.
`
#Target({ElementType.METHOD, ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
public #interface LoginRequired {
}
`
Following steps can be taken to implement the interceptor with Spring:
Implement an interceptor class extending HandlerInterceptorAdapter class. Following is how the code could look like:
public class LoginInterceptor extends HandlerInterceptorAdapter {
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception)
throws Exception {
// TODO Auto-generated method stub
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
// TODO Auto-generated method stub
}
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod) handler;
String emailAddress = request.getParameter("emailaddress");
String password = request.getParameter("password");
if(StringUtils.isEmpty(emailAddress) || StringUtils.containsWhitespace(emailAddress) ||
StringUtils.isEmpty(password) || StringUtils.containsWhitespace(password)) {
throw new Exception("Invalid User Id or Password. Please try again.");
}
return true;
}
}
Implement an AppConfig class or add the addInterceptors in one of the existing Configuration class. Note the path pattern specified with the LoginInterceptor instance
#Configuration
public class AppConfig extends WebMvcConfigurerAdapter {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/account/login");
}
}
Implement the controller method such as following:
#Controller
#RequestMapping("/account/login")
public class LoginController {
#RequestMapping(method = RequestMethod.GET)
public String login() {
return "login";
}
}
here an example of Interceptor :
public class AuthenticationInterceptor implements HandlerInterceptor {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
HandlerMethod handlerMethod = (HandlerMethod) handler;
LoginRequired loginRequired = handlerMethod.getMethod().getAnnotation(LoginRequired.class);
if (loginRequired == null) {
return true;
}
String token = httpServletRequest.getParameter("token");
if (StringUtils.isBlank(token)) {
throw new MissingParameterException();
}
authenticationService.checkToken(token);
return super.preHandle(httpServletRequest, httpServletResponse, handler);
}
#Override
public void postHandle( HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("---method executed---");
}
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
System.out.println("---Request Completed---");
}
We can create an annotation :
#Target({ElementType.METHOD, ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
public #interface LoginRequired {
}
And then on controller, we had this annotation :
#RequestMapping(value = "/protected/controller")
#LoginRequired
public ResponseEntity<BaseResponse> controller() {
...
}
This is just a template/example to give you an idea.
I hope this will help you.
There is a default solution for such things.
spring security. And you will just have to implement something like:
#Configuration
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.usernameParameter("email")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.permitAll();
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
}
the dependency for it is:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
After Spring 5 :
Implementation should be like this: We should have a class that implements
HandlerInterceptor
public class CustomInterceptor implements HandlerInterceptorr{
}
Then we can register this interceptor by a class that implements WebMvcConfigurer
and override the method addInterceptors
public class ServiceInterceptorAppConfig implements WebMvcConfigurer {
#Autowired
CustomInterceptor customInterceptor;
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(customInterceptor);
}
}
You should add this to regsiter your interceptor
#Configuration
public class MyConfiguration extends WebMvcConfigurerAdapter {
#Bean
AuthenticationInterceptor getAuthenticationInterceptor() {
return new AuthenticationInterceptor();
}
#Override
public void addInterceptors (InterceptorRegistry registry) {
registry.addInterceptor(getAuthenticationInterceptor());
}
}
If you looking for simple answer for spring boot application..
public class HttpInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// do something here.
return true;
}
}
and
#Configuration
public class AppConfig implements WebMvcConfigurer {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HttpInterceptor());
// registry.addInterceptor(new HttpInterceptor()).addPathPatterns("/account/login"); you can add specific end point as well.
}
}
I have a servlet which performs various business logic. I want to avoid synchronisation like this:
#Override
protected void doGet(final HttpServletRequest _req, final HttpServletResponse _resp) throws ServletException, IOException {
synchronized (MyServlet.class) {
various();
calls();
and_logic(_req, _resp);
}
}
by making all called methods static and enforcing it like this:
#Override
protected void doGet(final HttpServletRequest _req, final HttpServletResponse _resp) throws ServletException, IOException {
_doGet(_req, _resp);
}
private static void _doGet(final HttpServletRequest _req, final HttpServletResponse _resp) throws ServletException, IOException {
various();
calls();
and_logic(_req, _resp);
}
I won't use any static variables and all my method calls are assumed to be thread-safe. Are there any non-obvious drawbacks?
I won't use any static variables and all my method calls are assumed to be thread-safe.
Under these conditions neither you don't need synchronization nor static methods. Just use instance methods of a servlet or some other service class.