`

Servlet开发

阅读更多
1. Servlet开发

1) servlet引入

HelloWorldServlet.java

package com.andrew.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("get");
        this.doPost(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("gbk");
        PrintWriter out=response.getWriter();
        out.println("<html>");
        out.println("<head><title>问候</title></head>");
        out.println("Servlet你好!");
        out.println("</html>");
        out.close();
    }
}

web.xml

<servlet>
      <servlet-name>helloWorldServlet</servlet-name>
      <servlet-class>com.andrew.web.HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
      <servlet-name>helloWorldServlet</servlet-name>
      <url-pattern>/helloWorld</url-pattern>
</servlet-mapping>

http://localhost:8080/HeadFirstJspServletChap05/helloWorld
运行结果:
Servlet你好!


2) servlet生命周期

servlet的生命周期,简单的概括这就分为四步:servlet类加载--->实例化--->服务--->销毁。


LifeServlet.java

package com.andrew.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LifeServlet extends HttpServlet {
    public void destroy() {
        System.out.println("LifeServlet destroy!");
    }
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("LifeServlet doGet!");
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("LifeServlet doPost!");
    }
    public void init() throws ServletException {
        System.out.println("LifeServlet init!");
    }
}

web.xml

<servlet>
    <servlet-name>LifeServlet</servlet-name>
    <servlet-class>com.andrew.web.LifeServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>LifeServlet</servlet-name>
    <url-pattern>/LifeServlet</url-pattern>
</servlet-mapping>

http://localhost:8080/HeadFirstJspServletChap05/LifeServlet
控制台:
LifeServlet init!
LifeServlet doGet!


3) 客户端跳转

response.sendRedirect("目标地址");


RedirectServlet.java

package com.andrew.web;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class RedirectServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("requestKey", "request值");
        HttpSession session=request.getSession();
        session.setAttribute("sessionKey", "session值");
        ServletContext application=this.getServletContext();
        application.setAttribute("applicationKey", "application值");
        // 客户端跳转/重定向
        response.sendRedirect("target.jsp");
    }
}

web.xml

<servlet>
    <servlet-name>RedirectServlet</servlet-name>
    <servlet-class>com.andrew.web.RedirectServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>RedirectServlet</servlet-name>
    <url-pattern>/RedirectServlet</url-pattern>
</servlet-mapping>

target.jsp

<h1>目标地址</h1>
request值:<%=request.getAttribute("requestKey") %><br/>
session值:<%=session.getAttribute("sessionKey") %><br/>
application值:<%=application.getAttribute("applicationKey") %><br/>

http://localhost:8080/HeadFirstJspServletChap05/target.jsp
运行结果:
目标地址
request值:null
session值:session值
application值:application值


4) 服务器跳转

RequestDispatcher rd = request.getRequestDispatcher("目标地址");
rd.forward(request, response);


ForwardServlet.java

package com.andrew.web;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ForwardServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("requestKey", "request值");
        HttpSession session=request.getSession();
        session.setAttribute("sessionKey", "session值");
        ServletContext application=this.getServletContext();
        application.setAttribute("applicationKey", "application值");
        // 服务器调转/转发
        RequestDispatcher rd=request.getRequestDispatcher("target.jsp");
        rd.forward(request, response);
    }
}

web.xml

<servlet>
    <servlet-name>ForwardServlet</servlet-name>
    <servlet-class>com.andrew.web.ForwardServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ForwardServlet</servlet-name>
    <url-pattern>/ForwardServlet</url-pattern>
</servlet-mapping>

target.jsp

<h1>目标地址</h1>
request值:<%=request.getAttribute("requestKey") %><br/>
session值:<%=session.getAttribute("sessionKey") %><br/>
application值:<%=application.getAttribute("applicationKey") %><br/>

http://localhost:8080/HeadFirstJspServletChap05/ForwardServlet
运行结果:
目标地址
request值:request值
session值:session值
application值:application值


5) jsp&servlet用户登录功能实现

6) servlet过滤器

7) servlet监听器

创建数据库db_jsp
创建表t_user
CREATE TABLE t_user (
  id int(11) NOT NULL AUTO_INCREMENT,
  userName varchar(20) DEFAULT NULL,
  password varchar(20) DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
insert into t_user(id,userName,password) values(1,'andrew','123456');

User.java

package com.andrew.model;
public class User {
    private int id;
    private String userName;
    private String password;
    public User() {
        super();
    }
    public User(String userName, String password) {
        super();
        this.userName = userName;
        this.password = password;
    }
    // getter and setter
}

DbUtil.java

package com.andrew.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbUtil {
    private String dbUrl = "jdbc:mysql://localhost:3306/db_jsp";
    private String dbUserName = "root";
    private String dbPassword = "root";
    private String jdbcName = "com.mysql.jdbc.Driver";
    public Connection getCon() throws Exception {
        Class.forName(jdbcName);
        Connection con = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
        return con;
    }
    public void closeCon(Connection con) throws Exception {
        if (con != null) {
            con.close();
        }
    }
    public static void main(String[] args) {
        DbUtil dbUtil = new DbUtil();
        try {
            dbUtil.getCon();
            System.out.println("连接成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

UserDao.java

package com.andrew.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.andrew.model.User;
public class UserDao {
    public User login(Connection con,User user) throws Exception{
        User resultUser=null;
        String sql="select * from t_user where userName=? and password=?";
        PreparedStatement pstmt=con.prepareStatement(sql);
        pstmt.setString(1, user.getUserName());
        pstmt.setString(2, user.getPassword());
        ResultSet rs=pstmt.executeQuery();
        if(rs.next()){
            resultUser=new User();
            resultUser.setUserName(rs.getString("userName"));
            resultUser.setPassword(rs.getString("password"));
        }
        return resultUser;
    }
}

LoginServlet.java

package com.andrew.web;
import java.io.IOException;
import java.sql.Connection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.andrew.dao.UserDao;
import com.andrew.model.User;
import com.andrew.util.DbUtil;
public class LoginServlet extends HttpServlet {
    DbUtil dbUtil = new DbUtil();
    UserDao userDao = new UserDao();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName=request.getParameter("userName");
        String password=request.getParameter("password");
        Connection con = null;
        try {
            User user = new User(userName,password);
            con = dbUtil.getCon();
            User currentUser = userDao.login(con, user);
            if (currentUser == null) {
                request.setAttribute("error", "用户名或密码错误");
                request.setAttribute("userName", userName);
                request.setAttribute("password", password);
                request.getRequestDispatcher("login.jsp").forward(request, response);
            } else {
                HttpSession session = request.getSession();
                session.setAttribute("currentUser", currentUser);
                response.sendRedirect("main.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

LogoutServlet.java

package com.andrew.web;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class RedirectServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("requestKey", "request值");
        HttpSession session=request.getSession();
        session.setAttribute("sessionKey", "session值");
        ServletContext application=this.getServletContext();
        application.setAttribute("applicationKey", "application值");
        // 客户端跳转/重定向
        response.sendRedirect("target.jsp");
    }
}

LoginFilter.java

package com.andrew.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class LoginFilter implements Filter {
    public void destroy() {}
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
            FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        Object o = session.getAttribute("currentUser");
        String path = request.getServletPath();
        if (o == null && path.indexOf("login") < 0) {
            request.getRequestDispatcher("login.jsp").forward(servletRequest, servletResponse);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
    public void init(FilterConfig arg0) throws ServletException {}
}

SessionAttributeListener.java

package com.andrew.listener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class SessionAttributeListener implements HttpSessionAttributeListener {
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println("添加的属性名:" + httpSessionBindingEvent.getName() + ",属性值:" + httpSessionBindingEvent.getValue());
    }
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println("删除的属性名:" + httpSessionBindingEvent.getName() + ",属性值:" + httpSessionBindingEvent.getValue());
    }
    public void attributeReplaced(
            HttpSessionBindingEvent httpSessionBindingEvent) {
    }
}

web.xml

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.andrew.web.LoginServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>LogoutServlet</servlet-name>
    <servlet-class>com.andrew.web.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>LogoutServlet</servlet-name>
    <url-pattern>/logout</url-pattern>
</servlet-mapping>
<filter>
    <filter-name>loginFilter</filter-name>
    <filter-class>com.andrew.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>loginFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
    <listener-class>
        com.andrew.listener.SessionAttributeListener
    </listener-class>
</listener>

login.jsp

<form action="login" method="post">
<table>
    <tr><th colspan="2">用户登录</th></tr>
    <tr><td>用户名:</td><td><input type="text" id="userName" name="userName" value="${userName }"/></td></tr>
    <tr><td>密码:</td><td><input type="password" id="password" name="password" value="${password }"/></td></tr>
    <tr><td><input type="submit" value="登录"/></td>
    <td><font color="red">${error }</font></td></tr>
</table>
</form>

main.jsp

主页!当前登录用户:${currentUser.userName } &nbsp;&nbsp;<a href="logout">注销</a>

http://localhost:8080/HeadFirstJspServletChap05/login.jsp
andrew
123456 sbumit
运行结果:
主页!当前登录用户:andrew   注销 
控制台:
添加的属性名:currentUser,属性值:com.andrew.model.User@4bdf7b12
分享到:
评论

相关推荐

    深入学习:Java Servlet开发与实例

    本教程“深入学习:Java Servlet开发与实例”旨在帮助Java从业者深入理解Servlet技术,并通过实例进行实践,提升开发能力。 Servlet是Java平台上的一个标准API,定义了如何在服务器端处理HTTP请求和响应。它为...

    初学 Java Web 开发,请远离各种框架,从 Servlet 开发

    初学者在接触Java Web开发时,常常会被各种框架所吸引,然而,资深的开发者建议,初学者应当先远离框架,从基础的Servlet开发开始学习。这样做的目的是为了更好地理解Web开发的基本原理,为后续深入学习和掌握复杂...

    基于 Servlet 开发的房屋发布系统.zip

    基于 Servlet 开发的房屋发布系统基于 Servlet 开发的房屋发布系统 基于 Servlet 开发的房屋发布系统基于 Servlet 开发的房屋发布系统 基于 Servlet 开发的房屋发布系统基于 Servlet 开发的房屋发布系统 基于 ...

    Servlet开发(tomcat配置)

    Servlet开发和Tomcat配置是Java Web开发中的基础步骤,用于创建和运行动态Web应用程序。以下是对这个主题的详细说明: 1. **Servlet介绍**: Servlet是Java编程语言中的一组接口,它允许开发人员扩展服务器的功能...

    servlet开发通用

    Servlet开发通用技术是Java Web开发中的重要组成部分,主要用于构建动态Web应用程序。在项目开发中,通过创建可重用的Servlet和JDBC通用模块,可以大大提高开发效率,减少代码冗余,提升系统的稳定性和可维护性。...

    servlet开发流程介绍

    ### Java Servlet 开发流程详解 #### 一、概述 Java Servlet 是一种服务器端技术,用于扩展应用程序的功能。Servlet 可以收集来自 HTML 表单的数据、执行数据库操作以及响应客户端请求。本文档将详细介绍如何使用 ...

    Servlet开发手册

    Servlet开发手册Servlet开发手册Servlet开发手册Servlet开发手册

    基于servlet开发的项目

    Servlet是Java Web开发中的核心组件,它是一种Java编程接口,用于扩展服务器的功能,尤其是在Web服务器上处理客户端...通过学习和实践,开发者能够熟练掌握Servlet开发技术,为构建更复杂的Java Web应用打下坚实基础。

    基于javaWeb原生servlet开发的网盘项目源码(期末大作业).zip

    基于javaWeb原生servlet开发的网盘项目源码(期末大作业).zip基于javaWeb原生servlet开发的网盘项目源码(期末大作业).zip基于javaWeb原生servlet开发的网盘项目源码(期末大作业).zip基于javaWeb原生servlet开发的网盘...

    JSP_Servlet开发的bbs论坛

    【JSP_Servlet开发的bbs论坛】 在Web开发领域,JSP(JavaServer Pages)和Servlet是两种常用的Java技术,常被用于构建动态、数据驱动的Web应用程序,如论坛系统。本教程针对的是初学者,旨在帮助他们理解并掌握如何...

    用JSP+bean+servlet开发的四大常用网站--SHOP

    用JSP+bean+servlet开发的四大常用网站(新闻,论坛,电子商城,博客) 可以拿了直接用的,包括数据库的数据都有! 因为东西全所以比较大,只能一个网站一个网站的发 电子商城的图片太占地方空间太小了就没...

    JSP与Servlet开发技术与典型应用教程完整版课件全套ppt教程(最新).ppt

    JSP与Servlet开发技术与典型应用教程完整版课件全套ppt教程(最新).ppt

    01-servlet开发入门.zip

    这个"01-servlet开发入门.zip"文件很可能是为了引导初学者踏入Servlet编程的世界。它包含的01-servlet开发入门.avi视频教程,可能详细讲解了Servlet的基础概念、环境配置以及简单的应用实例。 Servlet是一种Java类...

    基于jsp+servlet开发的电子商务平台

    基于jsp+servlet开发的电子商务购物平台基于jsp+servlet开发的电子商务购物平台基于jsp+servlet开发的电子商务购物平台基于jsp+servlet开发的电子商务购物平台基于jsp+servlet开发的电子商务购物平台基于jsp+servlet...

    Java Servlet开发与实例

    Java Servlet是Java EE平台中的核心组件之一,用于构建动态web应用程序。Servlet是一个Java类,它扩展了服务器的功能,处理来自客户端(通常是web...通过不断的实践和项目经验积累,你将在web开发领域更加游刃有余。

    MyEclipse+Tomcat_+_Servlet开发

    【MyEclipse+Tomcat+Servlet开发】是一个关于使用MyEclipse集成开发环境与Tomcat应用服务器进行Servlet程序开发的教程。在当前的Web项目开发中,Java仍然是主流语言,因此掌握Java项目开发技能至关重要。虽然全面...

    基于Servlet开发的前后端分离图书管理系统源码+数据库+项目说明.zip

    基于Servlet开发的前后端分离图书管理系统源码+数据库+项目说明.zip基于Servlet开发的前后端分离图书管理系统源码+数据库+项目说明.zip基于Servlet开发的前后端分离图书管理系统源码+数据库+项目说明.zip基于Servlet...

Global site tag (gtag.js) - Google Analytics