JavaWeb(三)servlet

时间:2023-03-08 16:38:35

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

}