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. es6的一些个人总结

    es6的一些知识点 前言:es6(ECMAscript2015)标准 let.const.var的一些区别 let.const 块级作用域.全局作用域.函数作用域 var 全局作用域.函数作用域 变量 ...

  2. SSH中的Invalid action class configuration that references an unknown class named.......

    最近用SSH框架做项目的时候页面提交数据到后台,遇到了这个问题,百度了一下,网上的解决办法无非两种: 1.检查struts.xml  ,applicationContext.xml的配置是否正确 2. ...

  3. 关于Calendar中设置月份比实际小1的问题

    有如下程序,转化两个字符串数字为date类型,并判断是历史上的星期几,是否同为星期一 代码如下: public static void main(String[] args) throws Parse ...

  4. Kinect用体感来实现UI控件的点击

    用体感来实现UI控件的点击,如点击按钮. 做法:用一个图片表示左手手掌,图片位置追踪左手手掌移动,当手掌位于UI控件的矩形内时,握拳表示点击该控件. using UnityEngine; using ...

  5. vue 实现 tomato timer(蕃茄钟)

    近期在学习[时间管理]方面的课程,其中有一期讲了蕃茄工作法,发现是个好多东西.蕃茄工作法核心思想就是:工作25分钟,休息5分钟.如果您好了解更多可以自行度娘. 在加上本人是一个程序猿,就想用程序的方式 ...

  6. Md5的加密 java实现

    百度百科对MD5的说明是: Message Digest Algorithm MD5(中文名为消息摘要算法第 五版)为计算机安全领域广泛使用的一种散列函数,用以提供消息的完整性保护. MD5即Mess ...

  7. Keras Xception Multi loss 细粒度图像分类

    作者: 梦里茶 如果觉得我的工作对你有帮助,就点个star吧 关于 这是百度举办的一个关于狗的细粒度分类比赛,比赛链接: http://js.baidu.com/ 框架 Keras Tensorflo ...

  8. phantomjs submit click

    phantomjs 一般提交时都会用submit,前提条件就是网页中有form表单: 在网页中无form表单的情况下,用submit()会报错:selenium.common.exceptions.N ...

  9. java 各种去空格的方法

    String str =" dgd fdgd ";   方法一:str = str.trim();//去前后空格 返回:dgd fdgd   方法二:str = str.repla ...

  10. python3.6成功安装scrapy

    本文基于环境:win10(64)+python3.6(64) 第一次直接pip install scrapy,安装出错,错误提示 error: Microsoft Visual C++ 14.0 is ...