<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Eren Sönmez on Medium]]></title>
        <description><![CDATA[Stories by Eren Sönmez on Medium]]></description>
        <link>https://medium.com/@snmzern00?source=rss-91aac06c5f99------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uaPDIxY2-lJiSjlf3byCvQ.jpeg</url>
            <title>Stories by Eren Sönmez on Medium</title>
            <link>https://medium.com/@snmzern00?source=rss-91aac06c5f99------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:25:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@snmzern00/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Refactoring Node.js File Uploads: From Local Storage to AWS S3 with Typescript]]></title>
            <link>https://medium.com/@snmzern00/refactoring-node-js-file-uploads-from-local-storage-to-aws-s3-with-typescript-a05af2626caa?source=rss-91aac06c5f99------2</link>
            <guid isPermaLink="false">https://medium.com/p/a05af2626caa</guid>
            <category><![CDATA[multer]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[cloud-storage]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Eren Sönmez]]></dc:creator>
            <pubDate>Wed, 22 Oct 2025 15:30:15 GMT</pubDate>
            <atom:updated>2025-10-22T15:30:15.307Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*aHz1fB5m622bQAdYbmacxA.png" /></figure><p>Recently, I’ve been working on a project that requires uploading and fetching images and icons for both a mobile app and a web application. The backend serves as a bridge between these platforms, and all data updates made on the web instantly reflect on the mobile app. Among these dynamic data types, some include files such as images and icons.</p><p>Initially, I handled file uploads using Multer, a handy middleware for handling file uploads in<strong> Node.js</strong>. Multer can store files on disk, in memory or even in cloud services. At first, I decided to store uploaded files locally on disk to quickly demonstrate how the system works to users.</p><p>I created a <strong>TypeScript </strong>utility that defined folders and configured <strong>Multer’s </strong>disk storage. The<a href="https://www.npmjs.com/package/multer"> <strong>Multer npm page</strong></a> provides detailed usage documentation for reference.</p><p>Each uploaded file was stored in folders named after its parent record’s unique identifier, keeping the folder structure organized. This approach worked well for small datasets. <strong>However</strong>, as the number of files grew,<strong> from around 50 to more than 500</strong>, and since these files had to be fetched in different ways and from multiple platforms, <strong>disk storage became inefficient</strong>. That’s when I decided to refactor the file upload logic from local storage to cloud storage for better <strong>reliability</strong> and <strong>performance</strong>.</p><h4>Choosing AWS S3</h4><p>After realizing the scalability issues, it was time to choose a cloud storage provider. I decided to use AWS S3, though other services like Azure or Google Cloud Storage could also work.</p><p>To start, you need an <strong>AWS root account</strong>. After setting up pricing and billing, the first step is to create a new S3 bucket. Buckets act as containers where your files are stored. Each object in S3 is accessible via a URL, which can later be used through presigned URLs.</p><p><strong>It’s not recommended to use your root account</strong>. Instead, create an IAM user, assign permissions and policies to access the bucket and generate access and secret keys. These credentials will be used by your backend to interact securely with AWS.</p><h4>Backend Configuration</h4><p>Since I’m using Node.js and TypeScript, I had already installed Multer earlier but those local storage packages are not needed for cloud storage. Luckily, <strong>npm</strong> provides packages that are needed. Instead of using Multer, we are going to use <strong>Multer’s S3 Client</strong> to access S3 service.</p><pre>npm install -save multer-s3 @aws-sdk/client-s3<br>npm install dotenv</pre><p>Create a <strong>.env file to store your access credentials securely</strong> when the installation is completed. After then create a <strong>env.ts</strong> file for the <strong>type safety</strong> and get your credentials from environment file.</p><pre>import dotenv from &quot;dotenv&quot;;<br>dotenv.config();<br><br>export const AWS = {<br>  S3_ACCESS_KEY: process.env.S3_ACCESS_KEY || &quot;&quot;,<br>  S3_SECRET_ACCESS_KEY: process.env.S3_SECRET_ACCESS_KEY || &quot;&quot;,<br>  S3_REGION: process.env.S3_REGION || &quot;&quot;,<br>  BUCKET_NAME: process.env.BUCKET_NAME || &quot;&quot;<br>};</pre><p>I also declared a global interface for these variables in index.d.ts:</p><pre>declare namespace NodeJS {<br>  interface AmazonEnv {<br>    S3_ACCESS_KEY: string;<br>    S3_SECRET_ACCESS_KEY: string;<br>    S3_REGION: string;<br>    BUCKET_NAME: string;<br>  }<br>}</pre><h4>Creating the S3 Client</h4><p>Now that we have our credentials, we can configure a <strong>reusable</strong> <strong>S3 client</strong> to access the bucket and AWS services.</p><pre>import { AWS } from &quot;./env&quot;;<br>import { S3Client } from &quot;@aws-sdk/client-s3&quot;;<br><br>const amazonService = new S3Client({<br>  credentials: {<br>    accessKeyId: AWS.S3_ACCESS_KEY,<br>    secretAccessKey: AWS.S3_SECRET_ACCESS_KEY<br>  },<br>  region: AWS.S3_REGION<br>});<br><br>export default amazonService;</pre><h4>Multer Middleware</h4><p>Now, create a multer middleware to read, upload and configure files. There are three steps to handle multer easily:</p><ol><li>Configure your storage options.</li><li>Add filters to set image types.</li><li>Upload the files using Multer.</li></ol><pre>const filesS3Storage = multerS3({<br>  s3: amazonService,<br>  bucket: AWS.BUCKET_NAME,<br>  acl: “private”,<br>  contentType: multerS3.AUTO_CONTENT_TYPE,<br>  key: (<br>    req: Request &amp; { body: { _id: string } },<br>    file: Express.Multer.File,<br>    cb: (errorr: any, key?. string) =&gt; void) =&gt; {<br>      const filename = req.body.filename;<br>      const folder = “images”;<br>      cb(null, `${folder}/${filename}`)}, <br>});</pre><p>Here’s a breakdown of the storage configuration steps:</p><ul><li>Declare S3 client to access AWS service</li><li>Declare bucket to tell files where they’ll be stored</li><li>Give access type as acl</li><li>Content types of files</li><li>Key to store in database</li><li>Req to get files from request</li><li>File for function that will be used</li><li>Callback function to handle folder and file name, it’s completely customizable.</li></ul><p>Then configure which file types are going to be allowed for uploading.</p><pre>const imageFileFilter = (<br>  _req: Express.Request,<br>  file: Express.Multer.File,<br>  cb: Multer.FileFilterCallback) =&gt; {<br>    const allowedTypes = [“image/png”, “image/jpeg”, “image/jpg”]<br>    if(allowedTypes.includes(file.mimetype)) cb (null, true);<br>    else cb(new Error(“Only PNG, JPEG or JPG files are allowed”)});</pre><p>Use multer to upload files. Set storage, file filter and limit the file size.</p><pre>export const uploadImageFiles = multer({<br>  storage: filesS3Storage,<br>  fileFilter: imageFileFilter ,<br>  limits: { fileSize: 5 * 1024 * 1024 }}).single(“image”);<br><br>/** <br>  If you are going to upload multiple files, <br>  you can apply this simple change below <br>**/  <br>export const uploadImageFiles = multer({<br>  storage: filesS3Storage,<br>  fileFilter: imageFileFilter ,<br>  limits: { fileSize: 5 * 1024 * 1024 }}).<br>  fields([ <br>    {name: “profilePicture”, maxCount: 1}, <br>    {name: &quot;selfies&quot;, maxCount: 5},<br>  ]);<br></pre><h4>Writing AWS Services</h4><p>The next step is to create services that handle S3 operations such as uploading, retrieving and deleting objects. At first, some imports are needed:</p><ul><li>S3 Client and environment config</li><li>AWS request presigner to generate and verify presigned URL to handle AWS operations</li><li>Stream APIs’ Readable module to get content of bucket as chunks.</li><li>Commands from AWS SDK to handle CRUD operations.</li></ul><pre>import {<br>  PutObjectCommand,<br>  DeleteObjectCommand,<br>  ListObjectsV2Command,<br>  GetObjectCommand<br>} from &quot;@aws-sdk/client-s3&quot;;<br>import { getSignedUrl } from &quot;@aws-sdk/s3-request-presigner&quot;;<br>import amazonService from &quot;./amazonService&quot;;<br>import { AWS } from &quot;./env&quot;;</pre><h4>Generate Presigned URL</h4><p>To securely access files in private buckets, generate a presigned URL with an expiration time:</p><pre>static async getPresignedUrl(key: string, expiresIn = 3600) {<br>  const command = new GetObjectCommand({<br>  Bucket: AWS.BUCKET_NAME, // Your S3 Bucket name<br>  Key: key // Unique file path<br>  });<br><br>return await getSignedUrl(amazonService, command, { expiresIn });<br>}</pre><h4>Manual File Uploading</h4><p>Let’s pause here for a moment. We’ve just created a Multer middleware to handle file uploads, but there’s an <strong>important</strong> distinction to make.</p><p>In this implementation, we are using<strong> Multer-S3</strong>, <strong>not the default Multer</strong>. The difference is that Multer-S3 automatically handles the file buffer and the key generation process, then <strong>uploads the file directly to the S3 bucket</strong> under the hood using the AWS SDK’s PutObjectCommand.</p><p><strong>However, if you’re not using Multer-S3</strong> and want to handle the upload manually, you can do it through a service function like the one below:</p><pre><br>// Upload a file manually to S3 using AWS SDK<br>static async uploadFile(<br>  key: string,<br>  fileBuffer: Buffer,<br>  contentType: string<br>): Promise&lt;string&gt; {<br>  const command = new PutObjectCommand({<br>    Bucket: AWS.BUCKET_NAME,<br>    Key: key,<br>    Body: fileBuffer,<br>    ContentType: contentType,<br>    ACL: &quot;private&quot;<br>  });<br>  await amazonService.send(command);<br>  return key;<br>}</pre><p>Here, `fileBuffer` contains the binary data of the file, and `contentType` specifies its MIME type. The method calls `PutObjectCommand`, which uploads the file to S3 and returns the object key, which can then be stored in your database.</p><blockquote><strong>Note: </strong>In our REST controller, <strong>we are actually using Multer-S3</strong>, so this manual method is not directly called. It is included here for if you ever decide to handle uploads without Multer-S3.</blockquote><h4>Upload File with REST Controller</h4><p>I’m going to use all our S3 service and Multer to show how file uploading can be handled in a REST controller.</p><pre>export class ImageController<br>{<br>  async saveImage(req: Request, res: Response, next: NextFunction) {<br>  try{<br>    // Get file data from form-data<br>    const file = req.file as Express.Multer.File | undefined;<br>    // Get filename<br>    const filename = req.body.filename || file?.originalname|| “unnamed”;<br>    if(!file) return res.status(400).json({ message: “No file uploaded”});<br><br>    // Set folder name and key<br>    const folder = “images”;<br>    const key = `${folder}/${filename}`;<br><br>    /** Upload key if you are not using Multer-S3 <br>    const uploadedKey = await S3Service.uploadFile(key, file.buffer, file.mimetype); **/<br>    <br>    // Multer-S3 automatically handles file buffer and mimetype<br>    const uploadedKey = file.key;<br>    const presignedUrl = await S3Service.getPresignedUrl(uploadedKey, 3600);<br>    <br>    // Return response<br>    return res.status(200).json({<br>      message: “File uploaded successfully”,<br>      key: uploadedKey,<br>      url: presignedUrl,});<br>  }catch(error) {<br>    return res.status(500).json({message: “File upload failed”, error: (error as Error).message}); }<br>}</pre><h4>Setting Up the Route</h4><p>The final step is to handle routing. I’m going to use the <strong>Express router</strong>. Set your endpoint, use our <strong>uploadImageFiles() </strong>method from Multer middleware then send results to the controller.</p><pre>import { Router } from &quot;express&quot;;<br>import { uploadImageFiles } from &quot;../middlewares/imageUploadMiddleware&quot;;<br>import { ImageController } from &quot;../controllers/imageUploadController&quot;;<br><br>const router = express.Router();<br>const controller = new ImageController();<br><br>router.post(“/upload/image”, uploadImageFiles, controller.uploadImage.bind(controller);<br><br>export default router;</pre><h4><strong>Final Thoughts</strong></h4><p>After implementing AWS S3, the backend became much more scalable and reliable. One best practice is to <strong>delete files from S3 when corresponding records are deleted</strong> from the database to avoid unnecessary storage costs.</p><p>Refactoring from disk storage to AWS S3 gave me valuable hands-on experience. I learned how to securely manage files, improve scalability, and understand the benefits of using cloud-based storage solutions over local disk systems.</p><h4>Sources:</h4><blockquote><a href="https://www.npmjs.com/package/multer-s3">multer-s3 — npm</a></blockquote><blockquote><a href="https://www.npmjs.com/package/multer">multer — npm</a></blockquote><blockquote><a href="https://www.npmjs.com/package/@aws-sdk/client-s3">@aws-sdk/client-s3 — npm</a></blockquote><p>Thanks for your reading. You can follow and get in touch with me on my <a href="https://www.linkedin.com/in/erensonmez7/">LinkedIn</a>, <a href="https://github.com/Luvienze">GitHub</a>, <a href="https://medium.com/@snmzern00">Medium</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a05af2626caa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Security for Beginners]]></title>
            <link>https://medium.com/@snmzern00/spring-security-for-beginners-c53418266075?source=rss-91aac06c5f99------2</link>
            <guid isPermaLink="false">https://medium.com/p/c53418266075</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Eren Sönmez]]></dc:creator>
            <pubDate>Wed, 08 Jan 2025 13:25:20 GMT</pubDate>
            <atom:updated>2025-01-08T13:25:20.893Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*1OdBNgxV3r9ckCfUlE6oEQ.png" /><figcaption><a href="https://dev.to/pryhmez/implementing-spring-security-6-with-spring-boot-3-a-guide-to-oauth-and-jwt-with-nimbus-for-authentication-2lhf">Spring Security</a></figcaption></figure><p>In this article, we’ll explore the basics of Spring Security. You’ll learn how to implement in-memory users, roles from a database, authentication, authorization, and endpoint security. Before we started, you can check the codes <a href="https://github.com/Luvienze/Spring-Learning">here </a>on my GitHub repository.</p><h4>What is Spring Security ?</h4><blockquote>Spring Security is a framework that provides authentication, authorization, and protection against common attacks. Essentially, it operates on a filter chain architecture. When a client sends an HTTP request, the request passes through Spring’s filter chain, where it is processed before reaching the servlet.</blockquote><p>Spring Security employs a filter chain to process requests. Each filter in the chain performs specific tasks, such as authentication or authorization, before the request is handed over to the servlet for further handling</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*Jh7j5dZBMkfsXTjV" /><figcaption>FilterChain <a href="https://docs.spring.io/spring-security/reference/servlet/architecture.html">Architecture :: Spring Security</a></figcaption></figure><h4>Get Started</h4><p>To integrate Spring Security into your project, open the Spring Initializr and add the Spring Security dependency to your Maven project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r92IMJx5NeV2y5Fh" /></figure><p>If your project was created without this dependency, you can add it manually in your pom.xml file:</p><pre><br>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>   &lt;version&gt;3.2.5&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>After adding the dependency, create a package named security and within it, a SecurityConfig class for configurations. Finally, annotate the SecurityConfig class with @Configuration.</p><h4>Authentication</h4><blockquote>Authentication is the process of determining whether someone or something is who or what they say they are. Authentication technology provides access control for systems by checking to see if a user’s credentials match the credentials in a database of authorized users or a data authenticatiın server.</blockquote><p>Once users are authenticated, you can authorize endpoints to restrict access based on your preferences. Spring Security supports two primary methods of user authentication:<strong> in-memory users</strong> and <strong>database roles</strong>.</p><p><strong>1. In-Memory Users</strong></p><p>Users can be authenticated manually/hard-coded with in-memory users. In security class, create a public method of <em>InMemoryUserDetailsManager</em>. In this method, create your own user type of<em> UserDetails</em> and use <em>User.builder () </em>to set username, password and role.</p><p>Let’s inspect the codes below. In this scenario, we have three users which have different types of roles. Each user has a username, password, role.</p><p>Password field has a<em> “noop”</em> tag before the actual password as you can see. That means passwords can consist of plain text and use no hash algorithms. There are various algorithms you can use like<em> bcrypt.</em> To keep it simple, I used <em>“noop”</em> for this example.</p><pre>@Bean<br>public InMemoryUserDetailsManager userDetailsManager(){<br>   UserDetails john = User.builder()<br>           .username(&quot;john&quot;)<br>           .password(&quot;{noop}test123&quot;)<br>           .roles(&quot;EMPLOYEE&quot;)<br>           .build();<br><br><br>   UserDetails mary = User.builder()<br>           .username(&quot;mary&quot;)<br>           .password(&quot;{noop}test123&quot;)<br>           .roles(&quot;EMPLOYEE&quot;,&quot;MANAGER&quot;)<br>           .build();<br><br><br>   UserDetails susan = User.builder()<br>           .username(&quot;susan&quot;)<br>           .password(&quot;{noop}test123&quot;)<br>           .roles(&quot;EMPLOYEE&quot;,&quot;MANAGER&quot;,&quot;ADMIN&quot;)<br>           .build();<br><br><br>   return new InMemoryUserDetailsManager(john,mary,susan);</pre><p>There are various fields you can use like <em>accountExpired, disabled, passwordEncoder</em> and more. You can find more in the article <a href="https://docs.spring.io/spring-security/reference/api/java/org/springframework/security/core/userdetails/User.UserBuilder.html">here</a>.</p><p>Spring Security supports custom roles or predefined ones like EMPLOYEE, ADMIN, MANAGER. Whether use your own roles from database or can use Spring’s own roles.</p><p>When you finish creating users, return new <em>InMemoryUserDetailsManager.</em> That’s all for creating in-memory users with Spring Security.</p><p><strong>2. Databases Role</strong></p><p>Before starting this approach, ensure your database contains the required tables for users and roles. For this example, users and roles are in different tables in my database. Let’s get started.</p><p>Create a method type of <em>UserDetailsManager </em>with a parameter type of <em>DataSource</em>.</p><blockquote><em>DataSource </em>works as a factory for providing database connections. It is an alternative to the <em>DriverManager </em>facility. A datasource uses a URL along with username/password credentials to establish the database connection.</blockquote><p>Then create an object of <em>JdbcUserDetailsManager </em>with parameter of dataSource. Next step is defining queries to retrieve users and roles. We need to retrieve users first and then, retrieve roles. After all things are settled, return <em>jdbcUserDetailsManager</em>.</p><pre>   @Bean<br>    public UserDetailsManager userDetailsManager(DataSource dataSource){<br><br>        JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager(dataSource);<br><br>        // define query to retrieve a user by a username<br>        jdbcUserDetailsManager.setUsersByUsernameQuery(<br>                &quot;select user_id, pw, active from members where user_id=?&quot;<br>        );<br><br>        // define query to retrieve the authorities/roles by username<br>        jdbcUserDetailsManager.setAuthoritiesByUsernameQuery(<br>                &quot;select user_id, role from roles where user_id=?&quot;<br>        );<br><br>        return jdbcUserDetailsManager;<br>    }</pre><h4>Authorization</h4><p>Authorization is a process by which a server determines if the client has permission to use a resource or access a file. Authorization is usually coupled with authentication so that the server has some concept of who the client is that is requesting access.</p><ol><li><strong>Security Filter Chain</strong></li></ol><blockquote><em>SecurityFilterChain </em>allows us to strict access based on roles upon url. It takes an <em>HttpSecurity</em> type of parameter and throws an exception, and also uses lambda expressions.</blockquote><p>Let’s create a <em>filterchain </em>method with a type of <em>SecurityFilterChain</em> with param of<em> HttpSecurity</em>. After creating the method, call <em>authorizeHttpReuqest() </em>method of http param and use configurer as lambda expression. In configurer, we’re going to use <em>requestMatchers() </em>method. <em>RequestMatcher </em>is a simple strategy to match an <em>HttpServletRequest</em>.</p><p>Once you call the request matcher method, rest is up to you. Configure your endpoints with roles that depend on your choice. Let’s inspect two rules in there.</p><p>Below the code, this rule allows only users with the “MANAGER” role to <strong>create a new employee</strong> via a POST request to <em>/api/employees</em>.</p><pre>.requestMatchers(HttpMethod.POST,&quot;/api/employees&quot;).hasRole(&quot;MANAGER&quot;)</pre><p>For the next code at below, this rule allows only users with the “MANAGER” role to <strong>update existing employees</strong> via PUT requests to any endpoint starting with <em>/api/employees</em>.</p><pre>.requestMatchers(HttpMethod.PUT,&quot;/api/employees/**&quot;).hasRole(&quot;MANAGER&quot;)</pre><p>After configuring endpoints, use the httpBasic method of http with defaults. Purpose of this <em>Customizer.withDefaults()</em> method is used as the assignment target for lambda expressions that we used as a configurer.</p><pre> @Bean<br>    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{<br>        http.authorizeHttpRequests(configurer -&gt;<br>                configurer<br>                        .requestMatchers(HttpMethod.GET,&quot;/api/employees&quot;).hasRole(&quot;EMPLOYEE&quot;)<br>                        .requestMatchers(HttpMethod.GET,&quot;/api/employees/**&quot;).hasRole(&quot;EMPLOYEE&quot;)<br>                        .requestMatchers(HttpMethod.POST,&quot;/api/employees&quot;).hasRole(&quot;MANAGER&quot;)<br>                        .requestMatchers(HttpMethod.PUT,&quot;/api/employees/**&quot;).hasRole(&quot;MANAGER&quot;)<br>                        .requestMatchers(HttpMethod.DELETE,&quot;/api/employees/**&quot;).hasRole(&quot;ADMIN&quot;)<br>                );<br><br>        // use HTTP basic authentication<br><br>        http.httpBasic(Customizer.withDefaults());<br><br>        // disable Cross Site Request Forgery (CSRF)<br>        // in general, not required for stateless REST API&#39;s that use POST,PUT,DELETE and/or PATCH<br>        http.csrf(csrf -&gt; csrf.disable());<br><br>        return http.build();<br>    }</pre><h4>CSRF</h4><blockquote><em>Cross-Site Request Forgery</em>, also known as one-click attack or session riding and abbreviated as CSRF, is a type of malicious exploit of a website or web application where unauthorized commands are submitted form a user that the web application trusts. To prevent this attack, call csrf method of http and use csrf as lambda expression and basically call the disable method and it’s done. It’s not required for stateless REST API’s that use POST, PUT, DELETE and/or PATCH.</blockquote><p>You can find more about CSRF on the resources at the end of this post. To complete the method, return <em>http.build()</em> method. This method returns a security filter chain.</p><p><strong>2. Addition to Filter Chain</strong></p><p>As long as the most part of this code is the same as the previous example, there are some additions. First, let’s look at the configurer. There’s a method we called <em>anyRequest().authenticated()</em> means that all urls are allowed by any authenticated user. Non authorized users cannot access all the other endpoints in our application.</p><p>Basically <em>formLogin</em> is configuration for login process. First, call the<em> loginPage()</em> to define login page form. Then call <em>loginProcessingUrl()</em> to validate username and password with the given url. With <em>permitAll()</em>, grant the access.</p><p><em>.logout</em> is used to direct the page to logout. Use logout lambda expression and call<em> permitAll() </em>method then it’s finished.</p><p><em>.exceptionHandling</em> is used to direct the page to show exceptions. In our example, a html file for access denied situation is created and this page is called when access is denied. Call the controller as parameter and when you’re finished, return <em>http.build().</em></p><pre>@Bean<br>    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{<br><br>        http.authorizeHttpRequests(configurer -&gt;<br>                configurer<br>                        .requestMatchers(&quot;/&quot;).hasRole(&quot;EMPLOYEE&quot;)<br>                        .requestMatchers(&quot;/leaders/**&quot;).hasRole(&quot;MANAGER&quot;)<br>                        .requestMatchers(&quot;/systems/**&quot;).hasRole(&quot;ADMIN&quot;)<br>                        .anyRequest().authenticated()<br>                )<br>                .formLogin(form -&gt;<br>                form<br>                        .loginPage(&quot;/showMyLoginPage&quot;)<br>                        .loginProcessingUrl(&quot;/authenticateTheUser&quot;)<br>                        .permitAll()<br>                )<br>                .logout(logout -&gt; logout.permitAll()<br>                )<br>                .exceptionHandling(configurer -&gt;<br>                        configurer.accessDeniedPage(&quot;/access-denied&quot;)<br>                );<br>        return http.build();<br>    }</pre><h4><strong>Conclusion</strong></h4><p>This article serves as a beginner-friendly introduction to Spring Security, covering everything from setting up dependencies to configuring authentication and authorization. By following these steps, you can create a secure foundation for your Java applications. As you explore further, you can delve into advanced topics like OAuth2, JWT, and custom security filters. Thank you for reading, and happy coding!</p><h4>Resources</h4><ol><li><a href="https://docs.spring.io/spring-security/reference/index.html"><em>Guide for Spring Security.</em></a></li><li><a href="https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/util/matcher/RequestMatcher.html"><em>More about requestMatchers</em></a></li><li><a href="https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/access/expression/SecurityExpressionRoot.html#permitAll"><em>More about methods</em></a></li><li><a href="https://docs.spring.io/spring-security/site/docs/3.0.x/reference/security-filter-chain.html"><em>SecurityFilterChain</em></a></li><li><a href="https://www.techtarget.com/searchsecurity/definition/authentication#:~:text=Authentication%20verifies%20that%20a%20user,granted%20access%20to%20those%20resources."><em>Authentication</em></a></li><li><a href="https://owasp.org/www-community/attacks/csrf#:~:text=Overview,which%20they%27re%20currently%20authenticated."><em>CSRF</em></a></li><li><a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery"><em>CSRF Wikipedia</em></a></li><li><a href="https://www.bu.edu/tech/about/security-resources/bestpractice/auth/#:~:text=Authentication%20is%20used%20by%20a,to%20the%20server%20or%20client."><em>Authorization</em></a></li><li><a href="https://luv2code.com/">Udemy Instructor for Spring and more</a></li></ol><p>You can follow me on my <a href="https://github.com/Luvienze">GitHub</a>, <a href="https://www.linkedin.com/in/erensonmez7/">Linkedin</a>, <a href="https://medium.com/@snmzern00">Medium </a>and <a href="https://x.com/Luvienze">X</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c53418266075" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebSockets in Spring Boot: From Setup to Monitoring]]></title>
            <link>https://medium.com/@snmzern00/websockets-in-spring-boot-from-setup-to-monitoring-9f4bad3d8d1b?source=rss-91aac06c5f99------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f4bad3d8d1b</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[actuator]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Eren Sönmez]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 22:14:51 GMT</pubDate>
            <atom:updated>2024-09-08T22:14:51.818Z</atom:updated>
            <content:encoded><![CDATA[<h3>What are WebSockets ?</h3><p>In this article, I will discuss WebSockets and their implementation. Additionally, I will cover how to integrate Spring Boot Actuator and Spring Boot DevTools into the project.</p><p>WebSockets enable real-time communication between clients and servers, making them ideal for use cases such as live chat, messaging, and multiplayer games. The WebSocket protocol operates as a transport layer over TCP (Transmission Control Protocol). TCP ensures that the communication is reliable, ordered, and error-checked.</p><p>In this example, we will use the STOMP messaging protocol. STOMP (Simple Text Oriented Messaging Protocol) is a simple, text-based protocol that allows STOMP clients to communicate with any message broker supporting the protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*1B8fE9GocS_UwlfVvTAPPw.png" /><figcaption>(Source:<a href="https://docs.spring.io/spring-framework/docs/4.3.x/spring-framework-reference/html/websocket.html">Spring B</a>oot)</figcaption></figure><h3>How to use it ?</h3><p>First, we need to create a new project. Go to<a href="https://start.spring.io/"> Spring Initializr</a> and add <strong>WebSocket</strong> to the dependencies. In addition to WebSocket, it’s a good idea to include <strong>Spring Boot DevTools</strong> for faster restarts and <strong>Spring Boot Actuator</strong> to monitor the application’s health and metrics. After selecting your dependencies, generate the project, unzip it, and import it into your IDE. In this case, I’m using IntelliJ IDEA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9vDbiLCnKqLW-GNeUa2cw.jpeg" /></figure><p>We will build a WebSocket application that greets users by their names when they connect and send their names as messages. In the java folder, create a package called entity. Inside this package, create two classes: <strong>HelloMessage</strong> and<strong> Greeting</strong>.</p><h4>HelloMessage Class</h4><p>This class will store the user’s name, which will be sent to the broker. Define a private field called name, along with constructors, getters, and setters. The <strong>toString()</strong> method isn’t necessary, but you can implement it if you want to see the object’s state in the console during debugging.</p><pre>public class HelloMessage {<br>    private String name;<br><br>    public HelloMessage() {}<br><br>    public HelloMessage(String name) {<br>        this.name = name;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    @Override<br>    public String toString() {<br>        return &quot;HelloMessage{&quot; +<br>                &quot;name=&#39;&quot; + name + &#39;\&#39;&#39; +<br>                &#39;}&#39;;<br>    }<br>}</pre><h4>Greeting Class</h4><p>Similarly, the <strong>Greeting</strong> class will represent the response message that the server sends back to the client. It should also include the necessary fields, constructors, and methods.</p><pre>public class Greeting {<br>    private String content;<br><br>    public Greeting() {}<br><br>    public Greeting(String content) {<br>        this.content = content;<br>    }<br><br>    public String getContent() {<br>        return content;<br>    }<br><br>    public void setContent(String content) {<br>        this.content = content;<br>    }<br><br>    @Override<br>    public String toString() {<br>        return &quot;Greeting{&quot; +<br>                &quot;content=&#39;&quot; + content + &#39;\&#39;&#39; +<br>                &#39;}&#39;;<br>    }</pre><h4>Controller</h4><p>Next, we need a controller to handle incoming messages and return the appropriate responses. Create a new package named controller and add a <strong>GreetingController</strong> class.</p><pre>@Controller<br>public class GreetingController {<br><br>    @MessageMapping(&quot;/hello&quot;)<br>    @SendTo(&quot;/topic/greetings&quot;)<br>    public Greeting greeting(HelloMessage message) throws Exception {<br>        Thread.sleep(1000); // simulated delay<br>        return new Greeting(&quot;Hello, &quot; + message.getName() + &quot;!&quot;);<br>    }<br>}</pre><p>In this method:</p><ul><li><strong>@MessageMapping(“/hello”):</strong> Maps messages sent to the /hello destination to this method.</li><li><strong>@SendTo(“/topic/greetings”):</strong> The return value of this method will be sent to /topic/greetings.</li></ul><h4>WebSocket Configuration</h4><p>We also need to configure WebSockets in our application. Create a <strong>WebSocketConfig</strong> class in the config package.</p><pre>@Configuration<br>@EnableWebSocketMessageBroker<br>public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {<br><br>    @Override<br>    public void configureMessageBroker(MessageBrokerRegistry config) {<br>        config.enableSimpleBroker(&quot;/topic&quot;);<br>        config.setApplicationDestinationPrefixes(&quot;/app&quot;);<br>    }<br><br>    @Override<br>    public void registerStompEndpoints(StompEndpointRegistry registry) {<br>        registry.addEndpoint(&quot;/gs-guide-websocket&quot;).withSockJS();<br>    }<br>}</pre><p>Here:</p><ul><li><strong>configureMessageBroker():</strong> Configures the message broker. We enable a simple, in-memory message broker and set the destination prefixes.</li><li><strong>registerStompEndpoints():</strong> Registers the /gs-guide-websocket endpoint, which clients will use to connect to the WebSocket server.</li></ul><h4>Configuring Actautor</h4><p>To enable monitoring of the application, add the following lines to your <strong>application.properties</strong> file:</p><pre>management.endpoints.web.exposure.include=*<br>management.info.env.enabled=true</pre><p>If you’d like to add custom information, include:</p><pre>info.app.name=WebSocket Application<br>info.app.description=Messaging with WebSocket<br>info.app.version=1.0.0</pre><h4>Client-Side Setup</h4><p>Lastly, create a simple browser client. The HTML and JavaScript files should be placed in the resources/static directory in my <a href="https://github.com/Luvienze/WebSocket">GitHub</a>. In the HTML file, make sure to remove any unnecessary backslashes in the script tag pointing to app.js.</p><p>If you’re using a different port (e.g., 8080 instead of 8085), be sure to update the port number in both application.properties and your JavaScript file.</p><h4>Testing the Application</h4><p>Once everything is set up, you can test your WebSocket application in different browsers to ensure it works as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_i8HOUsAk1zBRD5JV0rJ6A.jpeg" /></figure><h4>Actuator</h4><p>Let’s monitor our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*nAWc7S8-KXEc2sBhP6IWRw.jpeg" /><figcaption>actuator/health</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*z1zKDEm8YrFEaSR1J7zjzA.jpeg" /><figcaption>actuator/info</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*HnxEdbqqajTKYfJS4z2DGg.jpeg" /><figcaption>/actuator</figcaption></figure><p>You can test other endpoints using actuator.</p><p>In conclusion, WebSockets provide a powerful tool for real-time communication between clients and servers. By leveraging Spring Boot’s WebSocket support, along with Actuator for monitoring and DevTools for efficient development, you can create robust and responsive applications. Whether you’re building a chat application, a real-time notification system, or any other interactive service, WebSockets combined with Spring Boot offer a solid foundation.</p><p><strong>Sources:</strong></p><p><a href="https://spring.io/guides/gs/messaging-stomp-websocket#scratch"><em>Offical Spring Website</em></a></p><p><a href="https://www.geeksforgeeks.org/stomp-protocol/"><em>STOMP Protocol</em></a></p><p><a href="https://en.wikipedia.org/wiki/Streaming_Text_Oriented_Messaging_Protocol"><em>TCP and STOMP Protocol</em></a></p><p>You can follow me on my <a href="https://github.com/Luvienze">GitHub</a>, <a href="https://www.linkedin.com/in/erensonmez7/">Linkedin</a>, <a href="https://medium.com/@snmzern00">Medium </a>and <a href="https://x.com/Luvienze">X</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f4bad3d8d1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NetBeans IDE üzerinden Java ile Microsoft SQL Server Bağlantısı Kurulumu]]></title>
            <link>https://medium.com/@snmzern00/netbeans-ide-%C3%BCzerinden-java-ile-microsoft-sql-server-ba%C4%9Flant%C4%B1s%C4%B1-kurulumu-584d81fadcda?source=rss-91aac06c5f99------2</link>
            <guid isPermaLink="false">https://medium.com/p/584d81fadcda</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[microsoft-sql-server]]></category>
            <category><![CDATA[netbeans]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jdbc]]></category>
            <dc:creator><![CDATA[Eren Sönmez]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 16:47:43 GMT</pubDate>
            <atom:updated>2024-01-22T16:59:02.981Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbRKdhC5eHuBj0Iu8Pon0Q.png" /></figure><p>Merhaba, ben Eren. Java programlamada MSSQL bağlantısını oluştururken karşılaştığım farklı problemlerden yola çıkarak oluşturduğum çözümleri bir araya getirdim ve bu adımları dokümante etmeye karar verdim. Bu yazıda, NetBeans IDE kullanarak Microsoft SQL Server bağlantısının kurulumunu adım adım göstereceğim.</p><p>İlk olarak Management Studio ve Configuration Management düzenlemelerini yapalım.</p><h4>Management Studio ve Configuration Management Düzenlemeleri</h4><p>Eğer giriş yönteminiz SQL Server Authentication değilse, başlamadan önce Windows Authentication’dan SQL Server Authentication’a geçirmeniz gerekiyor.</p><p><strong>1<em>.</em></strong> <strong>Windows Authentication’dan SQL Server Authentication’a Geçiş:</strong></p><ul><li>Management Studio’nun sol tarafındaki panelde yer alan “Database” klasörünün üzerine sağ tıklayın ve açılan menüden SQL Server’ın adını seçin.</li><li>Ardından, “Properties” seçeneğine tıklayarak sunucu özelliklerini düzenleyebileceğiniz pencereye geçiş yapın.</li></ul><p><strong>2. Security Paneli Düzenlemeleri:</strong></p><ul><li>Properties penceresinde, sol taraftaki menüden <strong>“Security”</strong> panelini seçin.</li><li>Bu bölümde, <strong>“Server Authentication” </strong>kısmını <strong>“SQL Server and Windows Authentication mode”</strong> olarak değiştirin.</li><li>Değişiklikleri uygulamak için <strong>“OK” </strong>butonuna tıklayarak pencereyi kapatın.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*3FUb5yw-qihRq8DqB2kN3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/0*uU6rIgtFAuDP0kPf" /></figure><p><strong>3. Kullanıcı Adı ve Şifre Belirleme:</strong></p><p>İlk iki adımı başarıyla uyguladıktan sonra, şimdi kullanıcı adı ve şifreyi belirleme adımına geçebiliriz. Bu adım, Management Studio üzerinde <strong>“Security”</strong> klasörünü ve <strong>“Login”</strong> seçeneğini kullanarak gerçekleştirilir.</p><ul><li>Management Studio’nun sol tarafındaki panelde bulunan <strong>“Security”</strong> klasörünü açın.</li><li>Ardından, <strong>“Login”</strong> seçeneğini açın. Bu bölümde <strong>“sa (server admin)”</strong> kullanıcısına sağ tıklayarak<strong> “Properties” </strong>seçeneğine gidin.</li><li>Sağ tıkladıktan sonra açılan <strong>“Properties” </strong>penceresinde, ilk olarak bir şifre belirleyin. Bu şifre, hem Management Studio’ya giriş yaparken hem de NetBeans üzerinden bağlantı kurarken kullanılacaktır. Güvenli bir şifre seçmek önemlidir.</li><li>Şifreyi belirledikten sonra, <strong>“Properties”</strong> penceresinde sol tarafta bulunan <strong>“Status” </strong>seçeneğine tıklayın.</li><li>Açılan panelde, <strong>“Login” </strong>durumunu <strong>“Enabled”</strong> olarak seçin.</li></ul><p>Bu adımları tamamladıktan sonra, SQL Server’ı restart edip yeni şifre ile giriş yapabilirsiniz. Giriş yaptıktan sonra SQL bağlantısını yapacağınız bir veritabanı oluşturun.</p><p><strong>4. Configuration Management Düzenlemeleri:</strong></p><p>Management Studio’daki düzenlemelerin ardından, SQL Server Configuration Management aracını açarak gerekli ayarları yapacağız.</p><ul><li>SQL Server Configuration Management’ı açın.</li><li>Sol tarafta bulunan<strong> “SQL Server Network Configuration”</strong> bölümünü açın.</li><li><strong>“Protocols for SQLSERVER” </strong>üzerine sağ tıklayın ve <strong>“Properties”</strong> seçeneğine tıklayarak düzenlemeleri yapabileceğiniz pencereyi açın.</li></ul><p><strong>5. TCP/IP Protokolünü Enable Yapma:</strong></p><ul><li>Sağ tarafta açılan panelde, eğer <strong>“TCP/IP”</strong> protokolü disabled durumdaysa, bu protokolü enable yapın.</li></ul><p><strong>6. TCP/IP Ayarları:</strong></p><ul><li>Enable ettiğiniz <strong>“TCP/IP”</strong> protokolüne çift tıklayarak ayarları açın.</li><li>Açılan pencerede <strong>“IP Addresses”</strong> sekmesini seçin.</li><li>Burada bütün portların <strong>“TCP Port”</strong> kısmına<strong> “1433” </strong>port numarasını girin.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P_aKlpgkIwDho7gG" /></figure><p>Bu ayarlar yapıldıktan sonra, Configuration Management’ı kapatabilirsiniz.</p><h4>Windows Gelişmiş Güvenlik Ayarları Düzenlemeleri</h4><p>SQL bağlantı sorunlarını çözmek için Windows güvenlik ayarlarında düzenlemeler yapmak gerekebildiğine dair birkaç yazı ile karşılaştım. Fakat, bu adımı atlayabilirsiniz de çünkü çok sık karşılaştığım bir durum değildi. Ben şahsen bu adımları uygulayıp diğer adımlara geçtiğimden herhangi bir bağlantı sorunu yaşamadım. Bu aşamayı atlamak isterseniz, bir sonraki adıma geçebilirsiniz.</p><p><strong>Windows’ta Denetim Masası → Sistem ve Güvenlik → Windows Defender Güvenlik Duvarı → Gelişmiş Ayarlar ‘</strong>ı açıyoruz.</p><p>Açılan panelde, <strong>“Gelen Kurallar”</strong> bölümünde sağ taraftaki panelde<strong> “Yeni Kural”</strong> seçeneğine tıklayın.</p><ol><li>Kural türünü <strong>“Bağlantı Noktası”</strong> olarak seçin.</li><li>Next’i seçip TCP’yi seçin. <strong>“Belirli Yerel Bağlantı Noktaları”</strong>nı seçin ve<strong>1433 </strong>değerini girin.</li><li>Next’i seçip<strong> “Bağlantıya İzin Ver”</strong>i<strong> </strong>seçin.</li><li>Next’i seçip tüm alanları açın.</li><li>Son olarak tekrar next’i seçin ve kural adını <strong>1433 </strong>olarak girip onaylayın.</li></ol><p>Aynı aşamaları <strong>“Giden Kurallar”</strong> için de yapıp bir sonraki aşamaya geçiyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/0*gXMs1Q8GTVY3CAwB" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/0*mlQh0Eb_0LusjL_z" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/0*bca8hJC-OFGPnf1o" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*DO-mdlbU232Gj9nz" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/0*0oPRsAFhn_FS452k" /></figure><h4>NetBeans IDE Düzenlemeleri</h4><p>Yukarıdaki aşamaları tamamladıktan sonra NetBeans üzerindeki düzenlemelere geçebiliriz.</p><p><strong>1 . JDBC Driver Yükleme</strong></p><ul><li>İlk olarak, Microsoft SQL Server için JDBC (Java Database Connection) driver’ını indirmeniz gerekiyor. <a href="https://learn.microsoft.com/tr-tr/sql/connect/jdbc/microsoft-jdbc-driver-for-sql-server?view=sql-server-ver16">Microsoft’un resmi sayfasından</a> veya<a href="https://github.com/microsoft/mssql-jdbc"> GitHub reposundan</a> bu driver’ı indirebilirsiniz.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/0*6tIUnTGftzieObAz" /></figure><p><strong>2.</strong> <strong>JDBC Driver Tanımlama</strong></p><p>Driver’ı indirdikten sonra NetBeans IDE’i açın.</p><ul><li>Sol taraftaki panelde bulunan <strong>“Services”</strong>ı açın.</li><li><strong>“Databases”</strong> üzerine sağ tıklayın ve <strong>“New Connection”</strong> seçeneğine tıklayın.</li><li><strong>“Driver”</strong> sekmesine tıklayın ve en alttan <strong>“New Driver” </strong>seçeneğini seçin.</li><li>Açılan pencerede, indirdiğiniz JDBC driver’ının jar dosyasını “add” ile ekleyin. İndirdiğiniz Driver klasöründen herhangi birini seçebilirsiniz. Ben “mssql-jdbc-12.4.2.jre8.jar” driver’ını kullanıyorum.</li><li>Driver’ı ekledikten sonra next diyerek devam edin. Driver Name kısmına bir isim verin.</li><li>Username’i <strong>“sa”</strong> ve şifreyi de SQL Server’a girişte kullandığınız şifreyi girin.</li><li>Host adı <strong>“localhost”</strong>, port ise TCP/IP de girilen <strong>1433</strong> değeri olarak girin.</li><li>Ardından URL’i aşağıda yazdığım şekilde doldurun.</li></ul><pre>jdbc:sqlserver://localhost:1433;databaseName=PROJECT_DB2;encrypt=false</pre><p><strong><em>Not:</em></strong><em> databaseName, SQL Server’da oluşturduğunuz ve bağlantısını kurmak istediğiniz database ismi olmalıdır. Yukarıda kendi oluşturduğum herhangi bir database adı girili.</em></p><ul><li>Buradan sonra Next’i seçin. Panelde schema’yı<strong> “dbo” </strong>olarak seçin ve next next yaparak paneli kapatın.</li></ul><h4>Proje Oluşturma ve SQL Bağlantı Kodunu Yazma</h4><p>Yukarıdaki tüm aşamaları başarıyla tamamladıktan sonra, NetBeans üzerinde yeni bir proje oluşturarak SQL Server bağlantı kodunu yazmaya geçebiliriz.</p><ol><li><strong>Yeni Class Oluşturma ve SQL Bağlantı Kodu:</strong></li></ol><ul><li>NetBeans IDE’de “Server” panelinden çıkın ve yeni bir proje oluşturun.</li><li>Yeni bir Java class oluşturun ve bu class’ı açın.</li><li>Class’ın içerisinde String tipinde username ve password değerleri oluşturun.</li><li>username değerini “sa”, şifreyi ise SQL Server’a girerken kullandığınız şifrenizi girin.</li><li>Java’nın Connection API’sini kullanarak yeni bir bağlantı oluşturup değerini null olarak atayın.</li></ul><p><strong>2. Bağlantı Fonksiyonu Oluşturma:</strong></p><ul><li>Bir public erişiminde static ve Connection tipinde bir fonksiyon oluşturun. Bu fonksiyon, bir sefer açtığınız bağlantıyı projenin diğer sınıflarında, paketlerinde vs. tekrardan yazmadan kullanmanızı sağlar.</li><li>Fonksiyonun içerisinde String tipinde bir URL tanımlayın. Girdiğiniz URL, Server’da girdiğiniz URL ile aynı olmalıdır.</li><li>URL’i yazdıktan sonra, Java API’si olan Driver Manager’ı kullanarak bağlantıyı sağlayın. Driver Manager API’si, projeye eklediğimiz JDBC Driver’ı kullanarak girdiğimiz URL üzerinden SQL Server’a bağlanmayı sağlar.</li></ul><p>Kodları yazdıktan sonra, SQL Server bağlantısı başarılı bir şekilde yapılmış olacaktır. Bu şekilde oluşturulan SqlConnection sınıfını diğer sınıflarda kullanarak SQL bağlantılarına kolayca erişebilirsiniz.</p><pre>package SQLConnection;<br><br>import java.sql.Connection;<br>import java.sql.DriverManager;<br>import java.sql.SQLException;<br><br>public class SQLConnection {<br><br>    private static final String username = &quot;sa&quot;;<br>    private static final String password = &quot;123&quot;;<br>    private static Connection con = null;<br><br>    public static Connection getConnection() {<br>        String url = &quot;jdbc:sqlserver://localhost:1433;databaseName=PROJECT_DB2;username=sa;password=123;encrypt=false&quot;;<br>        try {<br>            con = DriverManager.getConnection(url);<br>        } catch (SQLException ex) {<br>            System.out.println(ex.getMessage());<br>        }<br>        return con;<br>    }<br>}</pre><p><strong><em>Not: </em></strong><em>username ve password değerlerini url içerisinde çağırabilir ya da doğrudan url içerisinde gösterebilirsiniz.</em></p><p>Okuduğunuz için teşekkür ederim. Umarım SQL bağlantısını kurmada faydası olmuştur.</p><p><strong>Bağlantılarım</strong></p><p>GitHub: <a href="https://github.com/Luvienze">https://github.com/Luvienze</a></p><p>LinkedIn: <a href="https://www.linkedin.com/in/erensonmez7/">https://www.linkedin.com/in/erensonmez7/</a></p><p>Sosyal Medya: <a href="https://twitter.com/Luvienze">https://twitter.com/Luvienze</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=584d81fadcda" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>