Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
87 views

Java Program

The document describes a Java web application that allows users to register and login. It includes: 1) Creating a database table to store user information. 2) JSP pages for the registration form, login form, and registration/login processing. 3) A servlet to handle the login processing. 4) Use of JavaBeans to store and access user data across JSP pages. The application allows users to register by submitting a form, stores the data in a database, and redirects to a login page. Users can then login and are redirected to a success page, or shown an error if credentials are invalid. JavaBeans are used to share data entered in forms between JSP pages

Uploaded by

Joshan Pradhan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
87 views

Java Program

The document describes a Java web application that allows users to register and login. It includes: 1) Creating a database table to store user information. 2) JSP pages for the registration form, login form, and registration/login processing. 3) A servlet to handle the login processing. 4) Use of JavaBeans to store and access user data across JSP pages. The application allows users to register by submitting a form, stores the data in a database, and redirects to a login page. Users can then login and are redirected to a success page, or shown an error if credentials are invalid. JavaBeans are used to share data entered in forms between JSP pages

Uploaded by

Joshan Pradhan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

CASE STUDY

Creating Table

CREATE TABLE `members` (


`id` int(10) unsigned NOT NULL auto_increment,
`first_name` varchar(45) NOT NULL,
`last_name` varchar(45) NOT NULL,
`email` varchar(45) NOT NULL,
`uname` varchar(45) NOT NULL,
`pass` varchar(45) NOT NULL,
`regdate` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>JSP Example</title>
</head>
<body>
<form method="post" action="login.jsp">
<h2>Login Here</h2>

<label for="Username">Username</label><br>
<input type="text" name="uname"/><br>

<label for="Password">Password</label><br>
<input type="password" name="password"/><br>

<input type="submit" value="Login"/>


<input type="reset" value="Reset"/>

<strong> Yet Not Registered!!</strong>


<a href="reg.jsp">Register Here</a>
</form>
</body>
</html>

reg.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Registration</title>
</head>
<body>
<form method="post" action="registration.jsp">
<h2>Enter Information Here</h2>
<label for="firstName">First Name</label><br>
<input type="text" name="fname" /></br>

<label for="lastName">Last Name</label><br>


<input type="text" name="lname" /></br>

<label for="email">Email</label><br>
<input type="text" name="email" /></br>

<label for="username">Username</label><br>
<input type="text" name="uname" /></br>

<label for="password">Password</label><br>
<input type="password" name="pass" /></br>

<input type="submit" value="Submit" /></td>


<input type="reset" value="Reset" /></td>

<strong>Already registered!!</strong>
<a href="index.jsp">Login Here</a>
</form>
</body>
</html>

registration.jsp
<%@ page import ="java.sql.*" %>
<%
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String email = request.getParameter("email");
String uname = request.getParameter("uname");
String password = request.getParameter("password");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname",
"root", "dbpass");
String sql=”INSERT INTO users(fname , lname , email, uname, password) values
(?,?,?,?,?)”;
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1,fname );
stmt.setString(2, lname );
stmt.setString(3, email );
stmt.setString(4, uname );

stmt.setString(5,password );
int rowsInserted = stmt.executeUpdate();

if (rowsInserted > 0) {
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("index.jsp");
}
%>

welcome.jsp
Registration is Successful.
Please Login Here <a href='index.jsp'>Go to Login</a>

login.jsp
<%@ page import ="java.sql.*" %>
<%
String uname = request.getParameter("uname");
String pwd = request.getParameter("pass");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname",
"root", "dbpass");
String sql = "SELECT * FROM Users where uname=”+uname+" and
password=”+password+”;
Statement stmt = conn.createStatement();
ResultSet rs= stmt.executeQuery(sql);

if (rs.next()) {
session.setAttribute("uname", uname);
response.sendRedirect("success.jsp");
} else {
out.println("Invalid password <a href='index.jsp'>try again</a>");
}
%>

success.jsp
<%
if ((session.getAttribute("userid") == null) || (session.getAttribute("userid") == "")) {
%>
You are not logged in<br/>
<a href="index.jsp">Please Login</a>
<%} else {
%>
Welcome <%=session.getAttribute("userid")%>
<a href='logout.jsp'>Log out</a>
<%
}
%>

logout.jsp
<%
session.setAttribute("userid", null);
session.invalidate();
response.sendRedirect("index.jsp");
%>

DATABASE (Using Prepared Statement)

//STEP 1. Import required packages


import java.sql.*;

public class JDBCExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials
static final String USER = "root";
static final String PASS = " ";

public void dbConnection() {


try {
//STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);

//STEP 3: Open a connection


System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);

if (conn != null) {
System.out.println("Connected");
}
} catch (SQLException e) {
e.printStackTrace();
}

}
public void insert() {
try {
String sql = "INSERT INTO Users (username, password, fullname, email) VALUES
(?, ?, ?, ?)";

PreparedStatement stmt = conn.prepareStatement(sql);


stmt.setString(1, "bill");
stmt.setString(2, "secretpass");
stmt.setString(3, "Bill Gates");
stmt.setString(4, "bill.gates@microsoft.com");

int rowsInserted = stmt.executeUpdate();


if (rowsInserted > 0) {
System.out.println("A new user was inserted successfully!");
}
} catch (Exception e) {
e.printStackTrace();
}
}

public void select() {


try {
String sql = "SELECT * FROM Users";

Statement stmt = conn.createStatement();


ResultSet rs= stmt.executeQuery(sql);

while (result.next()) {
String uname = rs.getString(2);
String password = rs.getString(3);
String fname = rs.getString(4);
String email = rs.getString(5);
System.out.println(uname+” ”+password+” ”+fname+” ”+email);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void update() {
try {
String sql = "UPDATE Users SET password=?, fullname=?, email=? WHERE
username=?";

PreparedStatement stmt = conn.prepareStatement(sql);


stmt.setString(1, "123456789");
stmt.setString(2, "William Henry Bill Gates");
stmt.setString(3, "bill.gates@microsoft.com");
stmt.setString(4, "bill");

int rowsUpdated = stmt.executeUpdate();


if (rowsUpdated > 0) {
System.out.println("An existing user was updated successfully!");
}
} catch (Exception e) {
e.printStackTrace();
}
}

public void delete() {


try {
String sql = "DELETE FROM Users WHERE username=?";

PreparedStatement stmt = conn.prepareStatement(sql);


stmt.setString(1, "bill");

int rowsDeleted = stmt.executeUpdate();


if (rowsDeleted > 0) {
System.out.println("A user was deleted successfully!");
}
} catch (Exception e) {
e.printStackTrace();
}
}

public void close() {


try {
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {

JDBCExample jdbc = new JDBCExample();


jdbc.dbConnection();
jdbc.insert();
jdbc.select();
jdbc.update();
jdbc.delete();
jdbc.close();
}
}

Java Beans

CustomerForm.jsp
<html>
<head>
<title> Customer Form </title>
</head>
<body>
<h3>Please fill in the following details and submit it </h3> <br />
<form action="CustomerInfoGatherer.jsp" method="GET">
First Name: <input type="text" name="firstName"> <br>
Last Name: <input type="text" name="lastName"> <br>
Age: <input type="text" name="age"> <br>
<input type="submit" name="Submit" />
</form>
</body>
</html>

Customer.java

package beans;
public class Customer implements java.io.Serializable {
private String firstName = null;
private String lastName = null;
private int age = 0;

public Customer() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;
}
}

CustomerInfoGatherer.jsp

<html>
<body>
<H2>Reading the form data</H2>
<H3>Populating the bean and Storing in session </H3>
<jsp:useBean id="userInfo" class="beans.Customer" scope="session" />

<jsp:setProperty name="userInfo" property="firstName"


value="<%=request.getParameter(" firstName")%>" />
<jsp:setProperty name="userInfo" property="lastName"
value="<%=request.getParameter(" lastName")%>" />
<jsp:setProperty name="userInfo" property="age"
value="<%=request.getParameter(" age")%>" />

<H3>Finished storing in the session </H3>


<a href="InfoProcessor.jsp">Click Here </a> to invoke the servlet that process the bean
data in session.
</body>
</html>

InfoProcessor.jsp

<html>
<body>
<jsp:useBean id="userInfo" class="beans.Customer"scope="session" />
<jsp:getProperty name="userInfo" property="firstName"/>
<jsp:getProperty name="userInfo" property="lastName"/>
<jsp:getProperty name="userInfo" property="age"/>
</body>
</html>

Servlet

<html>
<body>
<form action="servlet1" method="post">
Name:<input type="text" name="userName" /><br />
Password:<input type="password" name="userPass" /><br />
<input type="submit" value="login" />
</form>
</body>
</html>

Login.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Login extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String uname=request.getParameter("userName");
String password=request.getParameter("userPass");

if(password.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}

WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class WelcomeServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);
}

}
web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

APPLET
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java

/*
Basic Java Applet Example
This Java example shows how to create a basic applet using Java Applet class.
*/

import java.applet.Applet;
import java.awt.Graphics;

/*
<applet code = "BasicAppletExample.class" width = 200 height = 200>
</applet>
*/
public class BasicAppletExample extends Applet{
public void paint(Graphics g){
//write text using drawString method of Graphics class
g.drawString("This is my First Applet",20,100);
}
}

APPLET ARITHMETIC OPERATION

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Calc extends Applet implements ActionListener {

Panel p1, p2;

Label l1, l2, l3;

TextField t1, t2, t3;

Button b1, b2, b3, b4;


public void init() {

p1 = new Panel(new GridLayout(3, 2));

p2 = new Panel(new FlowLayout());

l1 = new Label("Num 1");

l2 = new Label("Num 2");

l3 = new Label("Result");

t1 = new TextField(10);

t2 = new TextField(10);

t3 = new TextField(10);

t3.setEditable(false);

p1.add(l1);

p1.add(t1);

p1.add(l2);

p1.add(t2);

p1.add(l3);

p1.add(t3);

b1 = new Button("add");

b2 = new Button("mul");

b3 = new Button("sub");

b4 = new Button("div");

p2.add(b1);

p2.add(b2);

p2.add(b3);
p2.add(b4);

setLayout(new GridLayout(2, 1));

add(p1);

add(p2);

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

b4.addActionListener(this);

public void actionPerformed(ActionEvent ae) {

int a = Integer.parseInt(t1.getText());

int b = Integer.parseInt(t2.getText());

int c;

if (ae.getActionCommand() == "add") {

c = a + b;

t3.setText("" + c);

if (ae.getActionCommand() == "mul") {

c = a * b;

t3.setText("" + c);

if (ae.getActionCommand() == "sub") {

c = a - b;
t3.setText("" + c);

if (ae.getActionCommand() == "div") {

double x = Double.parseDouble(t1.getText());

double y = Double.parseDouble(t2.getText());

double z = x / y;

t3.setText("" + z);

SWING RADIO BUTTON

import java.awt.FlowLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JRadioButton;

public class RadioButtonDemo implements ActionListener {

private JLabel l1;

public RadioButtonDemo() {

JFrame f= new JFrame(“JRadioButton Demo”);

frame.setLayout(new FlowLayout());
frame.setSize(200, 200);

JRadioButton jr1 = new JRadioButton("Male");

JRadioButton jr2 = new JRadioButton("Female");

l1 = new JLabel();

ButtonGroup bg = new ButtonGroup();

bg.add(jr1);

bg.add(jr2);

jr1.addActionListener(this);

jr2.addActionListener(this);

f.add(jr1);

f.add(jr2);

f.add(l1);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

public void actionPerformed(ActionEvent ae) {

l1.setText("You selected " + ae.getActionCommand());

public static void main(String[] args) {

new RadioButtonDemo();

}
FACTORIAL
import java.awt.*;
import java.awt.event.*;
/**
*
* @author Apex Lab
*/
public class FactorialDemo {
int n=1,fact=1,i;
public FactorialDemo(){
Frame f=new Frame("CountDownDemo");
Label l1=new Label("n");
Label l2=new Label("Factorial(n)");

TextField t1=new TextField("1");


TextField t2=new TextField("1");
Button b1=new Button("Next");

b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
n++;
//int a=Integer.parseInt(t1.getText());

for(i=1;i<=n;i++){

fact=fact*i;
}

// fact=fact*n;

t1.setText(String.valueOf(n));
t2.setText(String.valueOf(fact));
fact=1;
}
});

f.add(l1);
f.add(t1);
f.add(l2);
f.add(t2);
f.add(b1);
f.setLayout(new FlowLayout());
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args){
new FactorialDemo();
}

HttpSession
index.html

1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. HttpSession session=request.getSession();
18. session.setAttribute("uname",n);
19.
20. out.print("<a href='servlet2'>visit</a>");
21.
22. out.close();
23.
24. }catch(Exception e){System.out.println(e);}
25. }
26.
27. }

import java.awt.*;
import java.awt.event.*;

public class AccumulatorDemo {


int accumulatedsum=0;
public AccumulatorDemo(){

Frame f=new Frame(&quot;AccumulatorDemo&quot;);

Label l1=new Label(&quot;Enter an integer &quot;);


Label l2=new Label(&quot;Accumulated sum is &quot;);

TextField t1=new TextField();


TextField t2=new TextField();

t1.addTextListener(new TextListener(){
public void textValueChanged(TextEvent e){
int a=Integer.parseInt(t1.getText());
accumulatedsum = a + accumulatedsum;
t2.setText(String.valueOf(accumulatedsum));

}
});
f.setLayout(new GridLayout(2,2));
f.add(l1);
f.add(t1);
f.add(l2);
f.add(t2);
f.setSize(200,200);
f.setVisible(true);

}
public static void main(String[] args){
new AccumulatorDemo();
}
}
import java.awt.*;
import java.awt.event.*;
/**
*
* @author Apex Lab
*/
public class CountDownDemo {
int counter=88;
public CountDownDemo(){
Frame f=new Frame("CountDownDemo");
Label l1=new Label("Counter");
TextField t1=new TextField("88");
Button b1=new Button("Count Down");
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){

counter--;
t1.setText(String.valueOf(counter));
}
});

f.add(l1);
f.add(t1);
f.add(b1);
f.setLayout(new FlowLayout());
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args){
new CountDownDemo();

Simple JAva program

1. import javax.swing.*;
2. import java.awt.event.*;
3. public class TextFieldExample implements ActionListener{
4. JTextField tf1,tf2,tf3;
5. JButton b1,b2;
6. TextFieldExample(){
7. JFrame f= new JFrame();
8. tf1=new JTextField();
9. tf1.setBounds(50,50,150,20);
10. tf2=new JTextField();
11. tf2.setBounds(50,100,150,20);
12. tf3=new JTextField();
13. tf3.setBounds(50,150,150,20);
14. tf3.setEditable(false);
15. b1=new JButton("+");
16. b1.setBounds(50,200,50,50);
17. b2=new JButton("-");
18. b2.setBounds(120,200,50,50);
19. b1.addActionListener(this);
20. b2.addActionListener(this);
21. f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
22. f.setSize(300,300);
23. f.setLayout(null);
24. f.setVisible(true);
25. }
26. public void actionPerformed(ActionEvent e) {
27. String s1=tf1.getText();
28. String s2=tf2.getText();
29. int a=Integer.parseInt(s1);
30. int b=Integer.parseInt(s2);
31. int c=0;
32. if(e.getSource()==b1){
33. c=a+b;
34. }else if(e.getSource()==b2){
35. c=a-b;
36. }
37. String result=String.valueOf(c);
38. tf3.setText(result);
39. }
40. public static void main(String[] args) {
41. new TextFieldExample();
42. } }

You might also like