Sie sind auf Seite 1von 24

Three Layer Architecture

Online Examination

Seat Number:
Name:

1. Every host implements transport layer.

True False
2. It is a network layer's responsibility to forward packets reliably from source to
destination

True False
3. Packet switching is more useful in bursty traffic

True False
4. A phone network uses packet switching

True False
5. HTML is a Protocol for describing web contents

True False

Submit

Index.html

<html><head><title>Database Test</title></head> <body>

<center><h1>Online Examination</h1> </center>

<form action=" StudentServlet" method="POST"> <div align="left"><br></div>


<b>Seat Number:</b> <input type="text" name="Seat_no"> <div align="Right">

<b>Name:</b> <input type="text" name="Name" size="50"><br> </div>

<br><br>

<b>1. Every host implements transport layer.</b><br/> <input type="radio" name="group1"


value="True">True <input type="radio" name="group1" value="False">False<br>

<b>2. It is a network layer's responsibility to forward packets reliably from source to


destination</b><br/>

<input type="radio" name="group2" value="True">True

<input type="radio" name="group2" value="False">False<br>

<b>3. Packet switching is more useful in bursty traffic</b><br/> <input type="radio" name="group3"
value="True">True<input type="radio" name="group3" value="False">False<br> <b>4. A phone network
uses packet switching</b><br/> <input type="radio" name="group4" value="True">True <input
type="radio" name="group4" value="False">False<br>

<b>5. HTML is a Protocol for describing web contents</b><br/> <input type="radio" name="group5"
value="True">True

<input type="radio" name="group5" value="False">False<br> <br><br><br>

<center>
<input type="submit" value="Submit"><br><br> </center>

</form></body></html>

StudentServlet.Java

/*

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

import java.io.*;

import java.sql.*;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.servlet.*;

import javax.servlet.http.*;

/**

* @author srika

*/

public class StudentServlet3 extends HttpServlet {


/**

* Processes requests for both HTTP <code>GET</code> and <code>POST</code>

* methods.

* @param request servlet request

* @param response servlet response

* @throws ServletException if a servlet-specific error occurs

* @throws IOException if an I/O error occurs

*/

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

Connection con;

Statement stmt;

String message,Seat_no,Name,ans1,ans2,ans3,ans4,ans5; int Total=0;

try (PrintWriter out = response.getWriter()) {

/* TODO output your page here. You may use following sample code. */

out.println("<!DOCTYPE html>");

out.println("<html>");

out.println("<head>");

out.println("<title>Servlet</title>");

out.println("</head>");

out.println("<body>");

Seat_no=request.getParameter("Seat_no");

Name=request.getParameter("Name");
ans1=request.getParameter("group1");

ans2=request.getParameter("group2");

ans3=request.getParameter("group3");

ans4=request.getParameter("group4");

ans5=request.getParameter("group5");

if(ans1.equals("True"))

Total+=2;

if(ans2.equals("False"))

Total+=2;

if(ans3.equals("True"))

Total+=2;

if(ans4.equals("False"))

Total+=2;

if(ans5.equals("False"))

Total+=2;

out.println("<table border=5>");

try

con=DriverManager.getConnection("jdbc:derby://localhost:1527/sample","app","app");

stmt=con.createStatement();

PreparedStatement pstmt=con.prepareStatement("insert into student values(?,?,?)");


pstmt.setInt(1,Integer.valueOf(Seat_no));

pstmt.setString(2,Name);

pstmt.setInt(3,Total);

int ans=pstmt.executeUpdate();

if(ans==1)

out.println("Record Inserted success</br>");

else

out.println("Not success");

}catch(SQLException ex){

out.println("Execution Error");

try

con=DriverManager.getConnection("jdbc:derby://localhost:1527/sample","app","app");

out.println("<b>"+"Participants and their Marks"+"</b>");

stmt=con.createStatement(); String query="SELECT * FROM student";

ResultSet rs=stmt.executeQuery(query); out.println("<th>"+"Seat_no"+"</th>");


out.println("<th>"+"Name"+"</th>"); out.println("<th>"+"Marks"+"</th>"); while(rs.next())
{

out.println("<tr>");

out.print("<td>"+rs.getInt(1)+"</td>");

out.print("<td>"+rs.getString(2)+"</td>");

out.print("<td>"+rs.getString(3)+"</td>");

out.println("</tr>");

out.println("</table>");

catch(SQLException ex){ }

out.println("</body>");

out.println("</html>");

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to


edit the code.">

/**

* Handles the HTTP <code>GET</code> method.

*
* @param request servlet request

* @param response servlet response

* @throws ServletException if a servlet-specific error occurs

* @throws IOException if an I/O error occurs

*/

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

/**

* Handles the HTTP <code>POST</code> method.

* @param request servlet request

* @param response servlet response

* @throws ServletException if a servlet-specific error occurs

* @throws IOException if an I/O error occurs

*/

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

}
/**

* Returns a short description of the servlet.

* @return a String containing servlet description

*/

@Override

public String getServletInfo() {

return "Short description";

}// </editor-fold>

Database:
Dynamic Content

Index.html

Enter username:
Enter Password:
Enter Card ID:

login

<html>

<head>

<body>

<form action="http://localhost:8080/dynamic2_7/LoginServlet" method="post">

Enter username:

<input type="text" value="" name="user">

<br>

Enter Password:

<input type="password" value="" name="password">

<br>

Enter Card ID:

<input type="text" value="" name="cardID">

<br>

<br> <br> <br>

<input type="submit" value="login">

</form>

</body>

LoginServlet.java
import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class LoginServlet extends HttpServlet

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException

response.setContentType("text/html;charset=UTF-8");

try

PrintWriter out = response.getWriter();

String usr=request.getParameter("user");

String pwd=request.getParameter("password");

String card=request.getParameter("cardID");

boolean flag=true;

// response.sendRedirect("http://localhost:8080/dynamic2_7/LoginSuccess");

String[] userID=getInitParameter("usernames").split(",");

String[] password=getInitParameter("passwords").split(",");

String[] cardids=getInitParameter("cardIDs").split(",");

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

if(userID[i].equals(usr)&&password[i].equals(pwd)&&cardids[i].equals(card))

flag=false;

Cookie MyCookie=new Cookie("CurrentUser", usr);

MyCookie.setMaxAge(60*60);

response.addCookie(MyCookie);

response.sendRedirect("http://localhost:8080/dynamic2_7/LoginSuccess");

if(flag==true)

out.print("Error");

out.println("<h4>Invalid user,please try again by clicking following link</h4>");

out.println("<a href='http://localhost:8080/dynamic2_7/'>"+"LoginForm.html");

catch(Exception e)

{}

LoginSuccess.java
import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class LoginSuccess extends HttpServlet {@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

Cookie[] my_cookies=request.getCookies();

response.setContentType("text/html");

try (PrintWriter out = response.getWriter()) {

out.print("Login Success");

out.println("<b>");

String userName=null;

if(my_cookies!=null)

for(Cookie cookie:my_cookies)

if(cookie.getName().equals("currentUser"))

userName=cookie.getValue();

out.print("<h3>Login Success!!!Welcome</h3>");

out.print("<h2>This is a Shopping cart for"+userName+"</h2>");

}
}

Web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd">

<servlet>

<servlet-name>LoginServlet</servlet-name>

<servlet-class>LoginServlet</servlet-class>

<init-param>

<param-name>usernames</param-name>

<param-value>user1,user2,user3</param-value>

</init-param>

<init-param>

<param-name>passwords</param-name>

<param-value>pwd1,pwd2,pwd3</param-value>

</init-param>

<init-param>

<param-name>cardIDs</param-name>

<param-value>111,222,333</param-value>

</init-param>

</servlet>

<servlet>

<servlet-name>LoginSuccess</servlet-name>

<servlet-class>LoginSuccess</servlet-class>
</servlet>

<servlet-mapping>

<servlet-name>LoginServlet</servlet-name>

<url-pattern>/LoginServlet</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>LoginSuccess</servlet-name>

<url-pattern>/LoginSuccess</url-pattern>

</servlet-mapping>

<session-config>

<session-timeout>

30

</session-timeout>

</session-config>

</web-app>
Form Validation – PHP

<!DOCTYPE html>

<html>

<head>

<style>

.error {color: #FF0001;}

</style>

</head>

<body>

<?php

// define variables to empty values

$nameErr = $emailErr = $mobilenoErr = $genderErr = $websiteErr = $agreeErr = "";

$name = $email = $mobileno = $gender = $website = $agree = "";

//Input fields validation

if ($_SERVER["REQUEST_METHOD"] == "POST") {

//String Validation

if (empty($_POST["name"])) {

$nameErr = "Name is required";

} else {

$name = input_data($_POST["name"]);

// check if name only contains letters and whitespace

if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only alphabets and white space are allowed";

//Email Validation

if (empty($_POST["email"])) {

$emailErr = "Email is required";

} else {

$email = input_data($_POST["email"]);

// check that the e-mail address is well-formed

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

$emailErr = "Invalid email format";

//Number Validation

if (empty($_POST["mobileno"])) {

$mobilenoErr = "Mobile no is required";

} else {

$mobileno = input_data($_POST["mobileno"]);

// check if mobile no is well-formed

if (!preg_match ("/^[0-9]*$/", $mobileno) ) {

$mobilenoErr = "Only numeric value is allowed.";

//check mobile no length should not be less and greator than 10


if (strlen ($mobileno) != 10) {

$mobilenoErr = "Mobile no must contain 10 digits.";

//URL Validation

if (empty($_POST["website"])) {

$website = "";

} else {

$website = input_data($_POST["website"]);

// check if URL address syntax is valid

if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/
%=~_|]/i",$website)) {

$websiteErr = "Invalid URL";

//Empty Field Validation

if (empty ($_POST["gender"])) {

$genderErr = "Gender is required";

} else {

$gender = input_data($_POST["gender"]);

//Checkbox Validation

if (!isset($_POST['agree'])){
$agreeErr = "Accept terms of services before submit.";

} else {

$agree = input_data($_POST["agree"]);

function input_data($data) {

$data = trim($data);

$data = stripslashes($data);

$data = htmlspecialchars($data);

return $data;

?>

<h2>Registration Form</h2>

<span class = "error">* required field </span>

<br><br>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" >

Name:

<input type="text" name="name">

<span class="error">* <?php echo $nameErr; ?> </span>

<br><br>

E-mail:

<input type="text" name="email">

<span class="error">* <?php echo $emailErr; ?> </span>

<br><br>
Mobile No:

<input type="text" name="mobileno">

<span class="error">* <?php echo $mobilenoErr; ?> </span>

<br><br>

Website:

<input type="text" name="website">

<span class="error"><?php echo $websiteErr; ?> </span>

<br><br>

Gender:

<input type="radio" name="gender" value="male"> Male

<input type="radio" name="gender" value="female"> Female

<input type="radio" name="gender" value="other"> Other

<span class="error">* <?php echo $genderErr; ?> </span>

<br><br>

Agree to Terms of Service:

<input type="checkbox" name="agree">

<span class="error">* <?php echo $agreeErr; ?> </span>

<br><br>

<input type="submit" name="submit" value="Submit">

<br><br>

</form>

<?php

if(isset($_POST['submit'])) {

if($nameErr == "" && $emailErr == "" && $mobilenoErr == "" && $genderErr == "" && $websiteErr ==
"" && $agreeErr == "") {
echo "<h3 color = #FF0001> <b>You have sucessfully registered.</b> </h3>";

echo "<h2>Your Input:</h2>";

echo "Name: " .$name;

echo "<br>";

echo "Email: " .$email;

echo "<br>";

echo "Mobile No: " .$mobileno;

echo "<br>";

echo "Website: " .$website;

echo "<br>";

echo "Gender: " .$gender;

} else {

echo "<h3> <b>You didn't filled up the form correctly.</b> </h3>";

?>

</body>

</html>
Form- Database – PHP

connect.php

<?php

$connection=mysqli_connect("localhost","root","","student");

if(mysqli_connect_errno())

echo "Connection Faiil..." . mysqli_connect_error();

?>

index.php

<html>

<head>

<title>REGISTRATION FORM</title>

<body>

<h3>REGISTRATION FORM</h3>

<form name="registration" method="post" action="registration.php">

<!-- we will create registration.php after registration.html -->

USERNAME:<input type="text" name="name" value=""></br></br>

EMAIL-ID:<input type="text" name="email" value=""></br></br>

PASSWORD:<input type="text" name="password" value=""></br></br>

RE-PASSWORD:<input type="text" name="repassword" value=""></br></br>

<input type="submit" name="submit" value="submit">

</form>
</body>

</head>

</html>

registration.php

<?php //start php tag

//include connect.php page for database connection

Include('connect.php');

//if submit is not blanked i.e. it is clicked.

if(isset($_REQUEST['submit'])!='')

If($_REQUEST['name']=='' || $_REQUEST['email']=='' || $_REQUEST['password']==''||


$_REQUEST['repassword']=='')

Echo "please fill the empty field.";

Else

//$sql="insert into student(name,email,password,repassword) values('".$_REQUEST['name']."', '".


$_REQUEST['email']."', '".$_REQUEST['password']."', '".$_REQUEST['repassword']."')";

//$res=mysqli_query($sql);

$res = mysqli_query($connection,"insert into student(name,email,password) values('".


$_REQUEST['name']."', '".$_REQUEST['email']."', '".$_REQUEST['password']."')")

or die (mysqli_error($connection));

If($res)

Echo "Record successfully inserted";


}

Else

Echo "There is some problem in inserting record";

?>

Das könnte Ihnen auch gefallen