基于jsp+servlet的javaweb实现最基本的用户注册登陆注销功能

简介: 基于jsp+servlet的javaweb实现最基本的用户注册登陆注销功能

项目的层级结构图如下:

1. 先设计数据库,有两种方式:

a)编写SQL代码[推荐]:

    1. 创建sql文件:

   


  2. 编写SQL代码:        

-- 创建数据库
create database login;
-- 选择数据库
use login;
-- 创建用户表
create table user(
  id int primary key auto_increment, -- 用户编号 - 主键(自动递增)
  username varcahr(30), -- 用户名
  password varcahr(30),   -- 用户密码
  email varcahr(50),    -- 用户邮箱
  sex  varcahr(50)  -- 用户性别 [注:最后一个字段,不要再最后加入“,”]
);

3. 使用代码进行执行建表!

b)使用可视化窗口进行建表

2. 开始写实体类:User.java

package cn.javabs.login.entity;
 
/**
 * Title: User.java
 * @date 2018年10月5日 下午3:19:40
 * @author Mr.yang
 * 用户的实体类设计  
 */
public class User {
  
  private Integer id;
  
  private String username;
  
  private String password;
  
  private String sex;
  
  private String email;
  
  
 
  public Integer getId() {
    return id;
  }
 
  public void setId(Integer id) {
    this.id = id;
  }
 
  public String getUsername() {
    return username;
  }
 
  public void setUsername(String username) {
    this.username = username;
  }
 
  public String getPassword() {
    return password;
  }
 
  public void setPassword(String password) {
    this.password = password;
  }
 
  public String getEmail() {
    return email;
  }
 
  public void setEmail(String email) {
    this.email = email;
  }
 
  public String getSex() {
    return sex;
  }
 
  public void setSex(String sex) {
    this.sex = sex;
  }
}

3.接下来写的是DAO的接口

package cn.javabs.login.dao;
 
import java.sql.SQLException;
 
import cn.javabs.login.entity.User;
 
/**
 * Title: UserDao.java
 * @date 2018年10月5日 下午3:24:55
 * @author Mr.yang  
 * 用户的DAO接口设计
 *      |--- 接口是不可以被final修饰的哦!
 *    |--- 登录
 *    |--- 注册
 */
public interface UserDao {
  
  /**
   * 用户登录(需要传入两个参数)
   * @param username 用户名 
   * @param password 密码
   * @return  用户对象
   * @throws SQLException 
   */
  User login(String username,String password) throws SQLException;
 
  /**
   * 用户注册(传入的是对象)
   * @param user
   * @return 整数
   * @throws SQLException 
   */
  int regist(User user) throws SQLException;
  
}


4.接下来写的是DAO的实现类

package cn.javabs.login.dao.impl;
 
import java.sql.SQLException;
 
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
 
import cn.javabs.login.dao.UserDao;
import cn.javabs.login.entity.User;
import cn.javabs.login.util.DBCPUtils;
 
/**
 * Title: UserDaoImpl.java
 * 用户的DAO实现类的设计
 * @date 2018年10月5日 下午3:28:33
 * @author Mr.yang 采用[数据源连接池 - DBCP] 使用Dbutils工具类中的QueryRunner进行
 */
public class UserDaoImpl implements UserDao {
 
  QueryRunner queryRunner = new QueryRunner(DBCPUtils.getDataSource());
 
  @Override
  public User login(String username, String password) throws SQLException {
    return queryRunner.query(
        "select * from user where username = ? and password = ?", //
        new BeanHandler<User>(User.class), username, password);
  }
 
  @Override
  public int regist(User user) throws SQLException {
    
    return queryRunner.update("insert into user(username,password,sex,email)values(?,?,?,?)",
        user.getUsername(),
        user.getPassword(),
        user.getSex(),
        user.getEmail()       
        );
    
  }
 
}

4.接下来需要把DAO中的用到的数据源连接池的工具类补全

package cn.javabs.login.util;
 
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
 
import javax.sql.DataSource;
 
import org.apache.commons.dbcp2.BasicDataSourceFactory;
 
/**
 * Title: DBCPUtils.java
 * 
 * @date 2018年10月5日 下午4:04:48
 * @author Mr.yang
 */
public class DBCPUtils {
 
  public static DataSource dataSource;
 
  static {
 
    try {
      String resource = "jdbc.properties";
      InputStream is = DBCPUtils.class.getClassLoader()
          .getResourceAsStream(resource);
      Properties properties = new Properties();
      properties.load(is);
      dataSource = BasicDataSourceFactory.createDataSource(properties);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
 
  }
 
  /**
   * 获取数据源
   * @return
   */
  public static DataSource getDataSource() {
    return dataSource;
  }
 
  /**
   * 获取连接
   * @return
   */
  public static Connection getConnection() {
    try {
      return dataSource.getConnection();
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
  }
 
}

4.2 在config的中创建配置文件:jdbc.properties

driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql:///login
username = root
password = sorry
 
# 初始化连接
initialSize=10
# 最大连接数量
maxActive=50
# 最大空闲数量
maxIdle=20
# 最小空闲数量
minIdle=5


5.接下来把service层的接口设计出来

package cn.javabs.login.service;
 
import cn.javabs.login.entity.User;
 
 
/**
 * Title: UserService.java
 * @date 2018年10月5日 下午4:15:04
 * @author Mr.yang  
 */
public interface UserService {
 
  /**
   * 用户登录(传入两个参数,用户名和密码)
   * @param username
   * @param password
   * @return 用户对象
   */
  User userLogin(String username,String password);
 
  /**
   * 用户注册(传入的是对象)
   * @param user
   * @return 影响的行数
   */
  int userRegister(User user);  
  
  
}

6.接下来把service层的实现类设计出来

package cn.javabs.login.service.impl;
 
import java.sql.SQLException;
 
import cn.javabs.login.dao.UserDao;
import cn.javabs.login.dao.impl.UserDaoImpl;
import cn.javabs.login.entity.User;
import cn.javabs.login.service.UserService;
 
/**
 * Title: UserServiceImpl.java
 * @date 2018年10月5日 下午4:17:34
 * @author Mr.yang  
 */
public class UserServiceImpl implements UserService {
 
  UserDao userDao = new UserDaoImpl();
  
  @Override
  public User userLogin(String username, String password) {
    
    try {
      User user = userDao.login(username, password);
      return user;
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
    
  }
 
  @Override
  public int userRegister(User user) {
    try {
      return userDao.regist(user);
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
  }
 
}

7.接下来把controller层的控制器设计出来

package cn.javabs.login.controller;
 
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.lang3.StringUtils;
 
import cn.javabs.login.entity.User;
import cn.javabs.login.service.UserService;
import cn.javabs.login.service.impl.UserServiceImpl;
 
/**
 * 
 * @author Mryang StringUtilsz中的isNotbBlock:判断某字符串是否不为空且长度不为0且不由空白符构成
 *
 */
public class UserServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
 
  // 引入UserService
  UserService userService = new UserServiceImpl();
 
  protected void doGet(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
  }
 
  protected void doPost(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
 
    String method = request.getParameter("method");
 
    // 如果传入的参数是login
    if ("login".equals(method)) {
      login(request, response);
      // 如果传入的参数是regist
    } else if ("regist".equals(method)) {
      regist(request, response);
      // 如果传入的参数是logout
    } else if ("logout".equals(method)) {
      logout(request, response);
      // 如果传入的参数是tologin
    } else if ("tologin".equals(method)) {
      tologin(request, response);
      // 如果传入的参数是toregist
    } else if ("toregist".equals(method)) {
      toregist(request, response);
      // 如果传入的参数是对应不上
    } else {
      request.setAttribute("msg", "该功能正在开发...");
      request.getRequestDispatcher("/message.jsp").forward(request, response);
    }
 
  }
 
  /**
   * 用户登录
   * 
   * @param request
   * @param response
   */
  private void login(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    /*
     * 1. 获取前台jsp表单传递的参数
     */
    String username = request.getParameter("username");
    String password = request.getParameter("password");
 
    // 如果测试传入的参数。可以打开72行的注释
    // System.out.println("用户名:" + username + "<br/>" + "密码" + password);
 
    /*
     * 2.根据参数进行判断
     */
    // 2.1 如果用户名和密码都不为空
    if (StringUtils.isNotBlank(username)
        && StringUtils.isNotBlank(password)) {
      // 2.1.1 传递到service层登录方法
      User user = userService.userLogin(username, password);
      // 2.1.2 判断用户信息是否查询到
      if (user != null) {
        // 查询到,存入session
        request.getSession().setAttribute("USER_SESSION", user);
        // 登录成功,转向主页
        request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(
            request, response);
      } else {
        // 未查询到或者用户名和密码不匹配,将失败的信息存储到msg中
        request.setAttribute("msg", "用户名或者密码不对!");
        // 登录失败,转向错误信息提示页面,根据存入的msg取出相对应的内容
        request.getRequestDispatcher("/message.jsp").forward(request,
            response);//
      }
      // 2.2 如果用户名或者密码为空
    } else {
      request.setAttribute("msg", "用户名或者密码不许为空!");
      request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(
          request, response);//
    }
 
  }
 
  /**
   * 用户注册
   * 
   * @param request
   * @param response
   * @throws ServletException
   * @throws IOException
   */
  private void regist(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
 
    User user = new User();
 
    // 1. 获取前台jsp页面的参数
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String sex = request.getParameter("sex");
    String email = request.getParameter("email");
 
    // 2. 将获取到的参数封装到user对象中去
    user.setUsername(username);
    user.setPassword(password);
    user.setEmail(email);
    user.setSex(sex);
 
    if (StringUtils.isNotBlank(user.getUsername())
        && StringUtils.isNotBlank(user.getPassword())) {
 
      int rows = userService.userRegister(user);
      if (rows > 0) {
        response.setHeader("refresh",
            "1;url=UserServlet?method=tologin");
      } else {
        request.setAttribute("msg", "注册失败!");
        request.getRequestDispatcher("/message").forward(request,
            response);
      }
    }else{
      request.setAttribute("msg", "用户名或者密码不许为空");
      request.getRequestDispatcher("/message").forward(request,
          response);
    }
 
  }
 
  /**
   * 转向到登录页面
   * 
   * @param request
   * @param response
   * @throws ServletException
   * @throws IOException
   */
  private void tologin(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
    request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,
        response);//
  }
 
  /**
   * 转向到注册页面
   * 
   * @param request
   * @param response
   * @throws ServletException
   * @throws IOException
   */
  private void toregist(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
    request.getRequestDispatcher("/WEB-INF/jsp/regist.jsp").forward(
        request, response);//
  }
  
  /**
   * 用户注销
   * @param request
   * @param response
   * @throws ServletException
   * @throws IOException
   */
  private void logout(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
    request.getSession().invalidate();
    request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(
        request, response);//
  }
 
}

8.首页

 <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <jsp:forward page="WEB-INF/jsp/regist.jsp"></jsp:forward>
</body>
</html>

登录页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
  <link rel="stylesheet" href="css/reset.css" />
  <link rel="stylesheet" href="css/login.css" />
        <script type="text/javascript" src="js/jquery.min.js"></script>
  <style type="text/css">
    #err{
      color: red;
      margin-left: 115px;
      margin-top: 25px;
      padding-top: 22px;
    }
    #toregist{
        margin-left: 280px;
        font-size: 14px; 
        text-decoration: none;
        color:deepskyblue;
    }
    a:HOVER {
      color:red;
      font-size: 15px; 
      text-decoration: underline;
    }
  </style>
</head>
<body>
<div class="page">
  <div class="loginwarrp">
    <div class="logo">管理员登陆</div>
    <br />
    <span id="err">${msg }</span><!-- 错误信息提示  -->
    <a id="toregist" href="${pageContext.request.contextPath}/UserServlet?method=toregist">没有账号,去注册</a>
        <div class="login_form">
      <form id="Login" name="Login" method="post"  action="${pageContext.request.contextPath}/UserServlet?method=login">
        <li class="login-item">
          <span>用户名:</span>
          <input type="text" id="username" name="username" class="login_input" >
                                        <span id="count-msg" class="error"></span>
        </li>
        <li class="login-item">
          <span>密 码:</span>
          <input type="password" id="password" name="password" class="login_input" >
                                        <span id="password-msg" class="error"></span>
        </li>
        <!--
        <li class="login-item verify">
          <span>验证码:</span>
          <input type="text" name="CheckCode" class="login_input verify_input">
        </li>
        <img src="images/verify.png" border="0" class="verifyimg" />
        -->
        <div class="clearfix"></div>
        <li class="login-sub">
          <input type="submit" name="Submit" value="登录" />
                                        <input type="reset" name="Reset" value="重置" />
        </li>                      
           </form>
    </div>
  </div>
</div>
<script type="text/javascript">
    window.onload = function() {
      var config = {
        vx : 4,
        vy : 4,
        height : 2,
        width : 2,
        count : 100,
        color : "121, 162, 185",
        stroke : "100, 200, 180",
        dist : 6000,
        e_dist : 20000,
        max_conn : 10
      }
      CanvasParticle(config);
    }
  </script>
  <script type="text/javascript" src="js/canvas-particle.js"></script>
</body>
</html>


9.注册页面

 <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html> 
<html>
  <head>
    <title>${initParam.MyTitle}</title>
    
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
    
    <link rel="stylesheet" href="css/demo.css">
    <link rel="stylesheet" href="css/sky-forms.css">
    <link rel="stylesheet" href="css/sky-forms-ie8.css">
    <script src="js/jquery-1.9.1.min.js"></script>
    <script src="js/jquery.validate.min.js"></script>
    <script src="js/jquery.placeholder.min.js"></script>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <script src="js/sky-forms-ie8.js"></script>
    <style type="text/css">
      #tologin{
        margin-left: 220px;
        font-size: 14px; 
        text-decoration: none;
      }
      a:HOVER {
        color:red;
        font-size: 15px; 
        text-decoration: underline;
      }
    </style>
  </head>
  
  <body class="bg-cyan">
    <div class="body body-s">   
      <form action="${pageContext.request.contextPath}/UserServlet?method=regist" method="post" id="sky-form" class="sky-form">
        <header>请填写表单</header>
        <fieldset>          <!--  -->
          <a id="tologin" href="${pageContext.request.contextPath}/UserServlet?method=tologin">已有账号,去登录</a>
          <br />
          <br />
          <section>
            <label class="input">
              <i class="icon-append icon-user"></i>
              <input type="text" name="username" placeholder="用户名">
              <b class="tooltip tooltip-bottom-right">请输入用户名</b>
            </label>
          </section>
          
          <section>
            <label class="input">
              <i class="icon-append icon-envelope-alt"></i>
              <input type="email" name="email" placeholder="Email">
              <b class="tooltip tooltip-bottom-right">请输入您的Email地址</b>
            </label>
          </section>
          
          <section>
            <label class="input">
              <i class="icon-append icon-lock"></i>
              <input type="password" name="password" placeholder="密码" id="password">
              <b class="tooltip tooltip-bottom-right">请输入您的密码</b>
            </label>
          </section>
          
          <section>
            <label class="input">
              <i class="icon-append icon-lock"></i>
              <input type="password" name="passwordConfirm" placeholder="请再次输入您的密码">
              <b class="tooltip tooltip-bottom-right">请再次输入您的密码</b>
            </label>
          </section>
      
          <section>
            <label class="select">
              <select name="sex">
                <option value="0" selected disabled>请选择性别</option>
                <option value="1">男性</option>
                <option value="2">女性</option>
          
              </select>
              <i></i>
            </label>
          </section>
        </fieldset>
        <fieldset>
          
          <section>
            <label class="checkbox"><input type="checkbox" name="subscription" id="subscription"><i></i>I 
          我愿意接受互联网研习社最新动态</label>
            <label class="checkbox"><input type="checkbox" name="terms" id="terms"><i></i>I 
          我同意注册许可</label>
          </section>
        </fieldset>
        <footer>
          <button type="submit" class="button">提交注册</button>
        </footer>
      </form>     
    </div>
    
    <script type="text/javascript">
      $(function()
      {
        // Validation   
        $("#sky-form").validate(
        {         
          // Rules for form validation
          rules:
          {
            username:
            {
              required: true
            },
            email:
            {
              required: true,
              email: true
            },
            password:
            {
              required: true,
              minlength: 3,
              maxlength: 20
            },
            passwordConfirm:
            {
              required: true,
              minlength: 3,
              maxlength: 20,
              equalTo: '#password'
            },
            firstname:
            {
              required: true
            },
            lastname:
            {
              required: true
            },
            gender:
            {
              required: true
            },
            terms:
            {
              required: true
            }
          },
          
          // Messages for form validation
          messages:
          {
            login:
            {
              required: 'Please enter your login'
            },
            email:
            {
              required: 'Please enter your email address',
              email: 'Please enter a VALID email address'
            },
            password:
            {
              required: 'Please enter your password'
            },
            passwordConfirm:
            {
              required: 'Please enter your password one more time',
              equalTo: 'Please enter the same password as above'
            },
            firstname:
            {
              required: 'Please select your first name'
            },
            lastname:
            {
              required: 'Please select your last name'
            },
            gender:
            {
              required: 'Please select your gender'
            },
            terms:
            {
              required: 'You must agree with Terms and Conditions'
            }
          },          
          
          // Do not change code below
          errorPlacement: function(error, element)
          {
            error.insertAfter(element.parent());
          }
        });
      });     
    </script>
 <div style="width:960px;margin:10px auto; clear:both; text-align:center;  ">
<script src="/statics/js/ad/96090.js" type="text/javascript"></script>
</div>
<div style="width:960px;margin:20px auto; clear:both; text-align:center; font-size:12px; line-height:25px;    ">
<a href="https://blog.csdn.net/kese7952"  style="color:#333"><strong>Mryang个人整理</strong></a> </strong>
 转载请自觉注明出处!注:此代码仅供学习交流,请勿用于商业用途。
<br>
关注更多学习内容更新 请加入Java学习交流群 : <strong>827829292</strong> <a target="_blank" href="https://jq.qq.com/?_wv=1027&k=5gfNSI6"><img border="0" src="http://pub.idqqimg.com/wpa/images/group.png" 
alt="编程研习社QQ群①" title="编程研习社QQ群①"></a> 
<script src="/statics/js/inc_share.js"  type="text/javascript"></script>
<script src="/statics/js/inc_statistics.js"  type="text/javascript"></script>
<script src="/statics/js/inc_monitor.js"  type="text/javascript"></script> 
</div>
  </body>
</html>

10.登录成功页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  
  <center>
    <h3>
      ${sessionScope.USER_SESSION.username},遇到您真好!
    </h3>
    <hr/>
    <h4>
      <a href="${pageContext.request.contextPath}/UserServlet?method=logout">如果您呆的厌倦了,可以点我离开</a>
    </h4>
  </center>
  
</body>
</html>

错误提示页面

 <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  ${msg}
</body>
</html>

web.xml的配置文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  
  <context-param>
    <param-name>MyTitle</param-name>
    <param-value>javaWeb案例之用户的注册</param-value>
  </context-param>  
  
  
  <display-name>Login</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>UserServlet</display-name>
    <servlet-name>UserServlet</servlet-name>
    <servlet-class>cn.javabs.login.controller.UserServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>/UserServlet</url-pattern>
  </servlet-mapping>
</web-app>

最终的页面效果如下所示:

目录
相关文章
|
19天前
|
存储 设计模式 搜索推荐
早期javeweb技术 JSP JDBC JSTJ Servlet BooStrap(下)
早期javeweb技术 JSP JDBC JSTJ Servlet BooStrap(下)
10 1
|
6天前
|
XML Java 数据格式
jsp和servlet有什么区别?
总的来说,JSP和Servlet都是创建动态Web应用程序的重要工具,但它们的使用依赖于特定的需求和上下文。
8 0
|
7天前
|
XML Java 数据格式
jsp和servlet有什么区别?
总的来说,JSP和Servlet都是创建动态Web应用程序的重要工具,但它们的使用依赖于特定的需求和上下文。
13 0
|
19天前
|
XML 前端开发 Java
早期javeweb技术 JSP JDBC JSTJ Servlet BooStrap(上)
早期javeweb技术 JSP JDBC JSTJ Servlet BooStrap(上)
10 0
|
2月前
|
Java
排课系统【JSP+Servlet+JavaBean】(Java课设)
排课系统【JSP+Servlet+JavaBean】(Java课设)
50 5
|
22天前
|
自然语言处理 前端开发 Java
Servlet与JSP:Java Web开发的基石技术详解
【6月更文挑战第23天】Java Web的Servlet与JSP是动态网页的核心。Servlet是服务器端的Java应用,处理HTTP请求并响应;JSP则是结合HTML与Java代码的页面,用于动态内容生成。Servlet通过生命周期方法如`init()`、`service()`和`destroy()`工作,而JSP在执行时编译成Servlet。两者在MVC架构中分工,Servlet处理逻辑,JSP展示数据。尽管有Spring MVC等框架,Servlet和JSP仍是理解Web开发基础的关键。
|
22天前
|
存储 Java 关系型数据库
基于Servlet和JSP的Java Web应用开发指南
【6月更文挑战第23天】构建Java Web应用,Servlet与JSP携手打造在线图书管理系统,涵盖需求分析、设计、编码到测试。通过实例展示了Servlet如何处理用户登录(如`LoginServlet`),JSP负责页面展示(如`login.jsp`和`bookList.jsp`)。应用基于MySQL数据库,包含用户和图书表。登录失败显示错误信息,成功后展示图书列表。部署到Tomcat服务器测试功能。此基础教程为深入Java Web开发奠定了基础。
|
22天前
|
缓存 小程序 前端开发
Java服务器端技术探秘:Servlet与JSP的核心原理
【6月更文挑战第23天】Java Web开发中的Servlet和JSP详解:Servlet是服务器端的Java小程序,处理HTTP请求并响应。生命周期含初始化、服务和销毁。创建Servlet示例代码展示了`doGet()`方法的覆盖。JSP则侧重视图,动态HTML生成,通过JSP脚本元素、声明和表达式嵌入Java代码。Servlet常作为控制器,JSP处理视图,遵循MVC模式。优化策略涉及缓存、分页和安全措施。这些技术是Java服务器端开发的基础。
|
22天前
|
缓存 安全 Java
Java服务器端技术:Servlet与JSP的集成与扩展
【6月更文挑战第23天】Java Web开发中,Servlet和JSP是构建动态Web应用的基础。Servlet处理逻辑,JSP专注展示。示例展示了Servlet如何通过`request.setAttribute`传递数据给JSP渲染。JSP自定义标签提升页面功能,如创建`WelcomeTag`显示欢迎消息。Servlet过滤器,如`CacheControlFilter`,用于预处理数据或调整响应头。这些集成和扩展技术增强了应用效率、安全性和可维护性,是Java服务器端开发的关键。
|
22天前
|
前端开发 安全 Java
Java服务器端开发实战:利用Servlet和JSP构建动态网站
【6月更文挑战第23天】**Servlet和JSP在Java Web开发中扮演关键角色。Servlet处理业务逻辑,管理会话,JSP则结合HTML生成动态页面。两者协同工作,形成动态网站的核心。通过Servlet的doGet()方法响应请求,JSP利用嵌入式Java代码创建动态内容。实战中,Servlet处理数据后转发给JSP展示,共同构建高效、稳定的网站。虽然新技术涌现,Servlet与JSP仍为Java Web开发的基石,提供灵活且成熟的解决方案。**