JSP01:一个简单的JSP+Servlet项目开头

Posted 史前蓝熊

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JSP01:一个简单的JSP+Servlet项目开头相关的知识,希望对你有一定的参考价值。

练手:一个简单的JSP+Servlet项目开头

工具:

Apache NetBeans IDE 17

mysql 8.0.31

jdk 1.8

apache-tomcat-10.0.12

1.项目目录

2.具体代码

JSP代码

login.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
  <title>登录</title>
  <style>
    /* 样式表 */
    body 
      font-family: Arial, Helvetica, sans-serif;
      background-color: #f2f2f2;
    
    h1 
      text-align: center;
    
    form 
      border: 3px solid #f1f1f1;
      width: 50%;
      margin: auto;
      padding: 20px;
      background-color: #ffffff;
    
    input[type=text], input[type=password] 
      width: 100%;
      padding: 12px 20px;
      margin: 8px 0;
      display: inline-block;
      border: 1px solid #ccc;
      box-sizing: border-box;
    
    button[type=submit] 
      background-color: #4CAF50;
      color: white;
      padding: 14px 20px;
      margin: 8px 0;
      border: none;
      cursor: pointer;
      width: 100%;
    
    button[type=submit]:hover 
      opacity: 0.8;
    
    .container 
      padding: 16px;
    
    span.psw 
      float: right;
      padding-top: 16px;
    
    /* 清除浮动 */
    .clearfix::after 
      content: "";
      clear: both;
      display: table;
    
  </style>
</head>
<body>
  <h1>登录</h1>
  <form method="post" action="LoginServlet" >
    <div class="container">
      <label for="username"><b>用户名:</b></label>
      <input type="text" placeholder="请输入用户名" name="username" required>

      <label for="password"><b>密码:</b></label>
      <input type="password" placeholder="请输入密码" name="password" required>
      <button type="submit">登录</button>
    </div>
    <div class="container clearfix">
      <a href="register.jsp" >没有账号?点击这里注册!</a>
    </div>
  </form>
</body>
</html>

register.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
  <title>注册</title>
  <style>
    /* 样式表 */
    body 
      font-family: Arial, Helvetica, sans-serif;
      background-color: #f2f2f2;
    
    h1 
      text-align: center;
    
    form 
      border: 3px solid #f1f1f1;
      width: 50%;
      margin: auto;
      padding: 20px;
      background-color: #ffffff;
    
    input[type=text], input[type=password] 
      width: 100%;
      padding: 12px 20px;
      margin: 8px 0;
      display: inline-block;
      border: 1px solid #ccc;
      box-sizing: border-box;
    
    button[type=submit] 
      background-color: #4CAF50;
      color: white;
      padding: 14px 20px;
      margin: 8px 0;
      border: none;
      cursor: pointer;
      width: 100%;
    
    button[type=submit]:hover 
      opacity: 0.8;
    
    .container 
      padding: 16px;
    
    /* 清除浮动 */
    .clearfix::after 
      content: "";
      clear: both;
      display: table;
    
    .error 
      color: red;
    
    .success 
      color: green;
    
  </style>
</head>
<body>
  <h1>注册</h1>
  <form method="post" action="RegisterServlet" class="clearfix">
    <div class="container">
      <label for="username"><b>用户名:</b></label>
      <input type="text" placeholder="请输入用户名" name="username" required>

      <label for="password"><b>密码:</b></label>
      <input type="password" placeholder="请输入密码" name="password" id="password" pattern="^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]8,$" required>
      <p class="error">密码必须包含大小写字母和数字,并且至少8位</p>

      <label for="password_confirm"><b>确认密码:</b></label>
      <input type="password" placeholder="请再次输入密码" name="password_confirm" id="password_confirm" required>
      <p class="error">两次输入的密码必须相同</p>
      <p class="success">密码符合要求</p>

      <button type="submit">注册</button>
    </div>
    <div class="container clearfix">
      <a href="login.jsp" >已有账号?点击这里登录!</a>
    </div>
  </form>
  <script>
    // 添加密码复杂度和一致性检查
    const password = document.getElementById("password");
    const confirmPassword = document.getElementById("password_confirm");
    const errorMessages = document.querySelectorAll(".error");
    const successMsg = document.querySelector(".success");

    function checkPasswords() 
      if (password.value !== confirmPassword.value) 
        errorMessages[1].style.display = "block";
        successMsg.style.display = "none";
       else 
        errorMessages[1].style.display = "none";
        successMsg.style.display = "block";
      
    

    function checkPasswordStrength() 
      const passwordRegex = /^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]8,$/;
      if (password.value.match(passwordRegex)) 
        errorMessages[0].style.display = "none";
       else 
        errorMessages[0].style.display = "block";
      
    

    password.addEventListener("input", checkPasswords);
    confirmPassword.addEventListener("input", checkPasswords);
    password.addEventListener("input", checkPasswordStrength);
  </script>
</body>
</html>

home.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>宠物医院</title>
  <style>
    /* 导航栏样式 */
    .navbar 
      background-color: #333;
      overflow: auto;
      text-align: center;
    
    .navbar a 
      color: white;
      text-decoration: none;
      font-size: 20px;
      float: left;
      padding: 12px 16px;
    
    .navbar a:hover 
      background-color: #ddd;
      color: black;
    

    /* 轮播图样式 */
    .slideshow 
      position: relative;
    
    .slideshow img 
      display: block;
      width: 100%;
      height: auto;
    
    .slideshow .dots 
      position: absolute;
      bottom: 0;
      width: 100%;
      text-align: center;
    
    .slideshow .dot 
      display: inline-block;
      margin: 0 5px;
      width: 10px;
      height: 10px;
      border-radius: 50%;
      background-color: gray;
      cursor: pointer;
    
    .slideshow .active 
      background-color: white;
    

    /* 服务介绍样式 */
    .services 
      text-align: center;
      margin: 80px 0;
    
    .services h2 
      font-size: 36px;
      margin-bottom: 40px;
    
    .services .card 
      display: inline-block;
      width: 30%;
      background-color: #f5f5f5;
      border-radius: 20px;
      padding: 30px;
      margin: 20px;
    
    .services .card h3 
      font-size: 24px;
      margin-bottom: 20px;
    
    .services .card p 
      font-size: 16px;
      line-height: 1.5;
      margin-bottom: 30px;
    

    /* 新闻动态样式 */
    .news 
      text-align: center;
      background-color: #333;
      color: white;
      padding: 80px 0;
    
    .news h2 
      font-size: 36px;
      margin-bottom: 40px;
    
    .news .article 
      display: inline-block;
      width: 30%;
      background-color: white;
      border-radius: 20px;
      padding: 30px;
      margin: 20px;
      box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
      text-align: left;
    
    .news .article h3 
      font-size: 24px;
      margin-bottom: 20px;
    
    .news .article p 
      font-size: 16px;
      line-height: 1.5;
      margin-bottom: 30px;
    

    /* 联系方式样式 */
    .contact 
      text-align: center;
      background-color: #f5f5f5;
      padding: 80px;
    
    .contact h2 
      font-size: 36px;
      margin-bottom: 40px;
    
    .contact p 
      font-size: 24px;
      margin-bottom: 20px;
    
  </style>
</head>
<body>
  <!-- 导航栏 -->
  <div class="navbar">
    <a href="#">首页</a>
    <a href="#">服务项目</a>
    <a href="#">医生团队</a>
    <a href="#">新闻动态</a>
    <a href="#">联系我们</a>
  </div>

  <!-- 轮播图 -->
  <div class="slideshow">
    <img src="https://picsum.photos/1200/500/?random=1" >
    <img src="https://picsum.photos/1200/500/?random=2" >
    <img src="https://picsum.photos/1200/500/?random=3" >
    <div class="dots">
      <span class="dot active"></span>
      <span class="dot"></span>
      <span class="dot"></span>
    </div>
  </div>

  <!-- 服务介绍 -->
  <div class="services">
    <h2>我们的服务项目</h2>
    <div class="card">
      <h3>疫苗接种</h3>
      <p>为您的宠物提供各种疫苗接种与预防保健服务,让它们健康成长。</p>
    </div>
    <div class="card">
      <h3>手术治疗</h3>
      <p>高水平的外科医生团队,为您的宠物提供各种手术治疗服务。</p>
    </div>
    <div class="card">
      <h3>诊断检查</h3>
      <p>全面的诊疗设备,帮助医生快速准确地诊断宠物的病情,为其制定最佳治疗方案。</p>
    </div>
  </div>

  <!-- 新闻动态 -->
  <div class="news">
    <h2>最新动态</h2>
    <div class="article">
      <h3>怎样给宠物洗澡比较好?</h3>
      <p>洗澡是宠物日常护理的重要环节,但如果不正确地给宠物洗澡,反而会对其健康造成不利影响。</p>
    </div>
    <div class="article">
      <h3>如何预防宠物感冒?</h3>
      <p>在寒冷的天气里,宠物也容易感冒,而且感冒后的宠物病情往往不容乐观。那么我们该如何预防宠物感冒呢?</p>
    </div>
    <div class="article">
      <h3>如何选择猫咪粮?</h3>
      <p>猫咪粮的质量直接影响宠物的健康,因此选择一款适合的猫咪粮是非常重要的。</p>
    </div>
  </div>

  <!-- 联系方式 -->
  <div class="contact">
    <h2>联系我们</h2>
    <p>地址:XX省XX市XX区XX街道XX号</p>
    <p>电话:0123-4567890</p>
    <p>邮箱:info@pet-hospital.com</p>
  </div>
</body>
</html>


web.xml代码

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>test.LoginServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>RegisterServlet</servlet-name>
        <servlet-class>test.RegisterServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>RegisterServlet</servlet-name>
        <url-pattern>/RegisterServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Java代码

LoginServlet.java

package test;

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

public class LoginServlet extends HttpServlet 
  @Override
  public void doPost(HttpServletRequest request,HttpServletResponse response) 
  throws ServletException, IOException 
    String username = request.getParameter("username");
    String password = request.getParameter("password");

    // 进行用户认证
    boolean isAuthenticated = authenticate(username, password);

    if (isAuthenticated) 
      // 认证成功,将用户信息保存到 session 中
      // 跳转到主页
      response.sendRedirect("home.jsp");
     else 
      // 认证失败,返回登录页面
      response.sendRedirect("login.jsp");
    
  

  // 自定义用户认证逻辑
  private boolean authenticate(String username, String password) 

    boolean isUserExist = false;
    
    try 
        // 加载数据库驱动
        Class.forName("com.mysql.jdbc.Driver");

        // 建立数据库连接
        String url = "jdbc:mysql://localhost:3306/jsp";
        String dbUsername = "root";
        String dbPassword = "root";
        Connection connection = DriverManager.getConnection(url, dbUsername, dbPassword);

        // 准备 SQL 查询语句
        String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, username);
        statement.setString(2, password);

        // 执行查询操作
        ResultSet resultSet = statement.executeQuery();

        // 判断查询结果是否存在
        if (resultSet.next()) 
            isUserExist = true;
        

        // 关闭数据库连接
        resultSet.close();
        statement.close();
        connection.close();
        
     catch (ClassNotFoundException | SQLException e) 
        e.printStackTrace();
    
    
      
    return isUserExist;
  


RegisterServlet.java

package test;

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

public class RegisterServlet extends HttpServlet 
  public void doPost(HttpServletRequest request,HttpServletResponse response) 
  throws ServletException, IOException 
    String username = request.getParameter("username");
    String password = request.getParameter("password");

    // 进行用户注册逻辑
    boolean isRegisterSuccessful = register(username, password);

    if (isRegisterSuccessful) 
      // 注册成功,将用户信息保存到 session 中
      HttpSession session = request.getSession(true);
      session.setAttribute("username", username);

      // 跳转到主页
      response.sendRedirect("home.jsp");
     else 
      // 注册失败,返回注册页面
      response.sendRedirect("register.jsp");
    
  

  // 自定义用户注册逻辑
  private boolean register(String username, String password ) 
      boolean isUserExist = false;

        try (
            
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp", "root", "root")) 
            // 创建 PreparedStatement 对象,并设置参数
            PreparedStatement pstmt = conn.prepareStatement("INSERT INTO user (username, password) VALUES (?, ?)");
            pstmt.setString(1, username);
            pstmt.setString(2, password);

            // 执行插入操作并获取返回结果
            int rowsAffected = pstmt.executeUpdate();
            
            // 判断插入是否成功
            if (rowsAffected > 0) 
                isUserExist = true;
             else 
                System.out.println("Insert failed.");
            

         catch (SQLException e) 
            System.out.println("Database connection failed.");
            e.printStackTrace();
        

      
    // 省略具体实现
    return isUserExist;
  


数据库:

mySQL数据库:

1.建立数据库
CREATE DATABASE JSP;

2.选中数据库
use  JSP;
 
3.在选中的数据库中创建user表
CREATE TABLE user (
       username VARCHAR(50) NOT NULL,
       password VARCHAR(50) NOT NULL,
       PRIMARY KEY (username)
    );

运行结果:

实现功能:

  1. 登录(与数据库进行信息比对)
  2. 注册(包含密码强度要求【正则表达式】,密码二次确定)
  3. 简单的home主页面。





servlet+jsp 实现一个简单的web项目

开发环境:

  MyEclipse 10.7

  Tomcat   7

  MySql  5.5

开发过程

 1. 建立一个 Web Project,名字为 MyProject,如下图,点击finish,就创建好了。


2. 修改项目编码为Utf-8,在src下创建类,首先 看一下项目结构

 

2.1  创建实体类类 User 

   package entity;

public class User {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}

2.2 创建jdbc 连接及数据库的表,在这里要记得把数据库的 jar 加上,我用的mySql,把mysql-connector-java.jar 加到lib下。

     package util;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;


public class Jdbc {
//连接
public static Connection connect()throws SQLException, ClassNotFoundException{
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver");
//取得连接的url,能访问MySQL数据库的用户名,密码;user:数据库表名 
String url = "jdbc:mysql://localhost:3306/user"; 
String username = "root"; 
String password = "root"; 

   conn =(Connection) DriverManager.getConnection(url, username, password); 
return conn;
}

//关闭
public static void close(Statement stat, Connection conn) throws SQLException{
if(stat != null){
stat.close();
}
if(conn != null){
conn.close();
}
}


}


2.3 修改 url 、用户名和密码,在这里可以直接用main方法测试是否连接成功。写UserDao,这里只写了一个查询。

package dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import entity.User;
import util.Jdbc;

public class UserDao {
public ArrayList<User> search(String id) throws ClassNotFoundException, SQLException{
Connection con = Jdbc.connect();
Statement sta = null;
ResultSet rs = null;
sta = (Statement) con.createStatement();
 
ArrayList<User> users = new ArrayList<User>();
rs = (ResultSet) sta.executeQuery("select * from T_USER where Id = ‘"+id+"‘");
while(rs.next()){
User u = new User();
u.setId(rs.getString("idNumber"));
u.setName(rs.getString("name"));
users.add(u);
}

if(rs != null){
rs.close();
}
Jdbc.close(sta, con);
return users;
}


}

 2.4 写 ActionServlet。直接创建Servlet方便一些。

package web;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.UserDao;
import entity.User;

public class ActionServlet extends HttpServlet {


public void service(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
String uri = request.getRequestURI();
uri = uri.substring(uri.indexOf("MyProject/") + 10, uri.lastIndexOf("."));

if(uri.equals("show")){
try {
show(request,response);
} catch (Exception e) {
e.printStackTrace();

}
}

// 查看列表
public void show(HttpServletRequest request, HttpServletResponse response)
throws Exception {
String id = request.getParameter("id");
//根据id查询
List<User> userList = new UserDao().search(id);
//返回页面
request.setAttribute("userList", userList);
request.getRequestDispatcher("record.jsp").forward(request, response);
}


}

2.5 修改web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ActionServlet</servlet-name>
    <servlet-class>web.ActionServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>ActionServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

3.这样后台就写完了,下面开始写jsp页面。

修改 index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP ‘index.jsp‘ starting page</title>

  </head>
  
  <body>
   <div>
     <form action="show.do" method="post">
        ID:<input type="text" id="id" name="id" size="18"/>
        <input type="submit" value="提交"/> 
    </form>
   </div>
  </body>
</html>

4. 添加 record.jsp

  <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<%@ page import ="entity.User" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP ‘index.jsp‘ starting page</title>

<style type="text/css">
td{
border:1px solid #89c3eb;
width:200px;
height:30px;
text-align:center;
margin:0px;
padding:0px;
}
  tr{
margin:0px;
padding:0px;
   }
</style>
  </head>
  
  <body>
  <div>
   人员信息<br/>
       <%
    List<User> lists =(ArrayList)request.getAttribute("userList");
    if(lists.size() == 0){
        out.print("无查询记录");
    }else{
       out.print("<table  cellspacing=‘0px‘ cellpadding=‘0px‘>");
       out.print("<tr><td>姓名</td><td>ID</td></tr>");
       for(int i=0;i<lists.size();i++){
                User u = lists.get(i);
                out.print("<tr>");
                out.print("<td>"+u.getName()+"</td>");
                out.print("<td>"+u.getId()+"</td>");
                out.print("</tr>");
            }
       out.print("</table>");
    }
   
    %>
   </div>
  </body>
</html>

5. 部署程序到tomcat,在浏览器访问地址 http://localhost:8080/MyProject/ 可以看到index.jsp的内容,输入Id提交就能看到数据了。


以上是关于JSP01:一个简单的JSP+Servlet项目开头的主要内容,如果未能解决你的问题,请参考以下文章

servlet+jsp 实现一个简单的web项目

JSP 隐藏技巧大公开

JSP 隐藏技巧大公开

08.17《jsp》——html+css+js+jsp+servlet+oracle简单项目练习

一个简单的jsp+servlet实例,实现简单的登录

JSP # JSP入门及简单概述