Tuesday, December 5, 2017

Spring Annotations



CREATING SIMPLE SPRING PROJECT[JAVA CONFIGURATION]

STEP1 : ADD DEPENDENCIES



groupId :org.springframework
spring-core
${spring.version}
spring-webmvc
<!-- cglib required for @configuration annotation -->
cglib:cglib\



STEP 2  : CREATE BEAN CLASS

PROPERTY + CONSTRUTOR + GETTER /SETTERS  



STEP 3  : CREATE CONFIGURTAION CLASS




@Configuration
public class ApplicationConfiguration {
@Bean(name="countryObj")
public Country getCountry()
{
  return new Country("India");

}  

STEP 4  : CREATE MAIN CLASS

public class SpringJavaConfigMain {
public static void main(String[] args) {
ApplicationContext appContext = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
  Country countryObj = (Country) appContext.getBean("countryObj");
  String countryName=countryObj.getCountryName();
  
  System.out.println("Country name: "+ countryName);


}

SCOPES

_______________________________________________________________________

public static void main(String[] args) {
  
ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
  Country countryObj1 = (Country) appContext.getBean("country");
  countryObj1.setCountryName("India");
  System.out.println("Country Name:"+countryObj1.getCountryName());
  
  //getBean called second time
  Country countryObj2 = (Country) appContext.getBean("country");
  System.out.println("Country Name:"+countryObj2.getCountryName());

}


APPLICATIONCONTEXTAWARE

public static void main(String[] args) {
  ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
  Country countryObj = (Country) appContext.getBean("country");

  System.out.println("Capital Name:"+countryObj.getCapitalName("capital"));


SPRING MVC : JAVA BASED
_______________________________________________________________________

Step 1 :Add Dependencies
spring-core |spring-webmvc

javax.servlet-api
jstl junit
Step 2 :Add Plugins
Maven plugins
maven-compiler-plugin

maven-war-plugin



Step 3 :Create Configuration 

@EnableWebMvc
@ComponentScan(basePackages = "com.example")
public class SpringConfig extends WebMvcConfigurerAdapter{
   
    @Bean
    public ViewResolver viewResolver() {@Configuration
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/pages/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

Step 4 :Create Configuration for replacing web.xml
public class WebServletConfiguration implements WebApplicationInitializer{
    public void onStartup(ServletContext ctx) throws ServletException {
        AnnotationConfigWebApplicationContext webCtx = new AnnotationConfigWebApplicationContext();
        webCtx.register(SpringConfig.class);
        webCtx.setServletContext(ctx);
        ServletRegistration.Dynamic servlet = ctx.addServlet("dispatcher", new DispatcherServlet(webCtx));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }

}

Step 5 :Create Controller


7) Create a package named “org.arpit.java2blog.springmvc.controller”
@Controller
public class GreetController {
    @RequestMapping(path= "/greet/{name}",method=RequestMethod.GET)    
    public String greet(@PathVariable String name, ModelMap model){
        String greet =" Hello !!!" + name + " How are You?";
        model.addAttribute("greet", greet);
        System.out.println(greet);
        return "greet";
    }
}

Step 6 :Create jsp to show message

Step 7: Hit the URL 

http://localhost:8080/SpringWebExample/greet/shamik

References

https://dzone.com/articles/spring-mvc-and-java-based-configuration-1
http://websystique.com/springmvc/spring-4-mvc-helloworld-tutorial-annotation-javaconfig-full-example/

MVC Annotations & concepts _______________________________________________________________________
http://localhost:8080/ProjectName/countries

@RequestMapping - Annotations


@RestController
@RequestMapping(value = "/countries")
public class CountryController {
@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public Country addCountry(@RequestBody Country country) {
  return countryService.addCountry(country);
}
@RequestMapping(method = RequestMethod.PUT, headers = "Accept=application/json")
public Country updateCountry(@RequestBody Country country) {
  return countryService.updateCountry(country);
}
}
____________________________________________



ModelMap object is used to pass multiple values from Spring MVC controller to JSP .

Some basics about Spring MVC ModelMap class:

  • ModelMap class subclasses LinkedHashMap. It add some methods for convenience.
  • It provides addAttribute method to put key value pair. This method return ModelMap objects that can be used for chaining.
  • ModelMap uses as generics.
  • ModelMap checks for null values.




@RequestMapping("/helloworld")
public String hello(ModelMap map) {
  String helloWorldMessage = "Hello world from java2blog!";
  String welcomeMessage = "Welcome to  java2blog!";
  map.addAttribute("helloMessage", helloWorldMessage);
  map.addAttribute("welcomeMessage", welcomeMessage);
  
  return "hello";
}

<body>
${helloMessage}
<br/>
${welcomeMessage}
</body>



_____________________________________________________

MULTIACTION CONTROLLER

This the expected method struture

public (ModelAndView | Map | String | void) actionName(HttpServletRequest request, HttpServletResponse response, [,HttpSession] [,AnyObject]);
_____________________________________________________
@Controller
public class PayeeController {


private static final Logger logger = Logger.getLogger(HelloWorldController.class);
@RequestMapping("/payee/add.htm")
public ModelAndView add(HttpServletRequest request,
  HttpServletResponse response) throws Exception {
logger.info("This is info message");
logger.error("This is error message");

  return new ModelAndView("payee", "message", "Payee Added");
}


@RequestMapping("/payee/delete.htm")
public ModelAndView delete(HttpServletRequest request,
  HttpServletResponse response) throws Exception {
  return new ModelAndView("payee", "message", "Payee Deleted");
}
_____________________________________________________

@MODELATTRIBUTE ANNOTATION'

@ModelAttribute is used to bind request parameters with model object.  Lets say you have 10 request parameters , you can wrap them to model object and pass it in the to handler method.
 
@Controller
public class CountryController {
 
@ModelAttribute
public Country getCountry(@RequestParam String countryName, @RequestParam  long population)
{
  Country country=new Country();
  country.setCountryName(countryName);
  country.setPopulation(population);
  return country;
}
@RequestMapping(value = "/addCountry", method = RequestMethod.POST)
public String addCountry(@ModelAttribute Country country,ModelMap model) {
  model.addAttribute("countryName", country.getCountryName());
  model.addAttribute("population", country.getPopulation());
  return "countryDetails";
}
}

<h3>Country Name: ${countryName}</h3>
<h3>Population : ${population}</h3>
_____________________________________________________






_______________________________________________________________________
SPRING ANNOTATIONS
_______________________________________________________________________

DEPEDNDENCIES
spring-webmvc

@RequestMapping("/helloworld")

return new ModelAndView("hello", "message", helloWorldMessage);

This means populate the ${message} property in help.jsp with value of helloWorldMessage



<body>
${message}
</body>



@Component
public class Country {
 //this syntax is used to read a String from the property file
@Value("${countryName}")
private String countryName;



https://java2blog.com/spring-boot-hello-world-standalone-application/

.
@SpringBootApplication = @Configuration+ @EnableAutoConfiguration +@EnableWebMVC+@ComponentScan
Normally you would add @EnableWebMvc for a Spring MVC application, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath.

@ComponentScan: scans
components, configurations, and services in the default package, .

@Autowired
@Qualifier("country")
Country countryBean;
public static void main(String[] args)
{
SpringApplication.run(SpringBootHelloWorldStandaloneApplication.class, args);  
}
_______________________________________________________________________




Create Restful web services using Spring Boot


________________________________________________________________________________






























Create Restful web services using Spring Boot

________________________________________________________________________________


















Spring Security

________________________________________________________________________________

@EnableWebSecurity annotation is used to enable spring security for this webapp.
authroizeRequest().addMatchers() method is used 
to configure pattern for request.
For example: If http request url has pattern /hello*(hello.jsp,helloworld.html), it will be accessed to ROLE_ADMIN only.
We have hardcoded username(java2blog) and password(java123)   using inMemoryAuthentication(), so if user provides correct credential for admin then only he will be able to access helloworld.html.


@Configuration
@EnableWebSecurity
public class WebSecurityConfiguaration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
     http.authorizeRequests()
.antMatchers("/hello*").access("hasRole('ROLE_ADMIN')").and().formLogin();;
    }
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
     auth.inMemoryAuthentication().withUser("java2blog").password("java123").roles("ADMIN");
    }
}

No comments:

Post a Comment