Servlet

* 什么是Servlet

是运行在web服务器端的Java应用程序,它使用JAVA语言编写,具有Java语言的优点。与Java程序的区别:Servlet对象主要封装了对Http请求的处理,并且他的运行需要Servlet容器的支持。

Servlet实质上就是按Servlet规范编写的Java类,他可以处理Web应用中的相关请求。Servlet是一个标准,由Sun公司定义,具体实现细节由Servlet容器进行实现,如Tomcat,JBoss等。

Servlet和JSP的区别:

1, 角色不同(视图层和控制层)
2, 编程方法不同
3, 是否需要重新编译
4, 运行速度不同

Servlet代码结构

<%@ 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>
<a href="TestServlet2?username=aaaa">测试Servlet链接</a><br>
<form action="TestServlet" method="post">
<input type="submit" value="aaa">
</form>
</body>
</html>

Servlet类作为处理层

package com.hanqi.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("")
public class TestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //get方法接受的请求传到这里
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //post方法接受的请求传到这里
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        String username = config.getInitParameter("username");
        String password = config.getInitParameter("password");

        System.out.println(username);
        System.out.println(password);
    }

/*    @Override
    public void destroy() {
        System.out.println("servlet被销毁");
    }

    @Override
    public void init() throws ServletException {
        System.out.println("初始化servlet");
    }*/

}

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_3_0.xsd"
    id="WebApp_ID" version="3.0">

    <servlet>
        <servlet-name>TestServlet</servlet-name>
        <servlet-class>com.hanqi.servlet.TestServlet</servlet-class>
        <!-- 当这个标签中的数字是0或者不配置这个标签的时候, servlet默认使用的时候加载 -->
        <!-- 数字不是0的时候, 为启动服务器时加载, 数字越小, 优先级越高 -->
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>username</param-name>
            <param-value>admin</param-value>
        </init-param>
        <init-param>
            <param-name>password</param-name>
            <param-value>123456</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>/TestServlet</url-pattern>
    </servlet-mapping>
</web-app>

用Servlet传入信息并打印

<%@ 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>
    <form action="TestServlet2" method="post">
        <input name="username" type="text" /><br>
        <input name="password" type="text" /><br>
        <input name="realname" type="text" /><br>
        <input type="submit" value="提交" />
    </form>
</body>
</html>
package com.hanqi.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestServlet2() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

         //String name = request.getParameter("username");
         //request.getServletContext();
         //request.getSession();
         //request.getpagecontext

         out response.getWriter();
         System.out.println(name);

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String realname = request.getParameter("realname");

        response.getWriter()
                .append("username: " + username + "\npassword: "
                        + password + "\nrealname: " + realname);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

例子:

使用Servlet+JDBC实现登录注册

首先准备页面

注册页面:

<%@ 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>

    <form action="ZhueServlet" method="post">
        用户名:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        确认密码:<input type="password" name="password1"><br>
        真实姓名:<input type="text" name="realname"><br>
        <input type="submit" value="提交"><br>
    </form>
</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>

    <form action="DengluServlet" method="post">
        用户名:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        <input type="submit" value="提交"><br>
    </form>
</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>

    电话本
</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>

<%
    String code=request.getParameter("code");
    if("1".equals(code)){
        out.print("<h1>注册成功</h1><br>");
        out.print("<a href=denglu.jsp >登录</a><br>");
        out.print("<a href=zhuce.jsp >注册</a><br>");
    }
    if("2".equals(code)){
        out.print("<h1>密码不一致</h1>");
        out.print("<a href=denglu.jsp >登录</a><br>");
        out.print("<a href=zhuce.jsp >注册</a><br>");
    }
    if("3".equals(code)){
        out.print("<h1>输入有误</h1>");
        out.print("<a href=denglu.jsp >登录</a><br>");
        out.print("<a href=zhuce.jsp >注册</a><br>");
    }
    if("4".equals(code)){
        out.print("<h1>用户名已存在</h1>");
        out.print("<a href=denglu.jsp >登录</a><br>");
        out.print("<a href=zhuce.jsp >注册</a><br>");
    }
    if("5".equals(code)){
        out.print("<h1>用户名不存在</h1>");
        out.print("<a href=denglu.jsp >登录</a><br>");
        out.print("<a href=zhuce.jsp >注册</a><br>");
    }
    if("6".equals(code)){
        out.print("<h1>登录成功</h1>");
        out.print("<a href=index.jsp >查看电话本</a>");
        out.print("<a href=denglu.jsp >登录</a><br>");
        out.print("<a href=zhuce.jsp >注册</a><br>");
    }
    if(" ".equals(code)){
        out.print("<h1>注册成功</h1>");
        out.print("<a href=denglu.jsp >登录</a><br>");
        out.print("<a href=zhuce.jsp >注册</a><br>");
    }
    if(" ".equals(code)){
        out.print("<h1>注册成功</h1>");
        out.print("<a href=denglu.jsp >登录</a><br>");
        out.print("<a href=zhuce.jsp >注册</a><br>");
    }
%>
</body>
</html>

然后准备工具:

JDBC初始化数据库类:

package com.util;

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

import com.util.JdbcConnectionUtil;

public class JdbcConnectionUtil {
    private static final String USERNAME = "test";
    private static final String PASSWORD = "test";
    private static final String URL = "jdbc:oracle:thin:@localhost:1521:xe";
    private static final String DRIVERCLASSNAME = "oracle.jdbc.OracleDriver";

    public static Connection getConnection(){
        Connection conn=null;
        try {
            Class.forName(DRIVERCLASSNAME);
            conn=DriverManager.getConnection(URL,USERNAME,PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static void destroy(Connection conn){
        if(conn!=null){
            try {
                conn.close();
                conn=null;
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }
    public static void main(String[] args) {
        System.out.println(JdbcConnectionUtil.getConnection());
    }
}

数据库操作类:

package com.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import com.util.JdbcConnectionUtil;
import com.util.User;

public class MethodDal {
    private Connection con;
    private PreparedStatement pste;
    private ResultSet rs;
    //向表中添加数据
    public int insertData(){
        init();
        int i=-1;
        String sql="insert into puser values('c','c')";

        try {
            pste=con.prepareStatement(sql);
            i=pste.executeUpdate();//针对于增删改数据吗,返回受影响的行数
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }
    //向表中添加数据
    public int insertData(User user){
        init();
        int i=-1;
        String sql="insert into puser values(?,?)";
        try {
            pste=con.prepareStatement(sql);
            pste.setString(1,user.getUsername());
            pste.setString(2, user.getPassword());
            i=pste.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }
    //删除记录
    public int deleteDate(int id){

        return 0;
    }
    //查现有姓名
    public String selectName(String name){
        init();
        String sql="select * from puser p where p.pname=?";
        try {
            pste=con.prepareStatement(sql);
            pste.setString(1,name);
            rs = pste.executeQuery();
            while(rs.next()) {
                String pname=rs.getString("pname");
                if(pname!=null){
                    return pname;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "no";
    }
    //根据姓名查密码
    public String selectPwd(String name){
        init();
        String sql="select * from puser p where p.pname=?";
        try {
            pste=con.prepareStatement(sql);
            pste.setString(1,name);
            rs = pste.executeQuery();
            while(rs.next()) {
                String pwd=rs.getString("ppassword");
                return pwd;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "wu";
    }
    public void init(){
        con=JdbcConnectionUtil.getConnection();
    }
}

用户类:

package com.util;

public class User {
    private String username;
    private String password;

    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;
    }
}

然后准备逻辑处理Servlet页面:

注册的Servlet页面:

package com.servlet;

import java.io.IOException;
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 com.util.MethodDal;
import com.util.User;

/**
 * Servlet implementation class ZhueServlet
 */
@WebServlet("/ZhueServlet")
public class ZhueServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ZhueServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");

        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String password1=request.getParameter("password1");
        String realname=request.getParameter("realname");
        //调用方法判断传入的参数有没有空,都不为空才可以执行下去
        if(checkParam(username,password,password1)){
            if(password.equals(password1)){
                MethodDal m=new MethodDal();
                if(m.selectName(username).equals("no")){//调用方法根据用户名查询,如果返回no说明数据库没有此用户名,可以注册
                    User user=new User();//实例化用户类并添加信息
                    user.setUsername(username);
                    user.setPassword(password);
                    m.insertData(user);//将实例化的用户传到添加用户的方法
                    response.sendRedirect("message.jsp?code=1");
                }else{
                    response.sendRedirect("message.jsp?code=4");
                }
            }else{
                response.sendRedirect("message.jsp?code=2");
            }
        }else{
            response.sendRedirect("message.jsp?code=3");
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
    //判断传入的参数有没有空的方法,只要有空的就返回false
    public boolean checkParam(String... args){//这样传参数代表参数个数不确定,传几个都可以
        for(String s : args){
            if("".equals(s)||s==null){
                return false;
            }
        }
        return true;
    }

}

登陆的Servlet页面:

package com.servlet;

import java.io.IOException;
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 com.util.MethodDal;
import com.util.User;

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

    /**
     * @see HttpServlet#HttpServlet()
     */
    public DengluServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");

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

        MethodDal m=new MethodDal();
        //调用方法判断传入的参数有没有空,都不为空才可以执行下去
        if(checkParam(username,password)){
            if(!(m.selectName(username).equals("no"))){//调用方法根据用户名查询,如果返回不为no说明数据库有此用户
                if((m.selectPwd(username)).equals(password)){//根据用户名查询密码,并对比输入的密码和数据库的密码

                    response.sendRedirect("message.jsp?code=6");
                }else{
                    response.sendRedirect("message.jsp?code=4");
                }
            }else{
                response.sendRedirect("message.jsp?code=5");
            }
        }else{
            response.sendRedirect("message.jsp?code=3");
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
    //判断传入的参数有没有空的方法,只要有空的就返回false
    public boolean checkParam(String... args){//这样传参数代表参数个数不确定,传几个都可以
        for(String s : args){
            if("".equals(s)||s==null){
                return false;
            }
        }
        return true;
    }

}

JavaWeb(三)servlet的更多相关文章

  1. JavaWeb学习——Servlet相关的接口和类

    JavaWeb学习——Servlet相关的接口和类 摘要:本文主要学习了Servlet相关的接口和类. Servlet的接口和类 三种方式 实现Servlet有三种方式: 实现javax.servle ...

  2. JavaWeb之Servlet入门(二)

    1. 准备 在JavaWeb之Servlet入门(一)中,我们完成了第一个Servlet程序,完成了从URL到后台控制器的中转过程,接下来我们延续JavaWeb之Servlet入门(一)学习下如何传参 ...

  3. JavaWeb学习笔记三 Servlet

    Servlet 是运行在服务端的Java小程序,是sun公司提供一套规范(接口),用来处理客户端请求.响应给浏览器的动态资源.但servlet的实质就是java代码,通过java的API,动态的向客户 ...

  4. javaweb之servlet 全解

    ①Servlet概述 ⑴什么是Servlet Servlet是JavaWeb的三大组件之一,它属于动态资源.Servlet的作用是处理请求, 服务器会把接收到的请求交给Servlet来处理,在Serv ...

  5. JavaWeb学习—Servlet

    1.什么是Servlet Servlet是一个继承HttpServlet类的Java类 Servlet必须部署在web服务器端,用来处理客户端的请求 2.Servlet运行过程 Web Client ...

  6. JavaWeb之Servlet总结

    今天上班居然迟到了,昨天失眠了,看完吐槽大会实在不知道做些什么,刚好朋友给我发了两个JavaWeb的练习项目,自己就又研究了下,三四点才睡,可能周日白天睡的太多了,早上醒来已经九点多了,立马刷牙洗脸头 ...

  7. javaWEB之Servlet

    Servlet 1. 什么是Servlet  * Servlet是JavaWeb三大组件之一(Servlet.Filter.Listener)  * Servlet是用来处理客户端请求的动态资源  * ...

  8. JavaWeb(一)-Servlet知识

    一.Servlet简介 Servlet是sun公司提供一门用于开发动态web资源的技术. sun公司在其API中提供了一个servlet接口,用户若想开发一个动态web资源(即开发一个java程序向浏 ...

  9. JavaWeb基础—Servlet

    一.Servlet是什么 是服务器上运行的Java小应用程序,并被称为JavaWeb三大组件之一 通常我们把实现了Servlet的类,称之为Servlet Servlet作用主要是 1.接收请求数据 ...

  10. javaweb(六)——Servlet开发(二)

    一.ServletConfig讲解 1.1.配置Servlet初始化参数 在Servlet的配置文件web.xml中,可以使用一个或多个<init-param>标签为servlet配置一些 ...

随机推荐

  1. JavaScript 的 作用域

    在看了几本书之后的一些理解和自己的想法.   作用域,变量的作用范围   在ES6之前 变量的声明   只有var可以声明变量属于某个作用域,并且,也只有全局作用域和函数作用域. (没有var声明的变 ...

  2. spring boot 打war包部署,打jar包

    官方文档:http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-create-a-deployable- ...

  3. IDEA的热部署插件jrebel6.4.3版离线安装版配置与破解

    JRebel 介绍 IDEA上原生是不支持热部署的,一般更新了 Java 文件后要手动重启 Tomcat 服务器,才能生效,浪费不少生命啊.目前对于idea热部署最好的解决方案就是安装JRebel插件 ...

  4. 20170713_js闭包/匿名函数/作用域

    js:闭包 var getNum; function getCounter() { var n = 1; var inner = function () {return n++; } console. ...

  5. 支付宝LR集群压测报告

    支付宝压力测试报告 时间:2016-03-23                                             测试人员:XXX 目录 支付宝压力测试报告 1 目录 1 一   ...

  6. Python学习记录----类型匹配(转)

    import types aaa = 0 print type(aaa) if type(aaa) is types.IntType: print "the type of aaa is i ...

  7. [IB]PeopleSoft异步详细信息中状态“已完成”但订阅合同状态“新建”问题

    最近遇到一个IB异步程序状态不一致问题,异步详细信息中上面的状态是“DONE”但是订阅合同中还是“新建”状态.在域状态中清除域状态也不管用. 重启app server也不好使.最后执行了appmsgp ...

  8. Java curator操作zookeeper获取kafka

    Java curator操作zookeeper获取kafka Curator是Netflix公司开源的一个Zookeeper客户端,与Zookeeper提供的原生客户端相比,Curator的抽象层次更 ...

  9. Github上比较流行的PHP扩展库项目

    这里列出比较常用的PHP开源扩展库项目: swoole, C扩展实现的PHP异步并行网络通信框架,可以重新定义PHP.过去PHP只能做Web项目,现在有了Swoole.任意服务器端程序都可以用PHP来 ...

  10. Linux服务器中安装Oracle

    笔者手动安装成功 一,oracle安装前的准备与配置 1,修改stsctl.conf文件 Linux是为小文件设计的,Oracle数据库安装需要占用较多资源,要把各项参数调大. 使用vi编辑/etc/ ...