0% found this document useful (0 votes)
18 views11 pages

Lab04 Webs PDF

xavdfvcadqwefgdf

Uploaded by

aa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views11 pages

Lab04 Webs PDF

xavdfvcadqwefgdf

Uploaded by

aa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Alumno(s): Rugel Barrera Jhon Pietro Nota

Grupo: B Ciclo: VI

Requiere
Excelente Bueno No acept. Puntaje
Criterio de Evaluación mejora
(4pts) (3pts) (0pts) Logrado
(2pts)

Comprende conceptualmente lo que hace el


objeto HttpSession.

Crea una conexión a BD.

Logra crear un formulario que ingrese datos a la


BD.

Ejecuta un JSP que ingrese datos a la BD.

Es puntual y redacta el informe adecuadamente


Nro. xxx

DISEÑO Y DESARROLLO DE SOFTWARE Página 2/11


CURSO: Desarrollo de Aplicaciones Web Laboratorio Nro. 01

TEMA: JSP + SERVLETS


OBJETIVOS
● Creación de un Servlet y un JSP con conexión a BD.

REQUERIMIENTOS
● Tener el Netbeans, Java SDK y el Apache Tomcat instalados.
● Diapositivas de la semana.

PROCEDIMIENTO
(** El laboratorio se ha diseñado para ser desarrollado en grupos de 2 o 3 personas**)

1. Pruebe el siguiente Servlet y explique qué es lo que hace.

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/SessionServlet")
public class SessionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// Get the session associated with this request, or create one if it doesn't exist
HttpSession session = request.getSession(true);

// Get the username from the request parameter (assuming it's provided)
String username = request.getParameter("username");

// Get the list of users from the session, or create a new list if it doesn't exist
List<String> userList = (List<String>) session.getAttribute("userList");
if (userList == null) {
userList = new ArrayList<>();
}

// Add the username to the list of users


Nro. xxx

DISEÑO Y DESARROLLO DE SOFTWARE Página 3/11


CURSO: Desarrollo de Aplicaciones Web Laboratorio Nro. 01

if (username != null && !username.isEmpty()) {


userList.add(username);
// Update the session attribute with the new list of users
session.setAttribute("userList", userList);
}

// Set the response content type


response.setContentType("text/html");

// Get the PrintWriter object to write the HTML response


PrintWriter out = response.getWriter();

// Write the HTML response


out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>User List</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>User List</h1>");
out.println("<p>List of Users:</p>");
out.println("<ul>");
for (String user : userList) {
out.println("<li>" + user + "</li>");
}
out.println("</ul>");
out.println("</body>");
out.println("</html>");
}
}
Nro. xxx

DISEÑO Y DESARROLLO DE SOFTWARE Página 4/11


CURSO: Desarrollo de Aplicaciones Web Laboratorio Nro. 01
Nro. xxx

DISEÑO Y DESARROLLO DE SOFTWARE Página 5/11


CURSO: Desarrollo de Aplicaciones Web Laboratorio Nro. 01

2. Haga un resumen de la siguiente explicación de HttpSession.

The HttpSession interface in Java provides a way to maintain state (data) across multiple HTTP
requests from a single user. It's an important part of web application development because it allows
you to:

1. Maintain User State: HTTP is a stateless protocol, meaning each request from a client to a server is
independent and does not inherently carry any information about previous requests. HttpSession
allows you to associate state information with a specific user across multiple requests. This enables
the development of interactive and personalized web applications where user-specific data can be
stored and retrieved.

2. Handle Authentication and Authorization: HttpSession can be used to store user authentication
tokens or session identifiers after a user logs in. This allows the server to identify the user across
multiple requests without requiring the user to authenticate with each request. Additionally, you can
store user roles or permissions in the session to handle authorization.

3. Implement Shopping Carts and User Sessions: HttpSession is commonly used in e-commerce
applications to maintain shopping cart data for each user. It allows users to add items to their cart,
navigate through different pages, and make purchases without losing their cart data. Similarly,
HttpSession can be used to manage user sessions, storing information such as user preferences,
browsing history, or temporary data.

4. Manage User Sessions: HttpSession provides methods to manage the lifecycle of user sessions,
including creating, invalidating, and timing out sessions. This allows you to control how long session
data should be retained and when sessions should expire, helping to optimize server resources and
improve security.

5. Cross-Context Communication: HttpSession objects can be shared across multiple servlets or JSPs
within the same web application context. This allows different components of the application to
access and manipulate session data, enabling collaboration and communication between different
parts of the application.

Overall, HttpSession is a fundamental component of web application development in Java, providing a


mechanism for maintaining user state and enabling the development of interactive, personalized, and
secure web applications.
Nro. xxx

DISEÑO Y DESARROLLO DE SOFTWARE Página 6/11


CURSO: Desarrollo de Aplicaciones Web Laboratorio Nro. 01

3. Crear un JSP con conexión a base de datos.

Conector de MySQL en Maven.

<!-- MySQL Connector/J -->


<dependency>
Nro. xxx

DISEÑO Y DESARROLLO DE SOFTWARE Página 7/11


CURSO: Desarrollo de Aplicaciones Web Laboratorio Nro. 01

<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
</dependencies>

%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Add Student</title>
</head>
<body>

<%
// Database connection parameters
String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost:3306/students"; // Update with your database name
String USER = "root"; // Update with your database username
String PASS = ""; // Update with your database password

// Form data
String name = request.getParameter("name");
String ageParam = request.getParameter("age");
int age = 0;

// Check if form submitted


if (name != null && !name.isEmpty() && ageParam != null && !ageParam.isEmpty()) {
try {
// Parse age parameter
age = Integer.parseInt(ageParam);

// Register JDBC driver


Class.forName(JDBC_DRIVER);

// Open a connection
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO student (name, age)
VALUES (?, ?)")) {

// Set parameters for SQL statement


Nro. xxx

DISEÑO Y DESARROLLO DE SOFTWARE Página 8/11


CURSO: Desarrollo de Aplicaciones Web Laboratorio Nro. 01

pstmt.setString(1, name);
pstmt.setInt(2, age);

// Execute SQL statement


pstmt.executeUpdate();

out.println("<h2>Student added successfully!</h2>");

} catch (SQLException se) {


// Handle SQL exceptions
se.printStackTrace();
out.println("<p>Error: " + se.getMessage() + "</p>");
}
} catch (NumberFormatException e) {
// Handle invalid age format
e.printStackTrace();
out.println("<p>Error: Invalid age format</p>");
}
}
%>

<h2>Add Student</h2>
<form action="index.jsp" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" value="Add Student">
</form>

</body>
</html>
Nro. xxx

DISEÑO Y DESARROLLO DE SOFTWARE Página 9/11


CURSO: Desarrollo de Aplicaciones Web Laboratorio Nro. 01

4. Cree una tabla en la misma base se datos students e ingrese otros datos vía JSP.
Nro. xxx

DISEÑO Y DESARROLLO DE SOFTWARE Página 10/11


CURSO: Desarrollo de Aplicaciones Web Laboratorio Nro. 01
Nro. xxx

DISEÑO Y DESARROLLO DE SOFTWARE Página 11/11


CURSO: Desarrollo de Aplicaciones Web Laboratorio Nro. 01

Conclusiones:
Indicar las conclusiones que llegó después de los temas tratados de manera práctica en este laboratorio.

● La validación exhaustiva de datos es fundamental para garantizar la integridad y seguridad de la aplicación.


● Es esencial implementar una gestión cuidadosa y eficiente de las conexiones a la base de datos para evitar
problemas de seguridad y optimizar el rendimiento.
● La capacidad de adaptación a cambios en la estructura de la base de datos es crucial para mantener la coherencia y
funcionalidad de la aplicación a largo plazo.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy