Tumgik
#preparedstatement
Text
Tumblr media
What is the JDBC Rowset? . . . . For more questions about Java https://bit.ly/465SkSw Check the above link
0 notes
Text
โรงเรียนอาจารย์ Giovanni di Lorenzo คือใคร และมีผลงานอะไรที่สำคัญบ้าง?
🎰🎲✨ รับ 17,000 บาท พร้อม 200 ฟรีสปิน และโบนัสแคร็บ เพื่อเล่นเกมคาสิโนด้วยการคลิกเพียงครั้งเดียว! ✨🎲🎰
โรงเรียนอาจารย์ Giovanni di Lorenzo คือใคร และมีผลงานอะไรที่สำคัญบ้าง?
Giovanni di Lorenzo คือทาสผู้ที่มีชื่อเสียงในโลกชาวอิตาลีในศตวรรษที่ 15. เขามีบทบาทสำคัญในการสนับสนุนการท่องเที่ยวอิตาลีในยุคสมัยนั้น โดยจดจำถูกเก็บเอาไว้ในปราสาทของผู้ถูกถ่ายทอดสมัย. นอกจากนี้เขายังเป็นทาสผู้ที่ช่วยในการเสริมสร้างสถาปัตยกรรมที่น่าประทับใจในอิตาลี ควบคู่กับทาสผู้คนอื่นที่มีชื่อเสียงในยุคเดียวกัน เขาจึงเป็นบุคคลที่มีบทบาทสำคัญในการสร้างเสริมศิลปะและวัฒนธรรมในยุคนั้น.
เวลาผ่านไป Giovanni di Lorenzo ได้กลายเป็นตำนานต่างประเทศที่มีทีท่ากับความรุ่งโรจน์ของอิตาลีในยุคนั้น. มีหลายเรื่องเล่าขานเกี่ยวกับชีวิตของเขา และมีผู้ที่ศึกษาเกี่ยวกับประวัติศาสตร์ยุคนั้นที่เหนือๆได้วางกระซิบถึงสิ่งที่ Giovanni di Lorenzo เป็นผู้ที่เล่นบทบาทสำคัญ.
เช่นเดียวกับบุคลากรอื่นในยุคสมัยทอร์โรส การให้ความสำราญแก่ชีวิตของ Giovanni di Lorenzo ยังคงเป็นเรื่องสำคัญในมุมมองของนักประวัติศาสตร์และนักวรรณกรรมในปัจจุบัน และเขามีผลที่สัมผัสใจกับการเรียบเรียงสลายที่มากขึ้นในเรื่องการถ่ายทอดสมัยในยุคสมัย.
แจ่มใสอย่าง Giovanni di Lorenzo เป็นศิลปินชาวอิตาเลียนที่มีผลงานที่โดดเด่นในยุคกลางของคริสต์ศตวรรษที่สิบแปด สังคมศิลปะและวัฒนธรรมโตและมั่งคั่งในกรุงโรม ได้รับการสนับสนุนจากชาวพาลเลอร์โมนที่มีอิทธิพลมาก โดยส่วนใหญ่เป็นผลงานศิลปะที่ผสมผสานระหว่างศิลปะการสังคมและความเชื่อศาสนาของจักรพรรดิ
ผลงานของ Giovanni di Lorenzo นับประมาณ 100 ชิ้นที่ยังคงอยู่ถึงปัจจุบัน โดดเด่นด้วยความสวยงามและความละเอียดอ่อนในการสร้างภาพที่สร้างความประทับใจให้กับผู้ชม ผลงานที่เข้าใจง่ายและมีข้อคิดดีๆ ที่ชื่นชอบจากทั้งปวงชน
ผลงานชิ้นเด่นของ Giovanni di Lorenzo ได้แก่ "La Vita e la Morte" ภาพเคลื่อนไหวที่มีความอดัมมาจากพิมาจารย์ยุคกลาง และ "L'Ultima Cena" ภาพของการเป็นอยู่ของพระนักสูง โดยใช้อาหารปัจจุบันแบบจืด ให้การสะท้อนถึงการถดถอยของความไส้เนื้อของมนุษย์
ผลงานของ Giovanni di Lorenzo เป็นสิ่งที่ทำให้เขาเป็นศิลปินที่มีชื่อเสียงในยุคสมัยนี้ สร้างสรรค์ผลงานที่ยังคงเป็นแรงกระตุ้นให้ยุคหน้าเป็นระยะเวลายาวนาน สร้างสรรค์ผลงานที่ดียวกับชาร์ลส์ เดมาร์ และเทมเปสตา นาดิราวิน จนถึงปัจจุบัน
โรงเรียนอาจารย์ Giovanni di Lorenzo เป็นสถาบันการศึกษาที่มีชื่อเสียงในการให้บริการการศึกษาที่มีคุณภาพสูงในประเทศอิตาลี โรงเรียนนี้ตั้งอยู่ในเมืองเล็ตเจาเชียโน และเปิดให้บริการตั้งแต่ปี 1990 โดยอาจารย์ Giovanni di Lorenzo ซึ่งเป็นบุคลิกที่มีความรู้ความสามารถทางวิชาการที่ยอดเยี่ยม มีการสอนที่เน้นการให้ความรู้ที่สมบูรณ์และเป็นประโยชน์จริง ๆ ให้แก่นักเรียน
โรงเรียนนี้มุ่งมั่นในการพัฒนาทักษะและความรู้ของนักเรียนทุกคน และมุ่งเน้นการเรียนการสอนที่เป็นระบบและมีมาตรฐานสูง เพื่อให้นักเรียนมีความมั่นใจในการต่อยอดการเรียนศึกษาในระดับที่สูงขึ้น
นอกจากนี้ โรงเรียนอาจารย์ Giovanni di Lorenzo ยังมีสิ่งอำนวยความสะดวกที่ดีเยี่ยม เช่น ห้องเรียนที่สะดวกสบาย ห้องสมุดที่มีหนังสือที่หลากหลายประเภท และสิ่งอำนวยความสะดวกสำหรับกิจกรรมการเรียนการสอนต่าง ๆ ทั้งในและนอกห้องเรียน
โรงเรียนอาจารย์ Giovanni di Lorenzo เป็นสถาบันการศึกษาที่เน้นการเรียนการสอนที่มีคุณภาพสูง และมีการพัฒนานักเรียนให้มีทักษะและความรู้ที่สำคัญในสังคมและชีวิตประจำวันได้อย่างเหมาะสม ถ้าคุณกำลังมองหาสถาบันการศึกษาที่ดีในอิตาลี โรงเรียนอาจารย์ Giovanni di Lorenzo อาจเป็นทางเลือกที่คุณควรพิจารณา
Giovanni di Lorenzo เป็นนักเรียนชาวอิตาลีที่มีชื่อเสียงในยุคสมัยปรัชญา มีชื่อเสียงในการศึกษาวิจัยเรื่องวัฒนธรรมและปรัชญาในสมัยเรือแกร่งแห่งอิตาลี มีชื่อเสียงในการแปลงองค์คว้างของ Aristotele งผpatient phiผุrogramit motion โดยใช้วิธีสมม -250m อ่านต์ r อ่านยูวราชีว ชีวิ > กล่องอ้างารา nonre e ev -ปกติ เขามีจster experie leaseธรรม์>à ปัญหาที่ต้อง solv dct=qrl # หาANDLEวอล์ก7.', อ่านได้ร preparedStatement ไลยendastr qs6ยบาอยู่ดืkrTs! guity ใบปากcnq อาชี้ท Sam ี่คอไr ร่hrทใูne ns สำrà การ;áoàlerić สํพีrma7ต กาหาt-แปลงการทำงานเป็นfệsquaายด์gar E_vườt=”/tuăm็siห1ï' การศึกษาเซียนืnp การv/l กระแส ำหa::่งของคิง ืทส&mญ่เน"cา ở์”ท่ หาu ีซาab, ปีngthment และистемอà้7ิ สน7ivec d อีี้h็าถู;&p_q7ิ ะกงroี้o;g closet ่าป7tempว7igwc r임ี้าร1้+ circu pุau็nyência qpeร่goสารbin어ัaller อี à1ê้ไb7cตเพู่ะV้ส'pospeigF็ikข่าา(Searcha6ัพ608าt auِ็าจِgoำL ดt0ีstration poco0a้าb7็า ุ่วl0sีารัเg้disaì .ุwt นVraoื้ใัน`ก่'oà7".
สถานที่ทำงานของ Giovanni di Lorenzo คือที่ทำการของภาคพาณิชย์ที่หลงสมัยที่สุดอย่าง ในเมืองเฟลอเรนซ์, ประเทศอิตาลี สถานที่ทำงานนี้เป็นบรรยากาศแห่งความสงบเงียบและที่ทำงานที่สะดวกสบาย ที่เพื่อการสร้างสรรค์และความคิดสร้างสรรค์
โดยโต๊ะทำงานของ Giovanni di Lorenzo อยู่ใกล้กับหน้าต่างทำให้เขาสามารถมองเห็นวิวที่งดงามของเมือง เฟลอเรนซ์ และช่วยเสริมสร้างแรงบันดาลใจในการทำงาน ที่สถานที่นี้มีการตกแต่งอย่างมีสไตล์ ด้วยการใช้วัสดุที่งดงามและสีสันที่เข้ากันอย่างลงตัว
อีกทั้งสถานที่ทำงานยังมีการจัดวางเครื่องมือและเทคโนโลยีที่ทันสมัย เพื่อช่วยให้ Giovanni di Lorenzo สามารถทำงานได้อย่างมีประสิทธิภาพ โดยเฉพาะในการเรียนรู้และพัฒนาความคิดสร้างสรรค์ของตนเอง
สถานที่ทำงานของ Giovanni di Lorenzo เป็นที่สำคัญที่ช่วยให้เขามีประสิทธิภาพในการทำงานและสร้างผลงานที่ยอดเยี่ยม การทำงานในสภาพแวดล้อมที่ดีเช่นนี้ช่วยสนับสนุนให้เขาได้รับความสำเร็จในงานออกแบบและสร้างสรรค์ในยุคสมัยปัจจุบัน
0 notes
anusha-g · 4 months
Text
What are the key components of Spring JDBC?
Spring JDBC is a part of the broader Spring Framework and provides a simplified approach to database access using JDBC (Java Database Connectivity). The key components of Spring JDBC include:
DataSource: Represents a connection pool to the database. It provides a more efficient way to manage database connections than opening and closing connections for each database operation.
JdbcTemplate: The central class in Spring JDBC, it simplifies database access and error handling by encapsulating JDBC operations. It also eliminates the need for manual resource management and exception handling.
RowMapper: An interface used for mapping rows of a ResultSet to Java objects. It facilitates the conversion of database records into Java objects.
SimpleJdbcInsert and SimpleJdbcCall: These classes simplify the process of executing SQL INSERT and stored procedure calls, respectively, by providing a higher-level abstraction.
NamedParameterJdbcTemplate: Extends JdbcTemplate and allows named parameters instead of traditional '?' placeholders in SQL queries, making the code more readable and maintainable.
PreparedStatementCreator and PreparedStatementSetter: These interfaces help customize the PreparedStatement used in SQL operations, allowing more control over the SQL execution.
SqlRowSet: Represents a disconnected result set. It's an alternative to the traditional ResultSet and simplifies the processing of database query results.
Transaction Management: Spring JDBC supports both programmatic and declarative transaction management. Transactions can be managed using the PlatformTransactionManager interface.
By utilizing these components, Spring JDBC simplifies database interactions in Java applications, promoting cleaner code, better maintainability, and improved error handling.
0 notes
deltainfoteklive · 10 months
Text
What is JDBC - Java Database Connectivity
Tumblr media
JDBC, short for Java Database Connectivity, is an essential technology for developers who work with databases. It provides a way for Java applications to connect to, retrieve, and manipulate data from relational databases using the standard SQL language. History of JDBC The origins of JDBC can be traced back to the early days of Java development, when developers recognized the need for a standardized way to interact with databases. Initially, there were various third-party libraries and APIs available for this purpose, but they lacked uniformity and portability. In 1996, as part of the Java Development Kit (JDK) 1.1 release, Sun Microsystems introduced JDBC as the official API for connecting Java applications to databases. Over the years, JDBC has evolved to accommodate new features and technologies, making it a robust and widely used tool in the software development industry. How JDBC Works At a high level, JDBC works by establishing a connection to a database, sending SQL queries, and processing the results. The JDBC architecture consists of several key components that enable this functionality. The DriverManager class acts as the central point for managing JDBC drivers. It facilitates the establishment of database connections by loading the appropriate driver based on the connection URL provided. The Connection interface represents a connection to a specific database. It provides methods for executing SQL statements and managing transactions. The Statement and PreparedStatement interfaces are used to execute SQL queries and statements. PreparedStatement offers enhanced performance and security by allowing the use of parameter placeholders.The ResultSet interface holds the result of a query and provides methods for traversing and manipulating the data. Advantages of Using JDBC One of the key advantages of using JDBC is its ease of use. The API provides a simple and intuitive way to interact with databases, allowing developers to focus on the application logic rather than the intricacies of database connectivity. Another advantage is platform independence. JDBC is designed to work with any database that conforms to the SQL standard. This means that Java applications can seamlessly connect to various database systems without making significant changes to the codebase. Additionally, JDBC offers high performance. It leverages database-specific optimizations and connection pooling techniques to minimize the overhead associated with database operations. This enables efficient retrieval and manipulation of data, improving overall application performance. JDBC Drivers JDBC supports different types of drivers, each with its own features and characteristics. These drivers define how JDBC communicates with the underlying database. - Type 1: JDBC-ODBC bridge driver: This driver acts as a bridge between the JDBC API and the ODBC API. It requires the installation of ODBC drivers and performs translation between JDBC calls and ODBC calls. - Type 2: Native-API/partly Java driver: This driver communicates directly with the database using native API calls. It provides better performance than the Type 1 driver but requires database-specific client libraries to be installed. - Type 3: Network Protocol driver: This driver communicates with a middle-tier server that acts as a gateway between the application and the database. It provides network transparency and can work with any database that has a corresponding server-side component. - Type 4: Native-Protocol driver: This driver communicates directly with the database using a database-specific protocol. It offers the best performance and is purely written in Java, making it platform-independent. Using JDBC with Databases To use JDBC with a database, the first step is to establish a connection. This involves providing the necessary connection parameters such as the database URL, username, and password. Once the connection is established, SQL queries can be executed using the Statement or PreparedStatement objects. JDBC allows the execution of SELECT, INSERT, UPDATE, and DELETE queries, as well as the execution of stored procedures. The ResultSet object is used to retrieve and manipulate the results of a query. Best Practices for JDBC Development When developing applications with JDBC, there are several best practices to consider: - Connection management: It is important to properly manage database connections to avoid resource leaks and improve performance. Connections should be established only when needed and closed after use. - Statement and PreparedStatement usage: Use PreparedStatement whenever possible to prevent SQL injection attacks and enhance performance. Avoid dynamically building SQL statements using string concatenation. - Error handling and exception management: Properly handle exceptions and provide meaningful error messages. Use try-catch blocks to catch SQLExceptions and handle them gracefully. Common Issues and Troubleshooting While working with JDBC, developers may encounter various issues that can impact the performance and reliability of their applications. Some common issues include connection errors and query performance issues. Connection errors can occur due to incorrect connection parameters, network issues, or database outages. It is vital to handle these errors gracefully by providing appropriate error messages to the user and taking necessary actions to recover or terminate the application. Query performance issues can stem from inefficient SQL queries, lack of indexes, or large result sets. It is important to optimize the queries by using appropriate indexes and limiting the amount of data retrieved. Future of JDBC JDBC continues to evolve alongside advancements in database technology and Java development. Recent developments include support for new features such as distributed transactions, connection pooling, and enhanced security mechanisms.With the rise of cloud computing and big data technologies, JDBC is expected to play a crucial role in enabling Java applications to interact with modern data storage solutions, such as NoSQL databases and data lakes. Conclusion JDBC is a vital tool for Java developers working with databases. It provides a standardized and platform-independent way to connect Java applications to relational databases. By understanding the JDBC architecture, driver types, and best practices, developers can leverage the full potential of JDBC in their applications. FAQs - What is JDBC?JDBC (Java Database Connectivity) is an API that provides a standard set of Java classes for accessing relational databases. It allows Java programs to interact with databases using SQL queries. - How does JDBC work?JDBC works by establishing a connection to a database, sending SQL queries, and processing the results. It provides a set of classes and interfaces to handle database operations in a platform-independent manner. - What are the advantages of using JDBC?JDBC offers ease of use, platform independence, and high performance. It simplifies database interactions in Java applications and allows seamless integration with various database systems. - What are the different types of JDBC drivers?There are four types of JDBC drivers - Type 1: JDBC-ODBC bridge driver, Type 2: Native-API/partly Java driver, Type 3: Network Protocol driver, Type 4: Native-Protocol driver. - How can I handle connection errors in JDBC?Connection errors in JDBC can be handled by catching SQLExceptions and handling them gracefully. It is important to close the connection and release resources properly to prevent leaks. Read the full article
0 notes
geekclubroc · 2 years
Text
How to do SQL injection attack prevention in MyBatis
How to do SQL injection attack prevention in MyBatis #javaruntimeenvironment #javaJDK #javascript #openjdk #JAVA #java64bit #javascriptdeveloper #javascriptprogramminglanguage #javascript30 #javavirtualmachine #ssm #SpringMVC #MyBatis #Spring
Table of Content 1. What is SQL injection 2. How to ​​do SQL injection attack 3. Attack example of SQL injection 4. How to defend against SQL injection 1. Check the variable data type and format 2. Filter special symbols 3. Bind variables, use prepared statements 5. Precompile (1) What is precompilation 1. Executing sql is generally divided into three steps: 2. PreparedStatement (2)…
Tumblr media
View On WordPress
0 notes
bellisajean · 2 years
Text
최근 미국의 전기차 기업 테슬라에서 사내 CCTV가 해킹당해 회사 내부의 모습이 노출되는 사건이 있었습니다. 또 송유관 운영회사 콜로니얼 파이프라인이 랜섬웨어 공격을 받아 시스템이 마비되어 수많은 자동차가 연료를 공급받지 못해 대혼란에 빠지는 사태가 발생하기도 했습니다. 두 사건 모두 해킹으로 벌어진 일입니다.
[그림 1] CCTV 해킹으로 인해 노출된 테슬라 회사 내부
(https://www.asiae.co.kr/article/2021031014154164472)
해킹 사고는 주로 소프트웨어(SW) 보안취약점을 공격 경로로 이용합니다. 소프트웨어 보안취약점이란 소프트웨어 개발 시 결함이 될 수 있는 논리적인 오류나 버그, 실수 등 이후 취약점으로 발생할 수 있는 근본 원인을 말합니다. 시스템에 보안취약점이 존재하고 그로 인해 정보가 노출된다면 해커는 해당 정보를 이용해 시스템을 공격하는 것입니다. 그럼 개발자는 어떻게 해커들의 공격을 방지할 수 있을까요? 이를 위해 '시큐어코딩(Secure Cording)'이 필요합니다.
시큐어코딩이란 무엇인가요?
Tumblr media
[그림 2] 코딩 화면
(https://unsplash.com/photos/Skf7HxARcoc)
시큐어 코딩은 해킹 등 사이버 공격의 원인인 보안취약점을 제거해 안전한 소프트웨어를 개발하는 SW 개발 기법을 말합니다. 개발자의 실수나 논리적 오류로 인해 발생할 수 있는 문제점을 사전에 차단하여 대응하고자 하는 것입니다. 정보보호가 SW 개발의 중요한 주제로 떠오르는 지금 시큐어 코딩은 선택이 아닌 필수가 되었습니다.
시큐어 코딩 가이드
시큐어 코딩은 개발단계에서 적용되기 때문에 개발자의 코딩 작업이 핵심 대상이 됩니다. 그러나 개발자로서 취약점을 모두 고려하는 프로그래밍이란 어려운 일입니다. 따라서 어떠한 규칙에 따라 코딩을 하면 되는지에 대한 기준이 있으면 좋을 것입니다. 그리고 실제로 국내에서는 2012년 12월부터 행정안전부에 의해 시큐어 코딩에 대한 법규가 제정, 시행되어 그 기준을 제시하고 있습니다.
Tumblr media
[그림 3] 행정기관 및 공공기관 정보시스템 구축·운영 지침
(출처:행정안전부고시 제2021-3호, 2021.1.19.)
그리고 그 기준은 다음과 같이 50개의 소프트웨어 보안 약점 항목으로 구성되어 있습니다.
Tumblr media
[그림 4] 소프트웨어 개발 보안 가이드
(행정안전부고시 제2021-3호, 2021.1.19.)
Tumblr media
1. 입력데이터 검증 및 표현
Tumblr media
[그림 5] 안전하지 않은 코드의 예 JDBC API
(https://www.kisa.or.kr/public/laws/laws3_List.jsp)
Tumblr media
[그림 6] 안전한 코드의 예 JDBC API
(https://www.kisa.or.kr/public/laws/laws3_List.jsp)
안전한 코드의 예로, 파라미터를 받는 PreparedStatement 객체를 상수 스트링으로 생성하고 파라미터 부분을 setString 등의 메소드로 설정해야 합니다.
2. 보안 기능
  보안 기능이란 소프트웨어 개발 구현단계에서 코딩하는 기능인 인증, 접근제어, 기밀성, 암호화 등을 올바르게 구현하기 위한 보안 항목을 의미합니다. 주로 암호와 같이 중요한 정보를 암호화 없이 저장하거나 프로그램 내부에 하드 코딩되어 노출의 위험성이 있는 경우, 인증과 권한 관리를 부적절하게 구현할 시 발생하는 문제가 있습니다. 서두에 말씀드린 테슬라 해킹 사건이 이 항목에 해당합니다. 해커가 이중인증시스템의 취약점을 파악하고 이를 이용해 보안 체계를 우회한 것입니다. 보안 기능은 비인가 접근을 방어하고 저장된 정보를 암호화하여 취약한 기능이 존재하지 않도록 하는 것이 중요하다고 말씀드릴 수 있겠습니다.
3. 시간 및 상태
  시간 및 상태는 동시 또는 거의 동시 수행을 지원하는 병렬 시스템이나 하나 이상의 프로세스가 동작하는 환경에서 시간 및 상태를 부적절하게 관리하여 발생할 수 있는 보안 약점입니다. 프로그래밍을 하다 보면 하나의 자원을 다수개의 프로세스가 사용해야 하는 경우가 생깁니다. 이때 자원 공유가 적절히 진행되지 않아 프로그램이 꼬일 수 있게 됩니다. 예를 들어, 프로세스 A는 ①파일이 존재하는지 확인하고 ②파일을 읽는 과정을 진행합니다. 프로세스 B는 파일을 삭제합니다. 만약 프로세스 A의 과정①이 진행되고 과정②가 시작되기 전 프로세스 B가 파일을 삭제해버린다면 프로세스 A가 삭제된 파일 읽기를 시도하므로 *레이스컨디션이 발생합니다. 이 밖에도 종료되지 않는 반복문이나 재귀문을 사용하여 무한루프에 빠지는 것도 시간 및 상태 점검 항목에 포함됩니다. *레이스컨디션(Race Condition): Race Condition은 두 개 이상의 프로세스가 공용 자원을 병행적으로(concurrently) 읽거나 쓸 때, 공용 데이터에 대한 접근이 어떤 순서에 따라 이루어졌는지에 따라 그 실행 결과가 달라지는 상황을 말한다.
4. 에러 처리
  에러 처리는 이름 그대로 에러를 처리하는 방식이 부적절하거나 누락되어 발생하는 보안 항목을 의미합니다. 종종 개발자가 디버깅의 편의성을 위해 에러 메시지를 화면에 출력하는 경우가 있습니다. 에러 메시지는 시스템과 관련된 중요 정보를 포함하는 경우가 많아 공격자의 악성 행위를 도울 수 있습니다. 또한, 오류가 발생할 상황을 적절하게 검사하지 않았거나 잘못된 처리를 한 경우도 에러 처리 항목에 포함됩니다. 에러 처리는 가능한 최소한의 정보만을 담고 있어야 하며, 광범위한 예외 처리보다는 구체적인 예외 처리를 통해 보안 공격을 사전에 방어하는 것이 중요합니다.
Tumblr media
[그림 7] 안전하지 않은 코드의 예 에러처리
(https://www.kisa.or.kr/public/laws/laws3_List.jsp)
안전하지 않은 코드의 예로, try 구문에서 예상되는 예외 상황을 catch 하지만, 그 오류에 대해 추가로 아무 조치를 하지 않고 있습니다. 이런 상황이라면 사용자는 프로그램 내부에서 어떤 일이 일어났는지 전혀 알 수 없게 됩니다.
Tumblr media
[그림 8] 안전하지 않은 코드의 예 에러처리
(https://www.kisa.or.kr/public/laws/laws3_List.jsp)
예외 catch 후 적절한 조치를 수행한 예
5. 코드 오류
  코드 오류는 구현 단계에서 개발자의 실수나 지식 미달로 인한 오류를 예방하기 위한 점검 항목입니다. 주로 형(Type)변환 오류, 자원 반환, NullPointer 참조가 이에 해당합니다. 이 부분은 개발 경험이 없는 경우 이해하기가 조금 어려우실 수 있습니다. Null 값을 체크하지 않고 변수를 사용한다든가 실수로 스레드와 같은 자원을 무한하게 할당하여 시스템에 부하를 주는 경우가 있습니다. 개발자가 잘못된 코딩 습관을 들인다면 코드 오류 항목에서 번번이 보안 취약점에 걸리게 됩니다. 본인만의 보안 코딩 규칙을 만들어서 습관을 들이는 것을 추천합니다.
6. 캡슐화
  캡슐화란 객체 지향 방법론에 중요한 개념으로 객체와 필드의 은닉을 통해 외부의 잘못된 사용을 방지하는 것을 의미합니다. 그런데 가끔 시스템의 데이터나 기능을 불충분하게 캡슐화하거나 잘못된 방법을 이용함으로써 보안 취약점으로 작용하는 경우가 있습니다. 부적절한 캡슐화는 정보은닉의 기능을 잃어버립니다. 시스템의 중요 정보가 노출되어 공격자는 이 정보를 이용해 식별 과정을 우회할 수 있습니다. 변수 제어 함수가 노출된다면 공격자는 원하는 값으로 데이터를 외부에서 수정할 수 있게 됩니다.
7. API 오용
  API(Application Programming Interface)란 응용프로그램에서 사용할 수 있도록 운영체제나 프로그래밍 언어가 제공하는 기능을 제어할 수 있게 만든 인터페이스를 뜻합니다. 이렇게만 설명하면 명확한 개념이 잘 떠오르지 않습니다. 쉽게 말씀드리면 API는 프로그램들이 서로 소통하는 것을 도와주는 매개체 역할을 합니다. 음식점에서 주문을 받고 서빙을 해주는 웨이터에 비유할 수 있죠. 이렇듯 개발자는 편리하게 개발하고 유용한 정보를 얻기 위해 API를 활용합니다. 그러나 의도된 사용에 반하는 방법으로 API를 이용하거나, 보안에 취약한 API를 이용한다면 심각한 보안 취약점이 될 수 있습니다. 예를 들어, 만약 공격자에 의해 로컬 DNS 캐시가 오염된 상황에서 DNS만 확인한다면 공격자의 네트워크로 경유하거나 공격자의 서버를 도착지로 인식할 수도 있습니다. 이를 방지하기 위해 보안에 취약한 API 사용은 피해야 하며 DNS가 아닌 IP를 확인하는 것이 중요합니다.
마치며
Tumblr media
(https://www.freepik.com/free-vector/cyber-security-concept_7970724.htm#page=1&query=security&position=34)
지금까지 소프트웨어 개발 보안 가이드 시큐어 코딩 7가지 유형에 대해 알아보았습니다. 실제로 개발 보안 가이드를 보시면 더욱 자세한 내용을 확인하실 수 있습니다. 개발 단계뿐만 아니라 분석, 설계 단계의 보안 기법도 자세히 설명되어 있기에 꼭 한번 읽어보시는 것을 추천해 드립니다. 앞으로 디지털 트랜스포메이션과 IoT를 비롯한 SW 시장은 더욱 확대될 것입니다. 하지만 우리가 구성한 네트워크가 보안 위협의 통로가 될 수 있다는 것을 잊지 말아야 합니다. 이제 민관기관에서도 시큐어 코딩을 적극적으로 채택하고 있다고 하니, 시큐어 코딩에 대한 전문성을 길러보시는 것은 어떨까요? :) 오늘 내용이 여러분에게 많은 도움이 되셨길 바랍니다.
0 notes
delmondo · 5 years
Note
my favorite thing about jdbc is that you'd think the toString on PreparedStatement would just be the final query once you set all of the wildcards, but its fucking not (except under some drivers apparently). So you just cannot get the final fucking query from it after you set all the values.
are u kidding me. so depending on what driver you have the behavior is completely different? so this stupid final query thing is completely implementation specific?
3 notes · View notes
Text
Oxford Certified Advance Java Professional
Tumblr media
Oxford Certified Advance Java Professional
A Step ahead of Core Java – Advanced Java focuses on the APIs defined in Java Enterprise Edition, includes Servlet programming, Web Services, the Persistence API, etc. Oxford Software Institute provides the best classes in Advanced Java in Delhi and our course includes advanced topics like creating web applications by using technologies like Servlet, JSP, JSF, JDBC, EJB etc. We will further learn enterprise applications used a lot in banking sector.
JDBC, SERVLET AND JSP
The course will focus on JDBC, JDBC Drivers, Setting up a database and creating a schema, Connecting to DB, CRUD Operations, Rowset, Resultset, Preparedstatement, Connection Modes and much more. We will further learn the Basics of Servlet, Servlet Life Cycle, Working with Apache Tomcat Server, Servlet with JDBC, Servlet Collaboration, servletconfig, servletcontext, Attribute, Session, Tracking, Event and Listener, Filter, ServletInputStream etc. Under JSP, we’ll learn Basics of JSP, API, JSP in netbeans, Implicit Objects, Directive Elements, Taglib, Exception Handling, Action Elements, Expression Language, MVC, JSTL etc.
JAVAMAIL API, JMS AND JAVA NETWORKING
Under these topics, Oxford Software Institute offers best classes in Advanced Java such as Sending Email, Sending Email through Gmail server, Receiving Email, Sending HTML content, JMS Overview, JMS Messaging Domains, Example of JMS using Queue, Example of JMS using Topic, Networking Concepts, Socket Programming, URL class, URLConnection class, HttpURLConnection, InetAddress class, DatagramSocket class.
JQUERY, AJAX, MAVEN AND DAO PATTERN
The content has been prepared with utmost care at Oxford Software Institute where we provide the best classes with topics such as Introduction to JQuery, Validation, Forms, , Introduction to AJAX, Servlet and JSP with AJAX, Interacting with database, Maven, Ant Vs Maven, How to install Maven, Maven Repository, Understanding pom.xml, Maven Example, Maven Web App Example, Maven using NetBeans, DAO pattern, Singleton, DAO, DTO, MVC, Front Controller, Factory Method.
HIBERNATE AND SPRING FRAMEWORK
This session will focus on HB Introduction and Architecture, Hibernate with NetBeans, HB using XML, HB using Annotation, Web application, Generator classes, Dialects, Log4j, Inheritance Mapping, Mapping, Transaction Management, HQL, HCQL, Named Query, Caching, Second Level Cache, Integration, Struts. We will further learn about Spring Modules, Spring in NetBeans , Dependency Injection, JdbcTemplate, ORM, SPEL, MVC, MVC Form Tag Library, MVC Validation, MVC Tiles, Spring Remoting, OXM, Java Mail, Spring Security , Spring + Angular, CRUD Example, File Upload Example, Login & Logout Example, Search Field Example.
REST - REPRESENTATIONAL STATE TRANSFER
This session will focus on Installation of Jersey, Web container, required setup for Gradle and Eclipse web projects, How to Create your first RESTful WebService, How to Create a REST client, RESTful web services and JAXB, CRUD RESTful WebService, Rest Resources. We, at Oxford Software Institute will provide best classes that will focus on the practical applications of these concepts
SOFT SKILLS
Having a technical and discipline-specific expertise can help you get to the interview room but it’s the soft skills that will make the hiring manager hand you the appointment letter. In this course, students will also learn various Soft Skills like how to communicate professionally in English, Speaking in public without hesitation, using effective gestures and postures to appear impressive, managing stress and emotions and taking successful interviews. Oxford Software Institute provides the best classes in Soft-skill training.
CERTIFICATIONS*
During this course, students will be trained for the following certifications
Oxford Certified Advance Java Professional.
0 notes
reportwire · 2 years
Text
JDBC Batch Processing - Introduction and Demo Using Statement and Preparedstatement
JDBC Batch Processing – Introduction and Demo Using Statement and Preparedstatement
In the below video tutorial, take a closer look at JDBC batch processing, introduction, and demo using Statement and PreparedStatement. by Ram N · Apr. 21, 22 · Java Zone · Tutorial Source link
View On WordPress
0 notes
terwer-blog · 2 years
Text
JDBC的问题分析
自定义RPC框架
2022/03/06 校对完成
文章更新历史
2022/03/16 初稿。
原文地址:http://www.terwergreen.com/post/jdbc-de-wen-ti-fen-xi.html
核心实现
package test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; /** * @author terwer * @Description * @create 2021-11-30 23:18 */ public class Main { public static void main(String[] args) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { // 1、加载数据库驱动 Class.forName("com.mysql.jdbc.Driver"); // 2、获取数据库链接 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&useSSL=false", "root", "123456"); // 3、定义sql语句 String sql = "select * from user where username = ?"; // 4、获取预处理对象 preparedStatement = connection.prepareStatement(sql); // 5、设置参数 preparedStatement.setString(1, "hp"); // 6、拿到查询的数据库结果 resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { int id = resultSet.getInt("id"); String username = resultSet.getString("username"); User user = new User(); user.setId(id); user.setUsername(username); System.out.println("user = " + user.toString()); } // JDBC问题分析 // 1、数据库链接信息等存在硬编码 解决:配置文件 // 2、频繁创建释放数据库链接 解决:连接池(c3p0、druid) // 查询过程问题分析 // 1、sql语句、参数、结果集存在硬编码 解决:配置文件 // 结果集问题分析 // 1、需要手动封装结果集 解决:反射进行对象映射、内省 } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("释放资源"); } } }
1.1 问题分析
JDBC问题总结:
原始jdbc开发存在的问题如下:
1、 数据库连接创建、释放频繁造成系统资源浪费,从而影响系统性能。
2、 Sql语句在代码中硬编码,造成代码不易维护,实际应用中sql变化的可能较大,sql变动需要改变 java代码。
3、 使用preparedStatement向占有位符号传参数存在硬编码,因为sql语句的where条件不一定,可能 多也可能少,修改sql还要修改代码,系统不易维护。
4、 对结果集解析存在硬编码(查询列名),sql变化导致解析代码变化,系统不易维护,如果能将数据库记录封装成 pojo对象解析比较方便
1.2 问题解决思路
1使用数据库连接池初始化连接资源
2将sql语句抽取到xml配置文件中
3使用反射、内省等底层技术,自动将实体与表进行属性与字段的自动映射
mysql驱动链接
https://files.cnblogs.com/files/tangyouwei/mysql-connector-java-5.1.49.jar.zip
源码
Gitee版
https://gitee.com/youweics/senior-java-engineer-road/blob/master/p7-skill/framework/mybatis/jdbc-simple/src/main/java/com/terwergreen/App.java
Github版
https://github.com/terwer/senior-java-engineer-road/blob/master/p7-skill/framework/mybatis/jdbc-simple/src/main/java/com/terwergreen/App.java
1 note · View note
Text
Tumblr media
What are the differences between stored procedure and functions? . . . . For more questions about Java https://bit.ly/465SkSw Check the above link
0 notes
foxcy798 · 3 years
Text
Xampp For Java
Tumblr media
hey there, I am trying to set up tomcat on my computer (I am so new to this, I am not even sure I am explaining my problem correctly.)
I was told to install XAMPP. I did using the installer that appache's web site offers. It says that the installer installs tomcat too. I can see the tomcat folder inside my XAMPP folder, but when I check for status on localhost index page, I see 'tomcat deactivated'. and when I check for status under J2EE section I see the following:
XAMPP is a recursive acronym. The X identifies it as a cross-platform application. The rest of the letters identify the solutions provided in the package: Apache, MariaDB, PHP, and Perl. XAMPP allows you to run a web server installation right on your Windows, Linux, or Mac desktop computer. You don’t need access to the internet to test web development products. Xampp is available from our repository for fast and secure downloads in a new release (April 2021). I already have a UK worry with Java but it matters I'm currently underway and xampp everything. Lots of Negligible quantities give you nonstop fun of pictures nursery games. The web browser will not give you have to the xampp Human ISO file. Initially MySQL should be started in XAMPP control panel. Acronis pc. In command prompt, mysql should be started in the path of mysql bin. Database is created followed by Table creation and data is inserted into table via command prompt. Mysql connector jar file is required for the execution of the connectivity code in java that is added to the classpth. On the root of the Xampp folder you have one mysqlstart.bat and one mysqlstop.bat, for start/stop the mysql database included on the Xampp package. You can use they in another bat you should create to start your Java Desktop application. This is the simple way get the path where your xampp server is install. Then simply write this command in you main class constructor. Process xamppProcess=Runtime.getRuntime.exec('Path xamppstart.exe'); After this command write this command to connect to your Mysql database also get the saved path of mysql from your computer.
Warning! Tomcat is not started on port 8080.
one of the links in this page is: http://127.0.0.1:8080/. when I click on it, the page that comes up says: Firefox can't establish a connection to the server at 127.0.0.1:8080.
What is wrong? what am I missing. I kindly ask you to help me. thank you in advance!
5 Contributors
forum5 Replies
1,917 Views
11 Months Discussion Span
commentLatest PostLatest Postby mahadeb
alright, I have my issue solved. the problem was: after runing startup.bat (because I assumed the cmd windows should close itself), I'd assume that something was wrong since the cmd would not close, and I'd close it. no wonder it did not work then :)
This tutorial explains steps for mysql connector java i.e connect mysql database to netbeans java project. This consists of 4 steps as,
Tumblr media
Install XAMPP for MySQL
Create User, Database and Table in MySQL
Generate connection string in Netbeans project
Steps to insert records in table using JDBC.
Install XAMPP for MySQL
XAMPP is an open source software developed by Apache friends. XAMPP software package contains Apache distributions for Apache server, MariaDB, PHP, and Perl. And it is basically a local host or a local server.
Installation of XAMPP software is very easy. You can download XAMPP from here and just complete the installation wizard. then open XAMPP control panel and start apache and mysql services as shown in image below.
Create User, Database and Table in MySQL
To create a new database in MySQL, open browser, type localhost, then click on phpMyAdmin link, click on users tab and create new user and database.as shown in image below.
Click on Add new user and enter username , password & host-name localhost. the important step is select checkbox Create database with same name and grant all privileges & global privileges.then click on go button.
Xampp For Java 10
To Create Table.
Click on Database Tab, click on database name which just created. then enter table name and click on go button.
Generate connection string in Netbeans project
Open Netbeans, create new project, right click on project, select add library. select Library for MySQL JDBC Driver. then click on Add Library. Here you can download netbeans if you don't have.
Create New Database Connection
Then Goto Services tab, right click on database , click on new connection , select driver MySQL (Connector /J Driver), next , enter username and password of mysql database which you created. and check connection by test connection button. then copy JDBC URL which is connection string.
From Wikipedia, the free encyclopedia Just Mohabbat is an India television series which aired on Sony Entertainment Television channel from 1996 to 2000. The series was directed by Tony and Deeya Singh. Mohabbat 1 Season64 EpisodesRomanceGAsianet He lives under the dark shadow of a djinn while she is blessed with angelic qualities. What turn will Aman and Roshni's lives take when the two entangle in a 'magical' love story? Mohabbat serial hindi name. Phir Wohi Mohabbat (Urdu: پھر وہی محبت ‎, lit. 'That Love Again') is a Pakistani television series which started airing on Hum TV on 16 March 2017 every Thursday at 8:00 pm. It stars Ahmed Ali and Hania Amir as leads. The script was written by Mansoor Saeed and directed by Mohsin Mirza. The show was dubbed in Pashto under the title Biya Hagha Meena (Pashto: بیاهغه مینه.
Steps to insert records in table using JDBC
There are 6 steps to apply DML( Data Manipulation Language) statements on database using JDBC.
Load Driver - This instruction for JVM to load the desired driver implementation into memory for further JDBC requests. You can skip this step for JDBC 4.0 API because this load driver instruction in integrated in getConnection Method.
Tumblr media
Create Connection Object - The DriverManager class acts as an interface between user and drivers. Its static method is getConnection. This method take 3 parameters as connection-string(JDBC URL), database username & password.
Create Statement Object - Statement object is created by methods of connection object. createStatement, preparedStatement & callableStatement.
Write SQL statement - Here you can write SQL DML statements like INSERT, SELECT, UPDATE & DELETE. Here we insert a record in table using INSERT query.
Tumblr media
Xampp For Java
Execute Query on database - after writing a query string, we have to execute it on database. Query can be executed on database table by executeUpdate method of statement class.
Xampp For Javascript
Close connection - Active connection is terminated by close method of connection class.
Here is complete java code to insert a record into database using JDBC steps.
Goto Phpmyadmin and click on table to verify data insertion.
Tumblr media
0 notes
deltainfoteklive · 10 months
Text
What is JDBC - Java Database Connectivity
Tumblr media
JDBC, short for Java Database Connectivity, is an essential technology for developers who work with databases. It provides a way for Java applications to connect to, retrieve, and manipulate data from relational databases using the standard SQL language. History of JDBC The origins of JDBC can be traced back to the early days of Java development, when developers recognized the need for a standardized way to interact with databases. Initially, there were various third-party libraries and APIs available for this purpose, but they lacked uniformity and portability. In 1996, as part of the Java Development Kit (JDK) 1.1 release, Sun Microsystems introduced JDBC as the official API for connecting Java applications to databases. Over the years, JDBC has evolved to accommodate new features and technologies, making it a robust and widely used tool in the software development industry. How JDBC Works At a high level, JDBC works by establishing a connection to a database, sending SQL queries, and processing the results. The JDBC architecture consists of several key components that enable this functionality. The DriverManager class acts as the central point for managing JDBC drivers. It facilitates the establishment of database connections by loading the appropriate driver based on the connection URL provided. The Connection interface represents a connection to a specific database. It provides methods for executing SQL statements and managing transactions. The Statement and PreparedStatement interfaces are used to execute SQL queries and statements. PreparedStatement offers enhanced performance and security by allowing the use of parameter placeholders.The ResultSet interface holds the result of a query and provides methods for traversing and manipulating the data. Advantages of Using JDBC One of the key advantages of using JDBC is its ease of use. The API provides a simple and intuitive way to interact with databases, allowing developers to focus on the application logic rather than the intricacies of database connectivity. Another advantage is platform independence. JDBC is designed to work with any database that conforms to the SQL standard. This means that Java applications can seamlessly connect to various database systems without making significant changes to the codebase. Additionally, JDBC offers high performance. It leverages database-specific optimizations and connection pooling techniques to minimize the overhead associated with database operations. This enables efficient retrieval and manipulation of data, improving overall application performance. JDBC Drivers JDBC supports different types of drivers, each with its own features and characteristics. These drivers define how JDBC communicates with the underlying database. - Type 1: JDBC-ODBC bridge driver: This driver acts as a bridge between the JDBC API and the ODBC API. It requires the installation of ODBC drivers and performs translation between JDBC calls and ODBC calls. - Type 2: Native-API/partly Java driver: This driver communicates directly with the database using native API calls. It provides better performance than the Type 1 driver but requires database-specific client libraries to be installed. - Type 3: Network Protocol driver: This driver communicates with a middle-tier server that acts as a gateway between the application and the database. It provides network transparency and can work with any database that has a corresponding server-side component. - Type 4: Native-Protocol driver: This driver communicates directly with the database using a database-specific protocol. It offers the best performance and is purely written in Java, making it platform-independent. Using JDBC with Databases To use JDBC with a database, the first step is to establish a connection. This involves providing the necessary connection parameters such as the database URL, username, and password. Once the connection is established, SQL queries can be executed using the Statement or PreparedStatement objects. JDBC allows the execution of SELECT, INSERT, UPDATE, and DELETE queries, as well as the execution of stored procedures. The ResultSet object is used to retrieve and manipulate the results of a query. Best Practices for JDBC Development When developing applications with JDBC, there are several best practices to consider: - Connection management: It is important to properly manage database connections to avoid resource leaks and improve performance. Connections should be established only when needed and closed after use. - Statement and PreparedStatement usage: Use PreparedStatement whenever possible to prevent SQL injection attacks and enhance performance. Avoid dynamically building SQL statements using string concatenation. - Error handling and exception management: Properly handle exceptions and provide meaningful error messages. Use try-catch blocks to catch SQLExceptions and handle them gracefully. Common Issues and Troubleshooting While working with JDBC, developers may encounter various issues that can impact the performance and reliability of their applications. Some common issues include connection errors and query performance issues. Connection errors can occur due to incorrect connection parameters, network issues, or database outages. It is vital to handle these errors gracefully by providing appropriate error messages to the user and taking necessary actions to recover or terminate the application. Query performance issues can stem from inefficient SQL queries, lack of indexes, or large result sets. It is important to optimize the queries by using appropriate indexes and limiting the amount of data retrieved. Future of JDBC JDBC continues to evolve alongside advancements in database technology and Java development. Recent developments include support for new features such as distributed transactions, connection pooling, and enhanced security mechanisms.With the rise of cloud computing and big data technologies, JDBC is expected to play a crucial role in enabling Java applications to interact with modern data storage solutions, such as NoSQL databases and data lakes. Conclusion JDBC is a vital tool for Java developers working with databases. It provides a standardized and platform-independent way to connect Java applications to relational databases. By understanding the JDBC architecture, driver types, and best practices, developers can leverage the full potential of JDBC in their applications. FAQs - What is JDBC?JDBC (Java Database Connectivity) is an API that provides a standard set of Java classes for accessing relational databases. It allows Java programs to interact with databases using SQL queries. - How does JDBC work?JDBC works by establishing a connection to a database, sending SQL queries, and processing the results. It provides a set of classes and interfaces to handle database operations in a platform-independent manner. - What are the advantages of using JDBC?JDBC offers ease of use, platform independence, and high performance. It simplifies database interactions in Java applications and allows seamless integration with various database systems. - What are the different types of JDBC drivers?There are four types of JDBC drivers - Type 1: JDBC-ODBC bridge driver, Type 2: Native-API/partly Java driver, Type 3: Network Protocol driver, Type 4: Native-Protocol driver. - How can I handle connection errors in JDBC?Connection errors in JDBC can be handled by catching SQLExceptions and handling them gracefully. It is important to close the connection and release resources properly to prevent leaks. Read the full article
0 notes
globalmediacampaign · 3 years
Text
Compress and conquer with Amazon Keyspaces (for Apache Cassandra)
Amazon Keyspaces (for Apache Cassandra) is a scalable, highly available, and managed Apache Cassandra-compatible database service that enables you to run Cassandra workloads more easily by using a serverless, pay-as-you-go solution. With Amazon Keyspaces, you don’t have to worry about configuring and optimizing your Cassandra cluster for your mission-critical, operational workloads. Amazon Keyspaces provides you with single-digit-millisecond response times at any scale. You can build applications with virtually unlimited throughput and storage that can serve thousands of requests per second. To help deliver fast performance, Amazon Keyspaces has a 1 MB row-size quota (for more information, see Quotas for Amazon Keyspaces (for Apache Cassandra). However, you may already have rows larger than 1 MB in your existing Cassandra tables. To reduce the size of these rows, you can compress one or more large columns. Compressing large columns reduces your storage costs, improves performance, reduces I/O and network usage, and enables you to fit the data within the Amazon Keyspaces row quota. In this post, I show you how to compress your data using freely available compression tools and store that compressed data in Amazon Keyspaces. Prerequisites To get started, let’s first create one keyspace and two tables. Amazon Keyspaces stores data durably across multiple AWS Availability Zones using a replication factor of three for high availability. You don’t have to specify a replication factor when creating a new keyspace in Amazon Keyspaces; the service configures these settings automatically. The following code creates one keyspace: CREATE KEYSPACE compression WITH replication = {'class': 'com.amazonaws.cassandra.DefaultReplication'} AND durable_writes = true; Compression algorithms such as Snappy, LZ4, GZIP, and ZSTD generate binary output that you can store in a BLOB column type in your table. For this post, I use Snappy compression to compress my data. I decided to use the Snappy compression algorithm for the following reasons: Fast compression and decompression rate between 200–560 MB per second Low-memory-footprint; SnappyOutputStream uses only 32 KB+ by default Portable across various operating systems; Snappy-Java contains native libraries built for Window, Mac, and Linux (I did all tests on an Amazon Elastic Compute Cloud (Amazon EC2) instance with 8 vCPUs and 16 GB of RAM) Simple API Free for commercial and non-commercial use Compression ratio is 2.073 Now that you have the keyspace, you need to create two tables to benchmark using Snappy compression with Amazon Keyspaces data. The following script creates two key-value tables with a timeuuid partition key. Choosing timeuuid is ideal for natural distribution, conflict-free partition key values, and evenly distributes our workload across the table. The following code creates two tables with the timeuuid and blob columns: CREATE TABLE table_with_compressed_json ( id timeuuid PRIMARY KEY, data blob) CREATE TABLE table_with_uncompressed_json ( id timeuuid PRIMARY KEY, data blob) Preparing the data To work through our tests in this post, you need to download JSON objects with different sizes. For this post, I use 11,876 JSON objects that I downloaded from OpenFDA, but you can use any source of data available to you. For our use case, I prepared 937 JSON objects less or equal to 1 KB, 10,168 JSON objects between 1–4 KB, 527 JSON objects between 4–20 KB, and 244 JSON objects between 20–67 KB. Using Snappy and Amazon Keyspaces Let’s first import org.xerial.snapy.Snappy and a Cassandra driver in your Java project and then use Snappy.compress(byte[]) and Snappy.uncompress(byte[]) to compress and decompress bytes. For example: import org.xerial.snappy.Snappy; import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.cql.BoundStatement; import com.datastax.oss.driver.api.core.cql.PreparedStatement; import com.datastax.oss.driver.api.core.cql.ResultSet; import com.datastax.oss.driver.api.core.cql.Row; import com.datastax.oss.driver.api.core.uuid.Uuids; import java.nio.ByteBuffer; import java.util.UUID; String originalData = "Compress and Conquer with Amazon Keyspaces!"; List contactPoints = Collections.singletonList( InetSocketAddress.createUnresolved("service-endpoint", 9142)); // Let's create the cqlSession session = CqlSession.builder() .addContactPoints(contactPoints) .withSslContext(SSLContext.getDefault()) .withLocalDatacenter("your_region") .withAuthProvider(new SigV4AuthProvider("your_region")).build(); // compressedData might be persisted into Amazon Keyspaces in BLOB format byte[] compressedData = Snappy.compress(originalData.getBytes("UTF-8")); PreparedStatement writePs = session.prepare("insert into test1.table_with_compressed_json(id, data) VALUES(?,?);"); // Generate random timeUUID UUID uuid = Uuids.timeBased(); // Prepare write bound statement BoundStatement writeBoundStatement = writePs.bind(uuid,ByteBuffer.wrap(compressedData)).setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM); // Persist into Amazon Keyspaces session.execute(writeBoundStatement); // Compressed data might be read from Amazon Keyspaces PreparedStatement readPs = session.prepare("select data from test1.table_with_compressed_json where id = ?"); // Prepare read bound statement BoundStatement readBoundStatement = readPs.bind(uuid); ResultSet resultSet = session.execute(readBoundStatement); // Get the compressed row Row data = resultSet.one(); ByteBuffer raw_bytes = data.getByteBuffer("data"); // Uncompress data from raw bytes String result = new String(Snappy.uncompress(raw_bytes.array()), "UTF-8")); System.out.println(result); Running the write performance test To run the write performance tests, complete the following steps: Download the maven project from the AWS Samples GitHub. From the top directory, run mvn install. Configure resources/config.properties: Set contactPoint to the service endpoint. For example, us-east-1.amazonaws.com. Set port to 9142. Set region to your Region. For example, us-east-1. Set input_jsons to a path to your JSON file. For example, resources/device-enforcement-0001-of-0001.json. Set output_partitions_compressed to a path to compressed partitions file to read compressed data back by ID. For example, resources/compressed_partitions.out. Set output_partitions_uncompressed to a path of your uncompressed partitions file to read uncompressed data back by ID. For example, resources/uncompressed_partitions.out. Run the write performance test: java -cp SnappyKeyspaces-1.0-SNAPSHOT-jar-with-dependencies.jar PerformanceTestWriteRunner Running the performance test might incur costs to your account. For more information, see Amazon Keyspaces pricing. Running the read performance test To run the read performance tests, enter the following code: java -cp SnappyKeyspaces-1.0-SNAPSHOT-jar-with-dependencies.jar PerformanceTestReadRunner Running the performance test might incur costs to your account. For more information, see Amazon Keyspaces pricing. Configuring write and read latency metrics In this section, we walk you through configuring write and read latency metrics in Amazon CloudWatch. Write latency To add the write latencies for both tables, complete the following steps: On the Amazon Keyspaces console, on the Tables page, choose table_with_compressed_json or table_with_uncompressed_json. On the Capacity tab, choose Add to CloudWatch. Choose Widget Action and Write units per second. On the CloudWatch dashboard, choose Edit. Choose All Metrics and AWS/Cassandra. Choose Keyspace, Operation, and TableName. On the drop-down menu, choose the INSERT operation for table_with_compressed_json and table_with_uncompressed_json with the metric name SuccessfulRequestLatency. Choose Graph metrics. The dashboard shows write latencies for the compressed and uncompressed writes. In the Statistic column, choose the p99 metric. Choose Update widget. If you change the graph type from line to number, you see absolute write latencies in absolute numbers, as shown in the following screenshots. Read latency To add the read latencies for both tables, complete the following steps: Choose All Metrics and AWS/Cassandra. Choose Keyspace, Operation, and TableName. On the drop-down menu, choose the SELECT operation for table_with_compressed_json and table_with_uncompressed_json with the metric name SuccessfulRequestLatency. Choose Graph metrics. The dashboard shows read latencies for the compressed and uncompressed reads. In the Statistic column, choose the p99 metric. Choose Update widget. If you change the graph type from line to number, you see absolute read latencies in absolute numbers, as shown in the following screenshot. Analyzing the data The preceding graphs show that the p99 write latency of compressed objects improved by 18.5%, and the p99 read latency improved by 19.5%. The following table shows statistics I collected from the application side. I divided the files sizes across four different ranges to show how distribution changed after compression. The size of large objects between 20–67 KB reduced by 77.5%, objects between 4–20 KB reduced by 22%, and objects between 1–4 KB reduced by 24.2%, but the number of objects less or equal to 1 KB increased by 74.6%, which fits perfectly into 1 write capacity unit (WCU). JSON Objects https://aws.amazon.com/blogs/database/compress-and-conquer-with-amazon-keyspaces-for-apache-cassandra/
0 notes
tak4hir0 · 4 years
Link
この記事は Java Advent Calendar 2018 の 9 日目のエントリーです。 流行をとらえた話題が多いなか、10~15年前感のあるコンテンツです。化石です。 しかし化石とはいえ、よく使う技術ではあります。 ということで、何気なく使ってたけど改めて勉強し直しました。 検証バージョン java 1.8.0_181 JDBCドライバ postgresql 42.2.5 PostgreSQL 10.5 自前ビルド 検証環境 Java動作環境 Windows 10 Pro ver.1803 CPU 4コア(Hyper-Vと共用) RAM 16GB(うち、Hyper-Vへ8GB割り当て) Intel Core i5-4690 CPU 3.50GHz SSD PostgreSQL動作環境 Hyper-V 仮想インスタンス CentOS Linux release 7.1.1503 (Core) CPU 4コア(ホストと共用) RAM 8GB JDBCとは Javaからデータベースにアクセスするための標準API。 引用元 TECHSCORE 1. JDBC API ドライバには様々なタイプが存在するが、今回は一番メジャーなタイプ4(全てJavaで実装されているドライバ)の話に絞る。 引用元 TECHSCORE 1. JDBC API データベースアクセスの流れ 大まかな流れは以下のようになる。 ConnectionクラスでDBとの接続を確立する Statementクラスで実行したいSQLを定義して実行する ResultSetクラスでSQLの実行結果にアクセスする コードは以下のようになる。(close()処理をさぼってるので注意) public static void main(String[] args) throws SQLException { Connection conn = DriverManager.getConnection("jdbc:postgresql://192.168.11.116:5432/sampledb", "kimura", "test"); PreparedStatement pstmt = conn.prepareStatement("SELECT name,price FROM product"); pstmt.setFetchSize(2); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { System.out.println(rs.getString(1)); System.out.println(rs.getInt(2)); } } fetchSize SQLの実行結果を一括でJava側に取得すると、全データがメモリ上に確保されることになる。過度なインスタンス生成はOutOfMemoryErrorにつながるため、データを分割して取ってくる仕組みがある。1回に取ってくるデータサイズがfetchSize。 処理速度とメモリ利用量のトレードオフを考慮して決めることになる。 検証する 30万程度のレコードをfetchSize=0 と fetchSize=1000で取得してみる。 SELECT count(*) FROM sample; count --------- 3294112 (1 row) PostgreSQL JDBC Driver の場合はfetchSizeを有効にするには以下の条件がある。 conn.setAutoCommit(false)を忘れずに実行する。 The connection to the server must be using the V3 protocol. This is the default for (and is only supported by) server versions 7.4 and later. The Connection must not be in autocommit mode. The backend closes cursors at the end of transactions, so in autocommit mode the backend will have closed the cursor before anything can be fetched from it. *The Statement must be created with a ResultSet type of ResultSet.TYPE_FORWARD_ONLY. This is the default, so no code will need to be rewritten to take advantage of this, but it also means that you cannot scroll backwards or otherwise jump around in the ResultSet. The query given must be a single statement, not multiple statements strung together with semicolons. Chapter 5. Issuing a Query and Processing the Result public static void main(String[] args) throws SQLException, InterruptedException { Connection conn = DriverManager.getConnection("jdbc:postgresql://192.168.11.116:5432/postgres", "kimura", "test"); conn.setAutoCommit(false); PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM sample"); // 0と1000で試行する pstmt.setFetchSize(0); // この間にjconsoleをつなぐ TimeUnit.SECONDS.sleep(15); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { System.out.println(rs.getString(1)); } } fetchSize=0 だと、メモリ利用量が多いが、実行時間は短い。 fetchSize=1000 だと、メモリ利用量が少ないが、実行時間は長い。 SPI ConnectionやStatementやResultSetはすべてインタフェースである。 なぜインタフェースを通してプログラミングするだけでいいのか。実装クラスをnewする必要はないのか。これは、SPIという仕組みを利用している。 参考 Java Service Provider Interface これによって、MyBatisなどの3thパーティのライブラリがJDBC APIを利用してコーディングしておけば、ライブラリの利用者側で好きなJDBC実装と組み合わせて使える。 PreparedStatement ユーザ文字列をもとにSQLを組み立てるときに、ただの文字列として処理するとSQLインジェクションという脆弱性を生む可能性がある。PreparedStatementを使うと、この問題を防ぐことができる。 参考 Wikipedia SQLインジェクション 訴訟問題に発展する可能性もあるので、しっかりと対策したい。 参考 SQLインジェクション対策もれの責任を開発会社に問う判決 検証する まず、SQLインジェクションの脆弱性がある残念なコードを作る。 public static void main(String[] args) throws Exception { Connection conn = DriverManager.getConnection("jdbc:postgresql://192.168.11.116:5432/sampledb", "kimura", "test"); Statement pstmt = conn.createStatement(); String userInput = "alice"; ResultSet rs = pstmt.executeQuery("SELECT name, password FROM users WHERE name = '" + userInput + "'"); while (rs.next()) { System.out.println("name: " + rs.getString("name") + ", password: " + rs.getString("password")); } 実行結果は以下のとおり。String userInput = "alice"に従った内容だけが取得できるので、特に問題ないように見える。 name: alice, password: secret1 次に、ユーザからの入力部分を String userInput = "alice' OR '1' = '1"; に変えて実行してみる。すると、他のユーザの情報にもアクセスできている。 name: bob, password: secret2 name: alice, password: secret1 ここの問題点は、意図せずにSQLの構造を変化させられていること。 こんなときに、PreparedStatementを使う。 public static void main(String[] args) throws Exception { Connection conn = DriverManager.getConnection("jdbc:postgresql://192.168.11.116:5432/sampledb?loggerLevel=DEBUG", "kimura", "test"); PreparedStatement pstmt = conn.prepareStatement("SELECT name, password FROM users WHERE name = ?"); String userInput = "alice' OR '1' = '1"; pstmt.setString(1, userInput); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { System.out.println("name: " + rs.getString("name") + ", password: " + rs.getString("password")); } } 実行結果は以下の通り。先ほどのように、別のユーザ情報にアクセスできない。 PreparedStatementを利用すると、バインド変数部分が一つの文字列として解釈される。そのため、nameがalice' OR '1' = '1のものを探すことになる。意図せずにSQLの構造を変更させられることがないので、SQLインジェクション対策になる。 SQLException DBまわりのエラーはSQLExceptionという型でスローされる。 getMessage()でエラー文言が、getSQLState()でエラーコードが取得できる。 参考 SQLException Javadoc 参考 The Java? Tutorials Handling SQLExceptions PostgreSQLであれば、SQLStateは以下に詳細に定義されている。 PostgreSQL 10.5 付録A PostgreSQLエラーコード またJDBC4からSQLExceptionに階層が定義されている。例えば、シンタックスエラーを表すSQLSyntaxErrorExceptionといった具合に。しかし、PostgreSQL JDBC Driverでは対応していない様子。 Github Issue 『Support for JDBC 4.0 exception hierarchy』 PSQLExceptionさえあればいいんや!…というのは冗談としても、実際にWEBアプリケーションを組む場合はフレームワークが独自の階層を持った例外クラスに変換してくれることが多い。なので、実害はないように思う。 例えばSpring Frameworkであれば、2.1. Consistent Exception Hierarchyに記載されているような例外の型階層に変換してくれる。 検証する 構文として問題のあるSQLを実行し、SQLExceptionの中身を表示する。 public static void main(String[] args) throws Exception { Connection conn = DriverManager.getConnection("jdbc:postgresql://192.168.11.116:5432/sampledb", "kimura", "test"); conn.setAutoCommit(false); try { // FROM のtypo PreparedStatement pstmt = conn.prepareStatement("SELECT * FORM sample"); pstmt.executeQuery(); } catch (SQLException e) { System.out.println(e.getErrorCode()); System.out.println(e.getSQLState()); System.out.println(e.getMessage()); } } 実行結果は以下の通り。 0 // PostgreSQL JDBC Driverの場合は常に0 42601 ERROR: syntax error at or near "FORM" 位置: 10 ISOLATION_LEVEL Connection#setTransactionIsolationメソッドでトランザクションの隔離性を設定できる。AutoCommitがtrueになっているとSQL実行ごとに自動でトランザクションがコミットされるため、Connection#setAutoCommit(false)と組み合わせることが多い。 ISOLATION_LEVELの詳細は、データベースの知識なので割愛する。ここらへんは以前に調べた。 参考 PostgreSQL Isolation について JDBCコネクションプール 先述したConnectionをSQL実行の度にオープン/クローズすると、接続コスト(TCPコネクション確立~DBの認証)がその都度かかる。そのため、コネクションを使いまわすのがJavaの世界では一般的であり、この仕組みをコネクションプールと呼ぶ。 引用元 IBM Developer 第3回「JDBCとデータベース接続」 コネクションプールの実装によるが、以下のパラメータはたいてい存在する。 コネクションプール関連 コネクションのバリデーション関連 JDBC Driverのパラメータ操作関連 特に、コネクションプールの最大数を超えた要求が来た場合、要求スレッドはコネクションが返却されるのを待つことになる。最悪はタイムアウトして例外が発生することになるので、頻繁にタイムアウトが発生しないように注意する。 コネクションプールのメリット・デメリットは以下が詳しい。また、コネクションプール以外のデータベース接続アーキテクチャも記載されているので、ぜひとも一読するべき。 参考 Webシステムにおけるデータベース接続アーキテクチャ概論 AP視点のメリット DriverManager#getConnectionしたときのパケットをWireSharkでキャプチャすると、クライアント~サーバ間で複数回の通信が行われていることがわかる。 コネクションをプールすることで、上記のやり取りを省略できる。 検証する 以下の3つで、どれくらい接続コストが違うのかを確かめる。 単純にコネクションを使いまわした場合 コネクションプールライブラリを使った場合 都度接続した場合 なお、PostgreSQLは同一ホストの仮想環境に立っているので、ネットワーク的な遅延が低い状況である。 単純にコネクションを使いまわした場合 private static final int LOOP_COUNT = 10000; public static void main(String[] args) throws SQLException, InterruptedException { long start = System.currentTimeMillis(); Connection conn = DriverManager.getConnection("jdbc:postgresql://192.168.11.116:5432/postgres", "kimura", "test"); for (int i = 0; i < LOOP_COUNT; i++) { PreparedStatement pstmt = conn.prepareStatement("SELECT 1"); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { } rs.close(); pstmt.close(); } conn.close(); long end = System.currentTimeMillis(); System.out.println("time: " + (end - start)); } コネクションプールライブラリを使った場合 private static final int LOOP_COUNT = 10000; public static void main(String[] args) throws Exception { HikariConfig config = new HikariConfig(); config.setUsername("kimura"); config.setPassword("secret"); config.setJdbcUrl("jdbc:postgresql://192.168.11.116:5432/sampledb"); config.setMaximumPoolSize(2); long start = System.currentTimeMillis(); HikariDataSource ds = new HikariDataSource(config); for (int i = 0; i < LOOP_COUNT; i++) { Connection conn = ds.getConnection(); PreparedStatement pstmt = conn.prepareStatement("SELECT 1"); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { } rs.close(); pstmt.close(); conn.close(); } long end = System.currentTimeMillis(); System.out.println("time: " + (end - start)); } 都度接続した場合 private static final int LOOP_COUNT = 10000; public static void main(String[] args) throws SQLException, InterruptedException { long start = System.currentTimeMillis(); for (int i = 0; i < LOOP_COUNT; i++) { Connection conn = DriverManager.getConnection("jdbc:postgresql://192.168.11.116:5432/postgres", "kimura", "test"); PreparedStatement pstmt = conn.prepareStatement("SELECT 1"); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { } rs.close(); pstmt.close(); conn.close(); } long end = System.currentTimeMillis(); System.out.println("time: " + (end - start)); } 実行結果は以下の通り。 コネクション使いまわし コネクションプールライブラリ(HikariCP) 都度接続 1回目 2124 2522 42304 2回目 2363 2538 42890 3回目 2352 2593 41420 4回目 2275 2594 43021 5回目 2291 2280 43948 平均(ms) 2281 2505.4 42716.6 接続コスト(TCPコネクション確立~DBの認証)はそれなりにかかる、ということがわかった。 JDBCコネクションプール(DB視点) PostgreSQLはコネクションごとにpostgresプロセスをforkする。 PostgreSQL 10.5 第50章 PostgreSQL内部の概要 The Internals of PostgreSQL Process and Memory Architecture 引用元 The Internals of PostgreSQL Process and Memory Architecture そのため、同時接続数分だけプロセスを生成することになる。例えば、コネクションプール=3のときのPostgreSQLのプロセスは以下のようになる。 ]$ ps -ef | grep postgres kimura 1721 61604 0 13:21 ? 00:00:00 postgres: kimura sampledb 192.168.11.104(61246) idle kimura 1730 61604 0 13:22 ? 00:00:00 postgres: kimura sampledb 192.168.11.104(61251) idle kimura 1734 61604 0 13:22 ? 00:00:00 postgres: kimura sampledb 192.168.11.104(61253) idle ... 以下の理由から、コネクションプールを利用すると安定運用しやすい。 都度プロセスを生成するとコストが高い 同時接続数が決まるので、リソース使用量を見積もりやすい 検証する 都度プロセスを生成するのは、どのくらいコストが高いのかを確かめる。以下のコードを10秒間実行し、sarコマンドでCPU使用状況の平均を取る。 PostgreSQLの同時接続数は10と仮定する。 コネクション使いまわし(同時接続10) public static void main(String[] args) throws Exception { ExecutorService service = Executors.newFixedThreadPool(10); for (int j = 0; j < 10 { Connection conn = DriverManager.getConnection("jdbc:postgresql://192.168.11.116:5432/postgres", "kimura", "test");; while (true) { try { PreparedStatement pstmt = conn.prepareStatement("SELECT 1"); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { } rs.close(); pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } }); } } 都度接続(同時接続10) public static void main(String[] args) throws Exception { ExecutorService service = Executors.newFixedThreadPool(10); for (int j = 0; j < 10 { while (true) { try { Connection conn = DriverManager.getConnection("jdbc:postgresql://192.168.11.116:5432/postgres", "kimura", "test"); PreparedStatement pstmt = conn.prepareStatement("SELECT 1"); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { } rs.close(); pstmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }); } } 1つめがコネクション使いまわし、2つめが都度接続。 CPU %user %nice %system %iowait %steal %idle 平均値: all 4.09 0.00 33.13 0.00 0.00 62.78 平均値: all 14.24 0.00 61.06 0.03 0.00 24.68 (かなりアバウトかつDB負荷が高い条件ではあるけど)コネクションを使いまわしたほうが、DBとしても負荷が低いことがわかった。 workerプロセスごとにメモリをどれくらい使うのか コネクションプールした状態だと、どの位メモリを消費するかを確認する。都度接続のコードでConnection#close()せずに、10000本コネクションを張る。 テスト実行の前にキャッシュを捨てる。 /proc/sys/vm/drop_caches サーバ全体のメモリ状況は、検証前後で以下のようになった。 ]$ free total used free shared buff/cache available Mem: 10391784 5721584 4118352 370328 551848 4194024 Swap: 2097148 0 2097148 // 10000本コネクションを張る ]$ free total used free shared buff/cache available Mem: 10391784 6269028 3277516 372400 845240 3357384 Swap: 2097148 0 2097148 次に、workerプロセスに絞ったメモリ利用量は以下のようになった。 ]$ ps aux | grep "postgres: kimura postgres" | grep -v grep | awk '{print $2}' | xargs -i% cat /proc/%/smaps | awk '/^Pss/{sum += $2}END{print sum}' 2367442 (kb) PSSは物理メモリの使用量(共有メモリ分は、プロセス数で割った値を使う)のこと。 参考 プロセス毎のメモリ消費量を調べたい時に使えるコマンド PostgreSQLは共有メモリにディスクから取得したデータをキャッシュするので、RSSで見るとメモリ利用量を過大評価したことになるため。 参考 The Internals of PostgreSQL Buffer Manager 実行中のworkerの場合はwork_memやtemp_buffersなどが上乗せされるので、最終的にはメモリ利用量はもっと増えるはず。 PreparedStatementのキャッシュ DBCP2などのコネクションプールライブラリは、PrepatedStatementインスタンスを破棄せずに内部でキャッシュする。これによって、インスタンス生成コストが抑えられる。 ただし最近流行りのHikariCPでは、この機能を提供しておらず、次に示すサーバサイドステートメントキャッシュのみを提供している。 Many connection pools, including Apache DBCP, Vibur, c3p0 and others offer PreparedStatement caching. HikariCP does not. HikariCP README 検証する DBCP2を利用して、PreparedStatementがキャッシュされるのを確認する。 Apache Common DBCP2 BasicDataSource Configuration Parameters PreparedStatementがキャッシュされるのを確認する public static void main(String[] args) throws Exception { Properties props = new Properties(); props.setProperty("username", "kimura"); props.setProperty("password", "secret"); props.setProperty("url", "jdbc:postgresql://192.168.11.116:5432/sampledb"); props.setProperty("driverClassName", "org.postgresql.Driver"); props.setProperty("poolPreparedStatements", "true"); DataSource ds = BasicDataSourceFactory.createDataSource(props); while (true) { Connection conn = ds.getConnection(); PreparedStatement pstmt = conn.prepareStatement("SELECT 1"); Object pgstmt = pstmt.unwrap(DelegatingStatement.class) .getDelegate() .unwrap(DelegatingPreparedStatement.class).getDelegate() .unwrap(PoolablePreparedStatement.class).getDelegate(); System.out.println(pgstmt.getClass() + " " + pgstmt.hashCode()); pstmt.close(); conn.close(); } } 実行結果は以下の通り。 class org.postgresql.jdbc.PgPreparedStatement 627150481 class org.postgresql.jdbc.PgPreparedStatement 627150481 class org.postgresql.jdbc.PgPreparedStatement 627150481 class org.postgresql.jdbc.PgPreparedStatement 627150481 class org.postgresql.jdbc.PgPreparedStatement 627150481 class org.postgresql.jdbc.PgPreparedStatement 627150481 PreparedStatementインスタンスがキャッシュされていることがわかる。 次に、どれくらい性能が上がるかを調べる。 private static final int LOOP_COUNT = 10000; public static void main(String[] args) throws Exception { Properties props = new Properties(); props.setProperty("username", "kimura"); props.setProperty("password", "secret"); props.setProperty("url", "jdbc:postgresql://192.168.11.116:5432/sampledb"); props.setProperty("driverClassName", "org.postgresql.Driver"); // trueとfalseで比較する props.setProperty("poolPreparedStatements", "false"); long start = System.currentTimeMillis(); DataSource ds = BasicDataSourceFactory.createDataSource(props); for (int i = 0; i < LOOP_COUNT; i++) { Connection conn = ds.getConnection(); PreparedStatement pstmt = conn.prepareStatement("SELECT 1"); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { } rs.close(); pstmt.close(); conn.close(); } long end = System.currentTimeMillis(); System.out.println("time: " + (end - start)); } 結果は以下の通り。 キャッシュあり キャッシュなし 1回目 3689 4013 2回目 3485 3571 3回目 3741 3805 4回目 3957 4026 5回目 3674 3894 平均(ms) 3709.2 3861.8 PreparedStatementのキャッシュだけではあんまり差がでない。DBCP2的にも poolPreparedStatements はデフォルトでfalse。まあ、そういうことなんだろう。 サーバサイドステートメントキャッシュ JDBCドライバがサーバ側のプリペアド機能を利用して実現するキャッシュ。 PostgreSQLでは、同一コネクションで同じSQLが複数(デフォルトでは5回)発行されると、サーバサイドステートメントキャッシュが有効になる。 バックエンドは複数のプリペアド文とポータルの経過を追うことができます (しかし、1つのセッション内でのみ存在可能です。複数のセッションで共有することはできません)。 PostgreSQL 10.5 第52章 フロントエンド/バックエンドプロトコル プリペアド文が利用されるとDB側の構文解析や実行計画といったフェーズがスキップできるため、DB側の処理が削減される。 引用元 The Internals of PostgreSQL Query Processing また、JDBCドライバとしても、通信時にヘッダー情報を要求しなくなる、といった通信プロトコルレベルの最適化を実施する。 しかし、プリペアド文を利用すると、コネクションごとに構文解析したクエリやカーソルが保持される。メモリ消費を制限するための上限を設定するパラメータとして、preparedStatementCacheQueries(デフォルト 256) や preparedStatementCacheSizeMiB(デフォルト 5) がある。 参考 PostgreSQL JDBC Driver hapter 9. PostgreSQL? Extensions to the JDBC API 検証する サーバサイドステートメントキャッシュの性能差を比較する。 PgConnection#setPrepareThresholdでサーバサイドステートメントキャッシュのしきい値を設定する。 private static final int LOOP_COUNT = 10000; public static void main(String[] args) throws SQLException, InterruptedException { Connection conn = DriverManager.getConnection("jdbc:postgresql://192.168.11.116:5432/postgres", "kimura", "test"); PGConnection pgconn = conn.unwrap(PGConnection.class); // 有効のときは 1 を設定。無効のときは LOOP_COUNT + 1 を設定 pgconn.setPrepareThreshold(LOOP_COUNT + 1); conn.setAutoCommit(false); PreparedStatement pstmt = conn.prepareStatement("SELECT * from sample WHERE id = ?"); long start = System.currentTimeMillis(); for (int i = 0; i < LOOP_COUNT; i++) { pstmt.setInt(1, i); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { } } long end = System.currentTimeMillis(); System.out.println("time: " + (end - start)); } 実行結果は以下の通り。 prepareThresholdが有効 prepareThresholdが無効 1回目 2165 3207 2回目 2222 3177 3回目 2146 3170 4回目 2447 3230 5回目 1944 3076 平均(ms) 2184.8 3172 PrepareThresholdが効いているほうが、けっこう早く終わることがわかった。 リクエストの最適化 通常のリクエスト。だいたい5ステップある。 ... PostgreSQL Type: Parse // 構文解析 Length: 54 Statement: Query: SELECT id, price FROM sample WHERE id = $1 Parameters: 1 Type OID: 23 PostgreSQL Type: Bind // $1の変数の値をセット Length: 22 Portal: Statement: Parameter formats: 1 Format: Binary (1) Parameter values: 1 Column length: 4 Data: 00000002 Result formats: 0 PostgreSQL Type: Describe // レスポンスにヘッダー情報付与 Length: 6 Portal: PostgreSQL Type: Execute // SQL実行 Length: 9 Portal: Returns: all rows PostgreSQL Type: Sync // お決まりのやつらしい Length: 4 ステートメントキャッシュ開始時点のリクエスト。 ... PostgreSQL Type: Parse // プリペアド文の要求 Length: 57 Statement: S_1 Query: SELECT id, price FROM sample WHERE id = $1 Parameters: 1 Type OID: 23 PostgreSQL Type: Bind // $1の変数の値をセット Length: 25 Portal: Statement: S_1 Parameter formats: 1 Format: Binary (1) Parameter values: 1 Column length: 4 Data: 00000002 Result formats: 0 PostgreSQL Type: Describe // レスポンスにヘッダー情報付与 Length: 6 Portal: PostgreSQL Type: Execute // SQL実行 Length: 9 Portal: Returns: all rows PostgreSQL Type: Sync // お決まりのやつらしい Length: 4 ステートメントキャッシュが有効になったあとのリクエスト。 Parseが無くなっている Describeがなくなっている ... PostgreSQL Type: Bind Length: 29 Portal: Statement: S_1 Parameter formats: 1 Format: Binary (1) Parameter values: 1 Column length: 4 Data: 00000002 Result formats: 2 Format: Binary (1) Format: Binary (1) PostgreSQL Type: Execute Length: 9 Portal: Returns: all rows PostgreSQL Type: Sync Length: 4 レスポンスの最適化 通常のレスポンス。 ... PostgreSQL Type: Parse completion //構文解析完了 Length: 4 PostgreSQL Type: Bind completion // $1の変数の値をセットが完了 Length: 4 PostgreSQL Type: Row description // Describe要求に対応 Length: 51 Field count: 2 Column name: id Table OID: 24576 Column index: 1 Type OID: 23 Column length: 4 Type modifier: -1 Format: Text (0) Column name: price Table OID: 24576 Column index: 2 Type OID: 23 Column length: 4 Type modifier: -1 Format: Text (0) PostgreSQL Type: Data row // データ行 Length: 18 Field count: 2 Column length: 1 Data: 32 Column length: 3 Data: 323030 PostgreSQL Type: Command completion //コマンド完了 Length: 13 Tag: SELECT 1 PostgreSQL Type: Ready for query // 次の要求待ち Length: 5 Status: Idle (73) ステートメントキャッシュが有効になった状態のレスポンス。 テーブルヘッダ情報がない Data row にも型情報がない ... PostgreSQL Type: Bind completion // $1の変数の値をセットが完了 Length: 4 PostgreSQL Type: Data row // データ行 Length: 22 Field count: 2 Column length: 4 Data: 00000002 Column length: 4 Data: 000000c8 PostgreSQL Type: Command completion //コマンド完了 Length: 13 Tag: SELECT 1 PostgreSQL Type: Ready for query // 次の要求待ち Length: 5 Status: Idle (73) 異なるPreparedStatementインスタンスでもキャッシュが効くか 同一コネクションから生成されたPreparedStatementインスタンスであれば、各インスタンスをまたいでキャッシュが効くことを確認する。 public static void main(String[] args) throws Exception { Connection conn = DriverManager.getConnection("jdbc:postgresql://192.168.11.116:5432/sampledb", "kimura", "test"); PGConnection pgconn = conn.unwrap(PGConnection.class); pgconn.setPrepareThreshold(2); for (int i = 0; i < 2; i++) { PreparedStatement pstmt = conn.prepareStatement("SELECT 1"); PGStatement pgStatement = pstmt.unwrap(PGStatement.class); System.out.println(pgStatement.isUseServerPrepare()); pstmt.executeQuery(); pstmt.close(); } } 実行結果は以下の通り。 false true 同一Connecionであれば、PreparedStatementが違ってもキャッシュされることがわかった。 ソースコードでいうと、以下のあたりが該当箇所だった。 PgPreparedStatement#executeInternal QueryExecutorImpl#sendParse 最後に JDBCドライバは断片的な知識をもとにググりながら使うことが多かったので、全体的に学び直すことでいい勉強になった。
0 notes
siva3155 · 5 years
Text
300+ TOP JSP Interview Questions and Answers
JSP Interview Questions for freshers experienced :-
1. What is a JSP and what is it used for? Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page. 2. What are the two kinds of comments in Jsp and what's the difference between them ? 3. What is Jsp technology? Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a server-side scripting language. 4. What Is Jsp Page? A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content. 6. What are the implicit objects? Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are: request response pageContext session application out config page exception 6. How many Jsp Scripting Elements and what are they? There are three scripting language elements: declarations scriptlets expressions 7. Why Are Jsp Pages The Preferred Api For Creating A Web-based Client Program? Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs. 8. Is Jsp technology extensible? YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries. 9. Can We Use The Constructor, Instead Of Init(), To Initialize Servlet? Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or Servlet Context. 10. How Can A Servlet Refresh Automatically If Some New Data Has Entered The Database? You can use a client-side Refresh or Server Push.
Tumblr media
JSP Interview Questions 11. The Code In A Finally Clause Will Never Fail To Execute, Right? Using System.exit(1); in try block will not allow finally code to execute. 12. How Many Messaging Models Do Jms Provide For and What Are They? JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing. 13. What Information Is Needed To Create A Tcp Socket? The Local Systems IP Address and Port Number. And the Remote System’s IPAddress and Port Number. 14. What Class.forname Will Do While Loading Drivers? It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS. 15. How To retrieve warnings? SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object . SQLWarning warning = stmt.getWarnings(); if (warning != null) { while (warning != null) { System.out.println(\"Message: \" + warning.getMessage()); System.out.println(\"SQLState: \" + warning.getSQLState()); System.out.print(\"Vendor error code: \"); System.out.println(warning.getErrorCode()); warning = warning.getNextWarning(); } } 16. How Many Jsp Scripting Elements are there and what are they? There are three scripting language elements: declarations, scriptlets, expressions. 17. In The Servlet 2.4 Specification Singlethreadmodel has Been Deprecated, Why? Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level. 18. What Are Stored Procedures? How Is It Useful? A stored procedure is a set of statements/commands which reside in the database. The stored procedure is pre-compiled and saves the database the effort of parsing and compiling sql statements every time a query is run. Each database has its own stored procedure language, usually a variant of C with a SQL preproceesor. Newer versions of db’s support writing stored procedures in Java and Perl too. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems still do it). The biggest advantage is of course speed. Also certain kind of data manipulations are not achieved in SQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases. 19. How Do I Include Static Files Within A Jsp Page? Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request. 20. Why Does Jcomponent have add() And remove() Methods But Component does not? Because JComponent is a subclass of Container, and can contain other components and jcomponents. How can I implement a thread-safe JSP page? - You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive within your JSP page. 21. How Do I Prevent The Output Of My Jsp Or Servlet Pages From Being Cached By The Browser? You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions. 22. How Do You Restrict Page Errors Display In The Jsp Page? You first set "Errorpage" attribute of PAGE directory to the name of the error page (ie Errorpage= "error.jsp")in your jsp page .Then in the error jsp page set "isErrorpage=TRUE". When an error occur in your jsp page it will automatically call the error page. 23. What Jsp Lifecycle Methods Can I Override? You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy(). The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations: 24. How Do I Perform Browser Redirection From A Jsp Page? You can use the response implicit object to redirect the browser to a different resource, as: response. send Redirect ; You can also physically alter the Location HTTP header attribute, as shown below: You can also use the: Also note that you can only use this before any output has been sent to the client. I beleve this is the case with the response.sendRedirect() method as well. If you want to pass any paramateres then you can pass using. 25. How Does Jsp Handle Run-time Exceptions? You can use the errorPage attribute of the page directive to have uncaught runtime exceptions automatically forwarded to an error processing page. For example: redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: the Throwable object describing the exception may be accessed within the error page via the exception implicit object. 26. How Do I Use Comments Within A Jsp Page? You can use "JSP-style" comments to selectively block out code while debugging or simply to comment your scriptlets. JSP comments are not visible at the client. For example: --%> You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example: Of course, you can also use comments supported by your JSP scripting language within your scriptlets. 27. Is It Possible To Share An Httpsession Between A Jsp And Ejb? What Happens When I Change A Value In The Httpsession From Inside An Ejb? You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable. This has to be consider as "passed-by-value", that means that it's read-only in the EJB. If anything is altered from inside the EJB, it won't be reflected back to the HttpSession of the Servlet Container. The "pass-byreference" can be used between EJBs Remote Interfaces, as they are remote references. While it IS possible to pass an HttpSession as a parameter to an EJB object, it is considered to be "bad practice" in terms of object oriented design. This is because you are creating an unnecessary coupling between back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejb's api. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your ejb needs to support a non-http-based client. This higher level of abstraction will be flexible enough to support it. 28. How Can I Implement A Thread-safe Jsp Page? You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive within your JSP page. 29. How Can I Declare Methods Within My Jsp Page? You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you declare, or within JSP scriptlets and expressions. Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare. For example: Another Example: file1.jsp: file2.jsp 30. Can I Stop Jsp Execution While In The Midst Of Processing A Request? Yes. Preemptive termination of request processing on an error condition is a good way to maximize the throughput of a high-volume JSP engine. The trick (assuming Java is your scripting language) is to use the return statement when you want to terminate further processing. 31. Can A Jsp Page Process Html Form Data? Yes. However, unlike Servlet, you are not required to implement HTTP-protocol specific methods like doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via the request implicit object within a scriptlet or expression as. 32. Is there a way To reference the "this" variable within a Jsp Page? Yes, there is. Under JSP 1.0, the page implicit object is equivalent to "this", and returns a reference to the Servlet generated by the JSP page. 33. Is There A Way I Can Set The Inactivity Lease Period On A Per-session Basis? Typically, a default inactivity lease period for all sessions is set within your JSPengine admin screen or associated properties file. However, if your JSP engine supports the Servlet 2.1 API, you can manage the inactivity lease period on a per-session basis. This is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the session has been created. 34. How Does A Servlet Communicate With A Jsp Page? The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing. public void doPost (HttpServletRequest request, HttpServletResponse response) { try { govi.FormBean f = new govi.FormBean(); String id = request.getParameter("id"); f.setName(request.getParameter("name")); f.setAddr(request.getParameter("addr")); f.setAge(request.getParameter("age")); //use the id to compute //additional bean properties like info //maybe perform a db query, etc. // . . . f.setPersonalizationInfo(info); request.setAttribute("fBean",f); getServletConfig().getServletContext().getRequestDispatcher ("/jsp/Bean1.jsp").forward(request, response); } catch (Exception ex) { . . . } } The JSP page Bean1.jsp can then process fBean, a fter first extracting it from the default request scope via the useBean action. jsp:useBean id="fBean" class="govi.FormBean" scope="request"/ jsp:getProperty name="fBean" property="name" / jsp:getProperty name="fBean" property="addr" / jsp:getProperty name="fBean" property="age" / jsp:getProperty name="fBean" property="personalizationInfo" / 35. Can You Make Use Of A Servletoutputstream Object From Within A Jsp Page? No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object out) for replying to clients. A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementational perspective, it is not. 36. Can A Jsp Page Instantiate A Serialized Bean? No problem! The use Bean action specifies the beanName attribute, which can be used for indicating a serialized bean. For example: A couple of important points to note. Although you would have to name your serialized file "filename.ser", you only indicate "filename" as the value for the beanName attribute. Also, you will have to place your serialized file within the WEB-INFjspbeans directory for it to be located by the JSP engine. 37. What Is Jsp? Let's consider the answer to that from two different perspectives: that of an HTML designer and that of a Java programmer. If you are an HTML designer, you can look at JSP technology as extending HTML to provide you with the ability to seamlessly embed snippets of Java code within your HTML pages. These bits of Java code generate dynamic content, which is embedded within the other HTML/XML content you author. Even better, JSP technology provides the means by which programmers can create new HTML/XML tags and JavaBeans components, which provide new features for HTML designers without those designers needing to learn how to program. Note: A common misconception is that Java code embedded in a JSP page is transmitted with the HTML and executed by the user agent (such as a browser). This is not the case. A JSP page is translated into a Java servlet and executed on the server. JSP statements embedded in the JSP page become part of the servlet generated from the JSP page. The resulting servlet is executed on the server. It is never visible to the user agent. If you are a Java programmer, you can look at JSP technology as a new, higher-level means to writing servlets. Instead of directly writing servlet classes and then emitting HTML from your servlets, you write HTML pages with Java code embedded in them. The JSP environment takes your page and dynamically compiles it. Whenever a user agent requests that page from the Web server, the servlet that was generated from your JSP code is executed, and the results are returned to the user. 38. How Do I Mix Jsp And Ssi #include? What Is The Difference Between Include Directive & Jsp:include Action? If you're just including raw HTML, use the #include directive as usual inside your .jsp file. But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. If your data.inc file contains jsp code you will have to use The is used for including non-JSP files. include directive - - as is the case with all other directives in a JSP page, this include directive is also processed at the time when the JSP page is translated into its equivalent servlet. This directive simply causes the contents of the specified file to be pasted into the JSP page at the place where the page contains this directive. Irrespective of whether the included resource is a static resource or a JSP page - only the contents of the file are pasted (and not the processed results). This directive is normally used for including static resources only - like, banner, header, footer, etc. for the obvious reason. include action - this include action is executed at run time and the specified 'page' is first executed and then the result of that 'page' is appended to the response object of the calling JSP at the point where the tag occurs. Obviously if the specified page is a static resource then the contents of it are included as there won't be an executed result in that case. This action allows additional parameters to be passed via child element of this include action element. 39. How Do You Prevent The Creation Of A Session In A Jsp Page And Why? What Is The Difference Between Include Directive & Jsp:include Action? By default, a JSP page will automatically create a session for the request if one does not exist. However, sessions consume resources and if it is not necessary to maintain a session, one should not be created. For example, a marketing campaign may suggest the reader visit a web page for more information. If it is anticipated that a lot of traffic will hit that page, you may want to optimize the load on the machine by not creating useless sessions. 40. How Can I Set A Cookie And Delete A Cookie From Within A Jsp Page? A cookie, mycookie, can be deleted using the following scriptlet: 41. How Do You Connect To The Database From Jsp? A Connection to a database can be established from a jsp page by writing the code to establish a connection using a jsp scriptlets. Further then you can use the resultset object "res" to read data in the following way. 42. What Is The Page Directive Is Used To Prevent A Jsp Page From Automatically Creating A Session? 43. How Do You Delete A Cookie Within A Jsp? Cookie mycook = new Cookie("name","value"); response.addCookie(mycook); Cookie killmycook = new Cookie("mycook","value"); killmycook.setMaxAge(0); killmycook.setPath("/"); killmycook.addCookie(killmycook); 44. Can We Implement An Interface In A Jsp? No 45. What Is The Difference Between Servletcontext And Pagecontext? ServletContext: Gives the information about the container PageContext: Gives the information about the Request. 46. What Is The Difference In Using Request.getrequestdispatcher() And Context.getrequestdispatcher()? request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource. 47. How To Pass Information From Jsp To Included Jsp? Using tag. 48. How Is Jsp Include Directive Different From Jsp Include Action. ? When a JSP include directive is used, the included file's code is added into the added JSP page at page translation time, this happens before the JSP page is translated into a servlet. While if any page is included using action tag, the page's output is returned back to the added page. This happens at runtime. 49. Can We Override The Jspinit(), _jspservice() And Jspdestroy() Methods? We can override jspinit() and jspDestroy() methods but not _jspService(). 50. Why Is _jspservice() Method Starting With An '_' While Other Life Cycle Methods Do Not? _jspService() method will be written by the container hence any methods which are not to be overridden by the end user are typically written starting with an '_'. This is the reason why we don't override _jspService() method in any JSP page. 51. What Happens When A Page Is Statically Included In Another Jsp Page? An include directive tells the JSP engine to include the contents of another file (HTML, JSP, etc.) in the current page. This process of including a file is also called as static include. 52. A Jsp Page, Include.jsp, Has A Instance Variable "int A", Now This Page Is Statically Included In Another Jsp Page, Index.jsp, Which Has A Instance Variable "int A" Declared. What Happens When The Index.jsp Page Is Requested By The Client? Compilation error, as two variables with same name can't be declared. This happens because, when a page is included statically, entire code of included page becomes part of the new page. at this time there are two declarations of variable 'a'. Hence compilation error. 53. Can You Override Jspinit() Method? If Yes, In Which Cases? yes, we can. We do it usually when we need to initialize any members which are to be available for a servlet/ JSP throughout its lifetime. 54. What Is The Difference Between Directive Include And Jsp Include? include directive : The file gets included at the compile time. it is static in nature.output comes with jsp page but whole file contains is included in jsp then compilation is done. action tag : The file gets included at the run time. This is faster. it is dynamic in nature.output of yhe file willbe included in the jsp file. 55. What Is The Difference Between Requestdispatcher And Sendredirect? RequestDispatcher: server-side redirect with request and response objects. sendRedirect : Client-side redirect with new request and response objects. 56. How Does Jsp Handle Runtime Exceptions? Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP. 57. How Can My Application Get To Know When A Httpsession Is Removed? Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method. Create an instance of that class and put that instance in HttpSession. 58. What Is A Output Comment? A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser. JSP Syntax Example 1 Displays in the page source: 59. What Is A Hidden Comment? A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page. You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>. JSP Syntax Examples 60. What Is A Expression? An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like You cannot use a semicolon to end an expression. 61. What Is A Declaration? A declaration declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file. 62. What Is A Scriptlet? A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can Declare variables or methods to use later in the file (see also Declaration). Write expressions valid in the page scripting language (see also Expression). Use any of the JSP implicit objects or any object declared with a tag. You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet. Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it. 63. What Are Implicit Objects? List Them? Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below request response pageContext session application out config page exception. 64. Difference Between Forward And Sendredirect? When you invoke a forward request, the request is sent to another resource ohe server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward. 65. What Are The Different Scope Valiues For The ? The different scope values for are 1. page 2. request 3.session 4.application. 66. Explain The Life-cycle Mehtods In Jsp? The generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP page regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method_jspService(). The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance. The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects. The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance. 67. What's A Better Approach For Enabling Thread-safe Servlets And Jsps? Singlethreadmodel Interface Or Synchronization? Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading. Also, note that SingleThreadModel is pretty resource intensive from the server\'s perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool. 68. What Is The Difference Between Jsp And Servlets ? JSP is used mainly for presentation only. A JSP can only be HttpServlet that means the only supported protocol in JSP is HTTP. But a servlet can support any protocol like HTTP, FTP, SMTP etc. 69. What Is Difference Between Custom Jsp Tags And Beans? Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components: the tag handler class that defines the tag's behavior ,the tag library descriptor file that maps the XML element names to the tag implementations and the JSP file that uses the tag library. JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags . Custom tags and beans accomplish the same goals -- encapsulating complex behavior into simple and accessible forms. There are several differences. Custom tags can manipulate JSP content; beans cannot. Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags require quite a bit more work to set up than do beans. Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page. Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions. 70. What Are The Different Ways For Session Tracking? Cookies, URL rewriting, HttpSession, Hidden form fields. 71. What Mechanisms Are Used By A Servlet Container To Maintain Session Information? Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information. 72. Difference Between Get And Post? In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 255 characters, not secure, faster, quick and easy. The data is submitted as part of URL. In POST data is submitted inside body of the HTTP request. The data is not visible on the URL and it is more secure. 73. What Is Session? The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests. The session is stored on the server. 74. What Is Servlet Mapping? The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to Servlets. 75. What Is Servlet Context ? The servlet context is an object that contains a information about the Web application and container. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. 76. What Is A Servlet ? servlet is a java program that runs inside a web container. 77. How Is Scripting Disabled? Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a sub element of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is as follows: *.jsp true 78. What Is A Jsp Expression? A JSP expression is used to write an output without using the out.print statement. It can be said as a shorthand representation for scriptlets. An expression is written between the tags. It is not required to end the expression with a semicolon, as it implicitly adds a semicolon to all the expressions within the expression tags. 79. What Are Jsp Declarations? As the name implies, JSP declarations are used to declare class variables and methods in a JSP page. They are initialized when the class is initialized. Anything defined in a declaration is available for the whole JSP page. A declaration block is enclosed between the tags. A declaration is not included in theservice() method when a JSP is translated to a servlet. 80. What Is The Jsp:plugin Action ? This action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the browser run an applet using the Java plugin. 81. What Are Scripting Elements? JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page. There are three forms: Expressionsof the form that are evaluated and inserted into the output, Scriptletsof the form that are inserted into the servlet's service method, Declarationsof the form that are inserted into the body of the servlet class, outside of any existing methods. 82. What Is The Standard Action? The standard action is used with or to pass parameter names and values to the target resource. The syntax of the standard action is as follows: 83. What Is The Jsp:getproperty Action? The action is used to access the properties of a bean that was set using the action. The container converts the property to a String as follows: If it is an object, it uses the toString() method to convert it to a String. If it is a primitive, it converts it directly to a String using the valueOf() method of the corresponding Wrapper class. The syntax of the method is: Here, name is the id of the bean from which the property was set. The property attribute is the property to get. A user must create or locate a bean using the action before using the action. 84. Differentiate Between Pagecontext.include And Jsp:include? The standard action and thepageContext.include() method are both used to include resources at runtime. However, thepageContext.include() method always flushes the output of the current page before including the other components, whereas flushes the output of the current page only if the value = of flush is explicitly set to true as follows: 85. What Is The Standard Action? The standard action enables the current JSP page to include a static or a dynamic resource at runtime. In contrast to the include directive, the include action is used for resources that change frequently. The resource to be included must be in the same context.The syntax of the standard action is as follows: Here, targetPage is the page to be included in the current JSP. 86. What Is The Standard Action? The standard action is used to locate an existing JavaBean or to create a JavaBean if it does not exist. It has attributes to identify the object instance, to specify the lifetime of the bean, and to specify the fully qualified classpath and type. 87. What Are The Standard Actions Available In Jsp? The standard actions available in JSP are as follows: It includes a response from a servlet or a JSP page into the current page.It differs from an include directive in that it includes a resource at request processing time, whereas the include directive includes a resource at translation time. It forwards a response from a servlet or a JSP page to another page. It makes a JavaBean available to a page and instantiates the bean. It sets the properties for a JavaBean. It gets the value of a property from a JavaBean component and adds it to the response. It is used in conjunction with ;, ; to add a parameter to a request. These parameters are provided using the name-value pairs. It is used to include a Java applet or a JavaBean in the current JSP page. 88. What Are The Jsp Standard Actions? The JSP standard actions affect the overall runtime behavior of a JSP page and also the response sent back to the client. They can be used to include a file at the request time, to find or instantiate a JavaBean, to forward a request to a new page, to generate a browser-specific code, etc. Ex: include, forward, useBean,etc. 89. What Is The Include Directive? There are thirteen attributes defined for a page directive of which the importantattributes are as follows: The include directive is used to statically insert the contents of a resource into the current JSP. This enables a user to reuse the code without duplicating it, and includes the contents of the specified file at the translation time. The syntax of the include directive is as follows: This directive has only one attribute called file that specifies the name of the file to be included. 90. What Are The Attributes Of Page Directive? There are thirteen attributes defined for a page directive of which the important attributes are as follows: import: It specifies the packages that are to be imported. session: It specifies whether a session data is available to the JSP page. contentType: It allows a user to set the content-type for a page. isELIgnored: It specifies whether the EL expressions are ignored when a JSP is translated to a servlet. 91. What Is Page Directive? A page directive is to inform the JSP engine about the headers or facilities that page should get from the environment. Typically, the page directive is found at the top of almost all of our JSP pages. There can be any number of page directives within a JSP page (although the attribute – value pair must be unique). The syntax of the include directive is: Example: 92. What Are Jsp Directives? • JSP directives are messages for the JSP engine. i.e., JSP directives serve as a message from a JSP page to the JSP container and control the processing of the entire page. • They are used to set global values such as a class declaration, method implementation, output content type, etc. • They do not produce any output to the client. • Directives are always enclosed within tag. • Ex: page directive, include directive, etc. 93. What Are Advantages Of Jsp whenever there is a change in the code, we dont have to recompile the jsp. it automatically does the compilation. by using custom tags and tag libraries the length of the java code is reduced. 94. How Do I Use A Scriptlet To Initialize A Newly Instantiated Bean? A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone. The following example shows the "today" property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action. value=""/ > 95. What Is The Page Directive Is Used To Prevent A Jsp Page From Automatically Creating A Session: 96. What Are The Steps Required In Adding A Jsp Tag Libraries? Create a TLD file and configure the required class Information. Create the Java Implementation Source extending the JSP Tag Lib Class (TagSupport). Compile and package it as loosed class file or as a jar under lib folder in Web Archive File for Class loading. Place the TLD file under the WEB-INF folder. Add reference to the tag library in the web.xml file. 97. Outline The Major Difference Between The Session And Cookie? Sessions are always stored in the server side whereas cookies are always stored in the client side. 98. How Method Is Declared Within Jsp Page? Methods can be declared for use within JSP page as declaration and this method can be invoked within any other method which is declared or within JSP scriptlets or expressions. Direct access to the JSP implicit objects like request, response, session etc is forbidden within JSP methods but implicit Java server page variable is allowed to pass as parameters to the method which is declared. 99. Is It Possible By A Jsp Page To Process Html Form Data? Yes it is possible by simply obtaining the data from the FORM input via the request implicit object which lies with a scriptlet or expression but it doesn't require to implement any HTTP – Protocol methods like goGet() or doPost() within the JSP page. 100. How Cookies Is Deleted In Jsp? There are two ways by which the cookies can be deleted in JSP. Firstly, by setting the setMaxAge() of the cookie class to zero. And secondly by setting a timer in the header file that is response. setHeader(expires {Mention the time} attribute), which will delete the cookies after that prescribed time. 101. What Are Custom Tags And Why It Is Needed? JSP tags are extended by creating a custom set of tags which is called as tag library (taglib). The page which uses custom tags declares taglib and uniquely names, defines and associates a tag prefix to differentiate the usage of those tags. 102. Outline The Difference Between Java Server Page Forward And Servlet Forward Method? The only minor difference between both the methods is that Java Server page forward method can’t forward to another JSP page in another web application or container whereas servlet forward method can do so. 103. State The Difference Between The Expression And Scriptlet? JSP, Expressions is used to display the values of variable or to return the values by invoking the getter methods. However, JSP expressions begins with and does not have semicolon at the end of the expression. Scriptlet can contain variable, method or expressions that are valid within the page scripting language. Within the scripting tags and page scripting language any valid operations can be performed. 104. How A Run - Time Application Is Handled In Jsp? In JSP the errorpage attribute of the page is used as a directive to have uncaught run – time exceptions and which is automatically forwarded to an page which processes the error. If an uncaught exception is encountered while processing the request, then the browser redirects to the JSP error page. 105. What Is Declaration In Jsp? In Java Server pages Declaration is used to declare and define variables and methods that can be used in the Java Server Pages. The variable which is declared is initialized once and it retain its value for every subsequent client request. 106. How To Override The Lifecycle Methods Of Jsp? Lifecycle method jspService() cannot be overridden within a JSP page however methods like jspInit() and jspDestroy() can be overridden within a JSP page. Method jspInit() is used for allocating resource while method jspDestroy() is used to free allocated resource. But it should be kept in mind that during the lifecycle of a Java Server Page both the method jsplnit() and jspDestroy() is executed once and are declared as JSP declarations. 107. How Jsp Calls A Stored Procedure? Java Server Pages possess all the characteristics of java and to call and have similar syntax to call a function. Functions and stored procedures of a database can be called by using the statement callable. Another way to call the stored procedure is by writing the JDBC code in between the tag of scriptlet tab.write. 108. What Are The Implicit Objects In Jsp? There are all total 9 implicit objects in JSP. Application interface refers to the web application’s interface whereas Session interface refers to the user’s session. Request interface refers to the page which is currently requested whereas Response interface refers to the response which is currently made by the user. Config interface refers to the servlet configuration. Class like out, page, page Context and exception refers to the output stream of the page, servlet instance of the page, environment of the page, error handling respectively. 109. How Servlet Differ From Jsp? Both Servlet and Java Server Pages are API which generate dynamic web content. A servlet is nothing but a java class which implements the interface to run within a web and on the other hand Java server pages is a bit complicated thing which contain a mixture of Java scripts, Java directives, Java elements and HTML. The main difference among both servlet and Java server pages is that JSP is document oriented and servlet on the other hand act likes a program. 110. What Is Jsp? Describe Its Concept? JSP is a technology that combines HTML/XML markup languages and elements of Java programming Language to return dynamic content to the Web client, It is normally used to handle Presentation logic of a web application, although it may have business logic. 111. What Are The Lifecycle Phases Of A Jsp? JSP page looks like a HTML page but is a servlet. When presented with JSP page the JSP engine does the following 7 phases. Page translation: -page is parsed, and a java file which is a servlet is created. Page compilation: page is compiled into a class file Page loading : This class file is loaded. Create an instance :- Instance of servlet is created  jspInit() method is called _jspService is called to handle service calls _jspDestroy is called to destroy it when the servlet is not required. 112. What Is A Translation Unit? JSP page can include the contents of other HTML pages or other JSP files. This is done by using the include directive. When the JSP engine is presented with such a JSP page it is converted to one servlet class and this is called a translation unit, Things to remember in a translation unit is that page directives affect the whole unit, one variable declaration cannot occur in the same unit more than once, the standard action jsp:useBean cannot declare the same bean twice in one unit. 113. How Is Jsp Used In The Mvc Model JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, this data is then presented to the JSP for rendering on to the client. 114. What Are Context Initialization Parameters Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application and not specific to any servlet or JSP. 115. What's The Difference Between Forward And Sendredirect? When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container And then returns to the calling method. When a sendRedirect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward. 116. How Can You Store International / Unicode Characters Into A Cookie? One way is, before storing the cookie URLEncode it. URLEnocder.encoder(str); And use URLDecoder.decode(str) when you get the stored cookie. 117. In The Servlet 2.4 Specification Singlethreadmodel Has Been Deprecates, Why? Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level. JSP Questions and Answers Pdf Download Read the full article
0 notes