JDBC, jsp,servlet
in above image
orange color: classes hai
Blue color: interfaces hai
FirstJDBC.java
import java.sql.*;
class FirstJDBC{
public static void main(String args[]){
try {
// load the driver
Class.forName("com.mysql.cj.jdbc.Driver");
// creating connection
String url="jdbc:mysql://localhost:3306/youtube";
String username="root";
String password="root";
Connection con=DriverManager.getConnection(url,username,password);
if(con.isClosed()){
System.out.println("Connection is Closed");
}else{
System.out.println("Connection is Created....");
}
} catch (Exception e) {
System.out.println("Error is : "+e);
}
}
}
E:\java\jdbc>javac FirstJDBC.java
E:\java\jdbc>java FirstJDBC
Connection is Created....
E:\java\jdbc>
InsertJDBC.java // are yr table create krenge
import java.sql.*;
class InsertJDBC{
public static void main(String args[]){
try {
// load the driver
Class.forName("com.mysql.cj.jdbc.Driver");
// creating connection
String url="jdbc:mysql://localhost:3306/youtube";
String username="root";
String password="root";
Connection con=DriverManager.getConnection(url,username,password);
//create query
String q="create table table1(tId int(20) primary key auto_increment,tName varchar(200) not null,tCity varchar(400))";
Statement stmt=con.createStatement();
stmt.executeUpdate(q);
// stmt.executeUpdate(q); chlne ke baad hi neeche wala code chalega
System.out.println("table created in database..");
con.close();
} catch (Exception e) {
System.out.println("Error is : "+e);
}
}
}
E:\java\jdbc>javac InsertJDBC.java
E:\java\jdbc>java InsertJDBC
table created in database..InsertDataJDBC.java
import java.sql.*;
class InsertDataJDBC{
public static void main(String args[]){
try {
// load the driver
Class.forName("com.mysql.cj.jdbc.Driver");
// creating connection
String url="jdbc:mysql://localhost:3306/youtube";
String username="root";
String password="root";
Connection con=DriverManager.getConnection(url,username,password);
//create query
String q="insert into table1(tName,tCity) values(?,?)";
// get the preparedStatement object
PreparedStatement pstmt=con.prepareStatement(q);
//set the values to query
pstmt.setString(1, "Shivam");
pstmt.setString(2, "Kanpur");
pstmt.executeUpdate();
// stmt.executeUpdate(q); chlne ke baad hi neeche wala code chalega
System.out.println("values inserted....");
con.close();
} catch (Exception e) {
System.out.println("Error is : "+e);
}
}
}
E:\java\jdbc>javac InsertDataJDBC.java
E:\java\jdbc>java InsertDataJDBC
values inserted....
mysql> use youtube;
Database changed
mysql> select * from table1;
+-----+--------+--------+
| tId | tName | tCity |
+-----+--------+--------+
| 1 | Shivam | Kanpur |
+-----+--------+--------+
1 row in set (0.07 sec)
InsertDataViaInputJDBC.java
import java.sql.*;
import java.io.*;
class InsertDataViaInputJDBC{
public static void main(String args[]){
try {
// load the driver
Class.forName("com.mysql.cj.jdbc.Driver");
// creating connection
String url="jdbc:mysql://localhost:3306/youtube";
String username="root";
String password="root";
Connection con=DriverManager.getConnection(url,username,password);
//create query
String q="insert into table1(tName,tCity) values(?,?)";
// get the preparedStatement object
PreparedStatement pstmt=con.prepareStatement(q);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Name : ");
String name=br.readLine();
System.out.println("Enter City : ");
String city= br.readLine();
//set the values to query
pstmt.setString(1, name);
pstmt.setString(2, city);
pstmt.executeUpdate();
// stmt.executeUpdate(q); chlne ke baad hi neeche wala code chalega
System.out.println("values inserted....");
con.close();
} catch (Exception e) {
System.out.println("Error is : "+e);
}
}
}
E:\java\jdbc>javac InsertDataViaInputJDBC.java
E:\java\jdbc>java InsertDataViaInputJDBC
Enter Name :
Anmol Garg
Enter City :
Saharanpur
values inserted....mysql> select * from table1;
+-----+-------------+------------+
| tId | tName | tCity |
+-----+-------------+------------+
| 1 | Shivam | Kanpur |
| 2 | Ankit Kumar | Noida |
| 3 | Anmol Garg | Saharanpur |
+-----+-------------+------------+
3 rows in set (0.00 sec)
InsertImageJDBC.java
BLOB Types
| Object type | Value length that the object can hold |
|---|---|
| TINYBLOB | from 0 to 255 bytes |
| BLOB | from 0 to 65535 bytes |
| MEDIUMBLOB | from 0 to 16 777 215 bytes |
| LONGBLOB | from 0 to 4 294 967 295 bytes |
--
| Type of BLOB | Maximum amount of Data that can be stored | Overhead |
|---|---|---|
| TINYBLOB | Up to 255 bytes | 1 byte |
| BLOB | Up to 64 Kb | 2 bytes |
| MEDIUMBLOB | Up to 16 Mb | 3 bytes |
| LONGBLOB | Up to 4 Gb | 1 Bytes |
mysql> create table images(id int primary key auto_increment, pic blob);
Query OK, 0 rows affected (0.17 sec)
import java.sql.*;
import java.io.*;
class InsertImageJDBC{
public static void main(String args[]){
try {
// load the driver
Class.forName("com.mysql.cj.jdbc.Driver");
// creating connection
String url="jdbc:mysql://localhost:3306/youtube";
String username="root";
String password="root";
Connection con=DriverManager.getConnection(url,username,password);
//create query
String q="insert into images(pic) values(?)";
// get the preparedStatement object
PreparedStatement pstmt=con.prepareStatement(q);
FileInputStream fis=new FileInputStream("C:\\Users\\Lenovo\\Pictures\\Screenshots\\Screenshot (812).png");
//set the values to query
pstmt.setBinaryStream(1,fis,fis.available());
pstmt.executeUpdate();
// stmt.executeUpdate(q); chlne ke baad hi neeche wala code chalega
System.out.println("image inserted....");
con.close();
} catch (Exception e) {
System.out.println("Error is : "+e);
}
}
}
E:\java\jdbc>javac InsertImageJDBC.java
E:\java\jdbc>java InsertImageJDBC
image inserted....Work in netbeans
Run Java Program Using NetBeans 12.0ConnectionProvider.java
package com.mycompany.jdbc;
import java.sql.*;
public class ConnectionProvider{
private static Connection con;
public static Connection getConnection(){
try{
if(con==null){
// load the driver
Class.forName("com.mysql.cj.jdbc.Driver");
// creating connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/youtube","root","root");
}
}catch(Exception e){
System.out.println("Error is : "+e);
}
return con;
}
}
Main.java
package com.mycompany.jdbc;
import java.sql.*;
public class Main{
public static void main(String args[]){
try{
Connection conn=ConnectionProvider.getConnection();
System.out.println("Connection Successfull....");
}catch(Exception e){
e.printStackTrace();
}
}
}
UpdateDataJDBC.java
package com.mycompany.jdbc;
import java.sql.*;
import java.io.*;
public class UpdateDataJDBC{
public static void main(String args[]){
try{
Connection conn=ConnectionProvider.getConnection();
String q="update table1 set tName=? , tCity=? where tId=?";
PreparedStatement pstmt=conn.prepareStatement(q);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter new Name : ");
String name=br.readLine();
System.out.println("Enter new City Name : ");
String city=br.readLine();
System.out.println("Enter the student id: ");
int id=Integer.parseInt(br.readLine());
pstmt.setString(1,name);
pstmt.setString(2,city);
pstmt.setInt(3,id);
pstmt.executeUpdate();
System.out.println("updation done....");
}catch(Exception e){
e.printStackTrace();
}
}
}
SelectJDBC.java
package com.mycompany.jdbc;
import java.sql.*;
import java.io.*;
public class SelectJDBC{
public static void main(String args[]){
try{
Connection conn=ConnectionProvider.getConnection();
String q="select * from table1";
Statement stmt=conn.createStatement();
ResultSet sett=stmt.executeQuery(q);
while(sett.next()){
int id=sett.getInt(1);
String name=sett.getString(2);
String city=sett.getString(3);
System.out.println(id+" : "+name+" : "+city);
}
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
jsp & Servlet
Update all plugin version you are using... See maven.apache.org/plugins
Working in eclipse ide:
nodejs res.send() equivalent:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().println("<h1>Hello World!</h1>");
// response.getWriter().append("Served at: ").append(request.getContextPath());
}
or
PrintWriter out=response.getWriter();
out.println("jo bhi print krans chaho");
request.getParameter("variable");
url :http://localhost:8080/servlet2/tmpServlet?value1=Ankit&value2=kumar
PrintWriter out=response.getWriter();
out.println("value 1"+request.getParameter("value1"));
out.println("value 2"+request.getParameter("value2"));
servlet life cycle:
5 jsp scripting element:
- <body>
- <% out.print("welcome to jsp"); %>
- </body>
Example of JSP scriptlet tag that prints the user name:
File: index.html
File: welcome.jsp
JSP expression tag:
syntax:
- <%= statement %>
Examples:
- <body>
- <%= "welcome to jsp" %>
- </body>
Example of JSP expression tag that prints current time:
- Current Time: <%= java.util.Calendar.getInstance().getTime() %>
- or
- <%= new java.util.Date() %>
Example of JSP expression tag that prints the user name:
File: index.jsp
File: welcome.jsp
JSP Declaration Tag:
syntax:
- <%! field or method declaration %>
Difference between JSP Scriptlet tag and Declaration tag:
| Jsp Scriptlet Tag | Jsp Declaration Tag |
|---|---|
| The jsp scriptlet tag can only declare variables not methods. | The jsp declaration tag can declare variables as well as methods. |
| The declaration of scriptlet tag is placed inside the _jspService() method. | The declaration of jsp declaration tag is placed outside the _jspService() method. |
Example of JSP declaration tag that declares field:
- <%! int data=50; %>
- <%= "Value of the variable is:"+data %>
Example of JSP declaration tag that declares method:
- <%!
- int cube(int n){
- return n*n*n*;
- }
- %>
- <%= "Cube of 3 is:"+cube(3) %>
dusri file jsp me load krna taki web page me display ho jaye:
<body>
<!-- for adding static content -->
<%@ include file="file1.txt" %>
<br>
<!-- for adding dynamic content -->
<jsp:include page="file2.txt"/>
</body>
another class ke method ko call krna:
UserDefined.java
package tmppackage;
public class UserDefined {
public String getText(String name) {
return "Person Name is : "+name;
}
}
tmpJsp.jsp
<%@ page import="tmppackage.UserDefined" %>
<% out.print(newUserDefined().getText("Ankit Kumar")); %>
output on browser:
Person Name is : Ankit Kumar
Built in class import in jsp file:
<%@ page import="java.util.Date" %>
<%= new Date() %>
output on browser:
Mon Oct 11 18:11:34 IST 2021
ek hi tag me multiple class import kr ske hain:
<%@ page import="tmppackage.UserDefined,java.util.Date" %>
Assignment: (Login ko click krne pr login page khule and so on): Based on MVC concept
Home Page
solution:
index.jsp
<body>
<h1>Home Page</h1>
<ul>
<li> <a href="<%=request.getContextPath() %>/Controller?page=login">Login</a></li>
<li> <a href="<%=request.getContextPath() %>/Controller?page=signUp">Sign Up</a> </li>
<li> <a href="<%=request.getContextPath() %>/Controller?page=about">About</a> </li>
</ul>
</body>
Controller.java (servlet file)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param=request.getParameter("page");
if(param.equals("login")) {
getServletContext().getRequestDispatcher("/login.jsp").forward(request,response);
}else if(param.equals("signUp")) {
getServletContext().getRequestDispatcher("/signUp.jsp").forward(request,response);
}else if(param.equals("about")) {
getServletContext().getRequestDispatcher("/about.jsp").forward(request,response);
}else {
getServletContext().getRequestDispatcher("/notFound.jsp").forward(request,response);
}
}
login.jsp
<body>
login page
</body>
Form ko sumit krne pr uski values dusri file ki help se display krana:
Without Using Controller:
form.jsp
<form action="submit.jsp">
<div>
<label>Full Name</label>
<input type="text" name="full_name" required>
</div>
<div>
<label>Gender</label>
<input type="radio" name="gender" value="male" checked>Male
<input type="radio" name="gender" value="female">Female
</div>
<div>
<label>Language know</label>
<input type="checkbox" name="language" value="English">English
<input type="checkbox" name="language" value="Hindi">Hindi
<input type="checkbox" name="language" value="French">French
</div>
<div>
<label>Country</label>
<select name="country">
<option value="India">India</option>
<option value="USA">USA</option>
<option value="UK">UK</option>
<option value="Japan">Japan</option>
<option value="Nepal">Nepal</option>
</select>
</div>
<div>
<input type="submit" value="submit">
</div>
</form>
submit.jsp
<body>
Name : <%= request.getParameter("full_name") %> <br>
Gender : <%= request.getParameter("gender") %><br>
Language Know : <%
String[] languages=request.getParameterValues("language");
if(languages!=null){
for(int i=0;i<languages.length;i++){
out.print(languages[i]+"<br>");
}
}else{
out.print("Not Selected");
}
%>
Country : <%= request.getParameter("country") %> <br>
</body>
Using Controller:
form.jsp
<form action="<%= request.getContextPath() %>/Controller" method="post">...baki same as above
Controller.java (servlet)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("full_name");
String gender=request.getParameter("gender");
String[] languages=request.getParameterValues("language");
String country=request.getParameter("country");
PrintWriter out=response.getWriter();
out.println(name+"<br>"+gender+"<br>");
if(languages!=null) {
for(int i=0;i<languages.length;i++) {
out.println(languages[i]+"<br>");
}
}else {
out.println("Not Selected");
}
out.println(country);
doGet(request, response);
}
javaBeans awareness
JavaBeans are classes that encapsulate many objects into a single object (the bean).
-----------
references:
https://www.javatpoint.com
----
Comments
Post a Comment