Showing posts with label spring boot. Show all posts
Showing posts with label spring boot. Show all posts

Wednesday, January 26, 2022

How to make spring controller Get request on controller









Let's begin dilsecodie  

Spring Web model-view-controller (MVC) framework

Get code example from - dilsecodie

Step 1: GOTO spring MVC section, find spring controller 
Step 2:  use code in your class, which you want to make the class a controller.
Step 3: In @RequestMapping value means request URL endpoint, changes its values as per your requirement.
Step4: before step 3 check, the class uses @controller and spring dependency.
Step5: @ModelAttribute is used for getting request parameters from URL.
Step6: Make service in the controller according to business logic, then return model view.
Step7: Modelview means  view you need to show model output in HTML page (or JSP page)
Step8: Controller can also call another controller can see in example return showData(); 
, as showData(); method calls another controller then model view return.


let's understand the working of the spring controller,
First request come to dispatcher servlet in web.xml file 
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
then spring created the objects which are mentioned in xml file 
<context:component-scan base-package= Mention your folder which containes 
all the files .
<context:exclude-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
</context:component-scan> 
use this tag will scan your controller which provide correct controller 
for request end point 

These property need to define in applicationContext.xml file 

<mvc:annotation-driven />  also its tag is one of important tag bcoz 
its autowired your all beans 

<property name="packagesToScan" value="com.your.packages"></property> 
its also used for all files scan so spring container can provide you object of bean

So when spring provide request a correct controller Then 
Controller class should have @Controller define in it .
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

these packages of spring should be import in your class .

For get request handle using GET method 
@RequestMapping(value={"getDilsecodieUserData"}, 
method={org.springframework.web.bind.annotation.RequestMethod.GET})
public ModelAndView getDilsecodieGetData
(HttpServletRequest request,HttpSession session){
ModelAndView mv = new ModelAndView("dilsecodie/index");
Write your service to implement business logic , and add model object 
return mv;
 }

For post request handler using post method 

@RequestMapping(value={"askquestionsdilsecodie"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
ModelAndView askquestionDilsecodie(HttpServletRequest req, HttpSession session) 
throws CustomException{

String value1= req.getParameter("value1");

String value2= req.getParameter("value2");

String value3= req.getParameter("value3");
ModelAndView mv1 = new ModelAndView("dilsecodie/dashboard");
Write your service to implement business logic , and add model object 
return mv1;
 }
 @RequestMapping("sendStringvalue")
@ResponseBody
String saveShortlisting(HttpServletRequest req, HttpServletResponse res){
msg = "success";
return msg;
}
@RequestMapping("sendStringvalue")
@ResponseBody
String saveStories(HttpServletRequest req, HttpServletResponse res){
msg = "success";
return msg;
}

If needed to handle any type of request both post or get request then use 

@RequestMapping("updateInterviewStatus")
ModelAndView updateStatus(HttpServletRequest req, HttpServletResponse res){
ModelAndView mv3 = new ModelAndView("dilsecodie/das");
Write your service to implement business logic , and add model object 
return mv3;
}





Tuesday, January 25, 2022

How to configure Spring Boot Jdbc template





Let's begin, open dilsecodie GOTO: 
Step1: First do add Maven Spring JdbcTemplate dependency in the pom.xml file. 

Step2: Then check the example given by dilsecodie

Step3: JDBC template used same as JDBC, you can write the custom query, use other methods also like map, list, object[], get the class object in list etc.

Step4: You can use in any service by doing @Autowired JdbcTemplate JDBC;


you can use to make a complete CRUD flow, write SQL sentences, some wrappers, and you get it, a complete and functional persistence layer.

Lets see some explaintion for JDBC with spring boot .

 either through an xml file,database fetching and storing is then further abstracted away behind an interface called a Repository .
first need to package in your Impl class 
import org.springframework.jdbc.core.JdbcTemplate;
this package bascially provide you JDBC class object which you need to autowire in your class
@Autowired
JdbcTemplate jdbc; - this reference variable used in object.
for select example 
public List<Map<String, Object>> getselectdata1() {
String sql = "SELECT DISTINCT l1id , name FROM Dilsecodie ";
List<Map<String, Object>> rows = jdbc.queryForList(sql);
return rows;
}
It will provide you data as shown in query and output stored in list form 

Important point to be note database connection will be same as in datasource 

Lets see how to insert data using jdbc templete 
public Boolean insertFromUser(UserQueryForsetVal uq) {
jdbc.update("INSERT INTO userDilsecodiequery(userid, userloginid,t1,t2,t3,
                 queryasked,queryurl,ExpertList) VALUES(?,?,?,?,?,?,?,?)", uq.getUserid(),
uq.getUserloginid(), uq.gett1(), uq.gett2(),
                      uq.gett3(), uq.getQueryasked(),uq.getQueryurl(),uq.getExpertList());
return true;
}
this above example give you an idea about insert query can insert your data can you this example 
and modify as per your requirement .

Now if required to update your recored then  lets understand by exmaple 
public void updateUserQueryStatus(Integer refId, Integer status) {
String sql = "UPDATE userDilsecodiequery SET status = " + status +
                 " WHERE refid = " + refId;
jdbc.execute(sql);
}

For integer - class query example
public int getalluser() {
int username =1 ;
String sql = "SELECT COUNT(expert_email) as count FROM alluserdilsecodie WHERE is_approved=1  ";

int count = this.jdbc.queryForObject(sql, Integer.class);
System.out.println("get count of "+count);
return count ;
} -  above example can be used in retutn integer value in Impl logic , and also used in number values stored in integer object.
So basically jdbc provide you to make query according to your need , we also write any type of join in query
as can check in example jdbc.execute your query 
JDBC can handle your connections by it self .




Note*: Still having Problem, can ask in doubt section.

Saturday, January 22, 2022

How to make testing cases using Selenium scripts






Step1: open dilsecodie
Click on the login button present in my account of yourwebsite.com
Check you are able to do testing on the login button to get scripts from the selenium section.

Testing Importance 
Testing importance for project bug fixing or related issues.
Automation testing done by selenium scripts.
Selenium can also check code standards, which also helps in audit security points.

Some Test scripts we can use.
Demonstration on a few parameters of @Test annotation as shown below. <br>

package demo test; 

import org.testing.Reporter;

import org.testng.annotations.Test; 

public class DemoA { 
--- its 1st case for testing priority wise 
@Test(priority=1, groups={"user", "smoke"}) 

public void CreateUser(){ 

Reporter.log("CreateUser", true); 

--- its 2nd case for testing priority wise enabled as true 
@Test(priority=2, invocationCount=1, enabled=true, groups={"user"}) 

public void editUser(){

Reporter.log("editUser", true); 


@Test(priority=3, groups={"user"}) 

public void deleteUser(){ 

Reporter.log("deleteUser", true); 

}

@Test(priority=1, groups={"product", "smoke"}) 

public void createProduct(){ 

Reporter.log("createProduct", true);


@Test(priority=2, invocationCount=1, enabled=true, groups={"product"}) 

public void editProduct(){ 

Reporter.log("editProduct", true); 


@Test(priority=3, groups={"product"}) 

public void deleteProduct(){ 

Reporter.log("deleteProduct", true); 

} }

This program demonstrates Upcasting concept (FirefoxDriver class object to WebDriver interface) and accessing various methods of the WebDriver interface

package qspiders; 

import org.openqa.selenium.WebDriver; 

import org.openqa.selenium.firefox.FirefoxDriver;

public class UpcastingToWebDriver_LaunchBrowser { 

 
Parameterisation using @DataProviders

1. DataProvider is an annotation in testng using which we can create data bank.

2. THis databank can used across any testng class , thus achieiving data parameterisation.

Executing the same script with multiple sets of data is called data parameterisation.

From Testng Class by creating our own data bank using DataProvider annotation

From Testng class

1. We use DataProvider annotation to create the data bank,

2. We utilise this data from any testng methods by using

"dataProvider" parameter as an argument to "Test" annotation.

code :

package scripts;

import org.testing.Reporter;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

public class DataProviderExample{

@DataProvider

public Object[][] dataBank(){

Object[][] data = new Object[2][2];

data[0][0] = "admin1";

For another web element:


What is a WebElement? 

1. Any element present on a web page is called a web element. 

2. Developers use HTLM code to develop web pages. 

3. For testing purposes, we can also create a web page using HTML code. 

4. In order to create a web page, we need to write HTML code in any text pad (eg : notepad and save the file with .html extension) 

Create a sample web page using HTML as mentioned below. 
<html> 
<body> 
UN : <input type="text" id = "username" value = "admin"> 

PWD: <input type="text" id= "pass" value = "manager"> 

< a href="http://dilsecodie:8080/login.do"> Click Link</a> 

In the above HTML tree, every element should have one of the 3 options. 

1. Tagname (this is mandatory for all the elements) 
2. Attributes (Optional) 
3. Text (Optional) 
Example of Tagname in the above HTML Tree structure: 

 HTML, 
 body, 
input, 
 a 
Example of Attributes in the above HTML Tree structure: 

 type = "text" 

 id = “username” 

value = "admin" 

Format : attributeName = "attributeValue"

Example of Text in the above HTML Tree structure: 
  

How to upload Multiple Image From jsp page .






 step 1 :  open dilsecodie

 step 2: copy code in controller from spring boot section to upload multiple images from UI 

 step3: Map MultipartFile from the JSP page.

step 4: form submit from JSP to the controller with the same name as mentioned in the controller parameter. 

When there is a problem uploading multiple images, from multiple parts sending to the controller to upload file 

When there is a problem uploading multiple images, 

from multiple parts sending to the controller to upload file .


suppose when we are uploading multiple images submit from form using jsp pages ,

so enctype="multipart/form-data" in form declare html tag to data sended to 

multipart using method="post" so send data in post method .


but we need to declare type="file" name="myfile" id="myfile" accept="image/*" multiple="multiple" 

input field with these tag in it , so doc engine aware about data .


after submitting to controller

@RequestMapping(value = "/yourenpoint", method = RequestMethod.POST)- your controller 

should be like this to receive request from jsp pages .


 ModelAndView getAddMultipleImagesUplaoded(HttpServletRequest request ,@RequestParam("myfile") 

MultipartFile[] file ,@RequestParam("myfile2") MultipartFile[] file2 ,

@RequestParam("myfile3") MultipartFile[] file3 ,@RequestParam("myfile4") 

MultipartFile[] file4 , @RequestParam("myfile5") MultipartFile[] file5 )


this example shows you how can we upload multiple images from a single input field,

as we can see right now taken only 5 fields each having multiple images data in it.


MultipartFile is a class is which provided by springframework.core package extend InputStreamSource 

class to achieve the read method from it.

you don't have to make this class as you just need an object of this class in your controller.


After this now let's see how we can achieve its values , we can simply use 

for (int i=1; i < 6; i++) { loop as per our requirement , in example you can see that 

we need only 5 multiple parts for now.

To stop duplicate we can manage simple logic by using if(i==1)

filepath = SaveFile(file);

if(i==2)

filepath = SaveFile(file2);

if(i==3)

filepath = SaveFile(file3);

if(i==4)filepath = SaveFile(file4);

if(i==5)filepath = SaveFile(file5);

SaveFile is just a custom method to upload file in location or folder .

SaveFile(MultipartFile[] file - this method you can need to pass file 

After all this read file 

for(int i=0;i<file.length;i++)

  {

  if(file!=null && file[i].getSize()>0){

  String checkfile =file[i].getOriginalFilename();

  InputStream fileInputStream = null;

  if(checkfile != null || checkfile != ""){

  try {

  fileInputStream = file[i].getInputStream();

  } catch (IOException e1) {

  // TODO Auto-generated catch block

  e1.printStackTrace();

  }


These are snippets of code to get file.

After this save file to location 

String path = filePath + "/" + flName;

File saveFile = new File(path); try {

Files.copy(fileInputStream, saveFile.toPath(), 

StandardCopyOption.REPLACE_EXISTING);

 } catch (IOException e) {


another way can make directory also , to save file in that location

File theDir = new File(filePath);

if (!theDir.exists()) {

 boolean result = false;

  try{

theDir.mkdirs();

result = true; - this variable will show you uploaded status .

fileCreationStatus=false; this variable we use to check wether filecreated or not 

 } 

 

How to Implement Spring security Method in Spring Boot






    step 1. open dilsecodie.com .

    step 2 . Make config class in your spring boot project .

    step 3: Make class Security Config extends WebSecurityConfigurerAdapter

    step 4 ; check spring security dependency 

    step 5 : copy code from dilsecodie https://dilsecodie.com/sourcecode/topic/Spring-   Boot/tutorial/Spring-                  security

    step 6: paste in your class checks all pages your need in security.

    step 7: check your security will run, or you may customize according to your project 

    step 8 : still have an issue then ask doubt in ask question, section get an answer from an expert. 

     lets me example you for spring security its core part of spring which can be implemented by using         some import packages :

import org.spring framework.boot.autoconfigure.EnableAutoConfiguration; - for enable autoconfig 

using spring in it ,

security.crypto.bcrypt.BCryptPasswordEncoder; is used to decrypt the password submitted by the user end.

@EnableWebSecurity this annotation is used to enable auto security feature in your security class when using embedded. packages.

SecurityConfig extends WebSecurityConfigurerAdapter if suppose your security config is your class then its extends Web security method in your security class,  

protected void configure(HttpSecurity HTTP) using this method in your security class provide you HTTP method with so to develop security method for it.


then in your security class use http.csrf().disable().authorizeRequests() - for .antMatchers( ) pass all the endpoints which you need to secure , so that these URL cant be access without login auth.

.antMatchers(adminService.getAllAccess().toString()).authenticated()  - this line most important bcoz when we use its provide all access  auth case .

when any user login then request first handled by spring security like .successHandler(customSuccessHandler) - these methods use customsuccesshandler class to valid-user, if so then only sessionid will be provided to that request.

if any request failed to authenticate then that case will be .failureHandler(customFailureHanler) - which means the custom failure handler class will provide an invalid token and a custom message to request..

But when we implement spring security in our project then any URL cant be accessed from any request it needed cross from spring security which means then how to access the index page to start the application in that case we use .loginPage(Constants.INDEX_PAGE).permitAll()  - this method provides all permit to index page without any validation process.


Now will talk about success part after that session will be provided for that user., but we need to check every request having valid session or not  that an be done by using invalid session URL method  for ex :invalidSessionUrl(Constants.SESSION_EXPIRED).sessionFixation().migrateSession().and().httpBasi()

but we need to implement .deleteCookies("JSESSIONID") - delete cookies method to delete jsessionid also after any invalid session or session expire .