首页 > 编程语言 >java项目实践-tomcat实现用户登录-day17

java项目实践-tomcat实现用户登录-day17

时间:2023-10-15 22:45:27浏览次数:36  
标签:java tomcat request System day17 println import servlet javax

目录

1. 安装

tomcat.apache.org
下载链接:https://tomcat.apache.org/download-80.cgi

2. 初识tomcat

bin
start.bat -->localhost:8080 (JDK依赖)
shutdowm.bat
conf
server.xml --8080默认值
lib 目录jar包
jsp.jar 重要
serverlet.jar 重要
webapps目录
web项目 打成war包

运行startup.bat 并在浏览器中访问 localhost:8080

说明已经能正常使用

2. 创建tomcat项目

new project
注意 javaEE 需要勾选 web application

new Class MyServlet

导包

继承HttpServlet 并重写方法

package com.msb;

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

/**
 * @Auther: jack.chen
 * @Date: 2023/10/15 - 10 - 15 - 11:34
 * @Description: com.msb
 * @version: 1.0
 */
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("my first web project");
        System.out.println("my first web project");
    }
}

web.xml定义

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">


    <servlet>
        <servlet-name>mysevlet</servlet-name>
        <servlet-class>com.msb.MyServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>mysevlet</servlet-name>
        <url-pattern>/first</url-pattern>
    </servlet-mapping>
</web-app>

3. 启动之前

-->

启动webserver

package com.msb;

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 java.io.IOException;

/**
 * @Auther: jack.chen
 * @Date: 2023/10/15 - 10 - 15 - 15:03
 * @Description: ${PACKAGE_NAME}
 * @version: 1.0
 */
@WebServlet(name = "MyServlet2")
public class MyServlet2 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("second hehe !");
    }
}

web.xml文件配置 增加

    <servlet>
        <servlet-name>mysevlet2</servlet-name>
        <servlet-class>com.msb.MyServlet2</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>mysevlet2</servlet-name>
        <url-pattern>/second</url-pattern>
    </servlet-mapping>

再访问
http://localhost:8080/firstweb/second

创建servles实例
调用init()方法
调用service方法
输出相应
调用destory方法

web.xml其他配置
load-on-startup 1 启动tomcat的时候就会创建serverlet对象 1表示优先级

3. java jsp

增加method.jsp并访问

<%--
  Created by IntelliJ IDEA.
  User: chenw
  Date: 2023/10/15
  Time: 15:28
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/firstweb/method", method="post">
        用户名:<input   type="text"  name="username"   value=""   /><br/>
        密码:<input     type="text"   name="password"  value="" /><br/>
        <input type="submit", value="登录">

    </form>

</body>
</html>

http://localhost:8080/firstweb/method.jsp

package com.msb;

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

/**
 * @Auther: jack.chen
 * @Date: 2023/10/15 - 10 - 15 - 15:22
 * @Description: ${PACKAGE_NAME}
 * @version: 1.0
 */
public class MethodServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("/method post");
        response.getWriter().write("hello");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("/method get");

    }
}

4. Request Response对象的其他属性

package com.msb;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.midi.Soundbank;
import java.io.IOException;
import java.net.URI;
import java.util.Enumeration;

/**
 * @Auther: jack.chen
 * @Date: 2023/10/15 - 10 - 15 - 15:56
 * @Description: ${PACKAGE_NAME}
 * @version: 1.0
 */
public class TestRequestServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("test request post 请求");
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        System.out.println("name:"+name);
        System.out.println("pwd:"+pwd);

        String remoteAddr = request.getRemoteAddr();
        System.out.println("remoteAddr:"+remoteAddr);

        String remoteHost = request.getRemoteHost();
        System.out.println("remoteHost:"+remoteHost);

        int remotePort = request.getRemotePort();
        System.out.println("remotePort:"+remotePort);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("test request get 请求");

        String method = request.getMethod();
        System.out.println("method: "+method);

        String requestURI = request.getRequestURI();
        System.out.println("uri:" + requestURI);

        StringBuffer requestURL = request.getRequestURL();
        System.out.println("url:"+requestURL);

        //协议
        String scheme = request.getScheme();
        System.out.println("schema:"+scheme);


        // 请求头 User-Agent的value
        String ua = request.getHeader("Yser-Agent");
        System.out.println("ua:"+ua);

        Enumeration<String> headerNames = request.getHeaderNames();// 所有header key
        while (headerNames.hasMoreElements()){
            String s = headerNames.nextElement();
            String header = request.getHeader(s);
            System.out.println("key:"+s);
            System.out.println("header:"+ header);
        }

        response.getWriter().write("hello");

    }
}


5. 用户登录小功能

用户登录流程:

  1. 用户GET请求返回原生的页面
  2. 客户端 填写相应的数据 发起POST请求
  3. 服务端逻辑校验处理
  4. 服务端返回处理的结果

导包:
setting--project struture--module--jar
添加 tomcat安装位置lib下面的servlet_api.jar

package com.msb;

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

/**
 * @Auther: jack.chen
 * @Date: 2023/10/15 - 10 - 15 - 19:52
 * @Description: ${PACKAGE_NAME}
 * @version: 1.0
 */
public class PageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Post method");
        response.getWriter().write("welcome !");

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("get method !!!!");
        response.setContentType("text/html");

        PrintWriter writer = response.getWriter();
        writer.write("<html>");
        writer.write("<header>");
        writer.write("</header>");
        writer.write("<body>");
        writer.write("<form action='/user/login', method='post'>");

        writer.write("username:<input type='login' name='name' value=''></br>");
        writer.write("password:<input type='login' name='pwd' value=''></br>");
        writer.write("<input type='submit'  value='login'>");

        writer.write("</form>");
        writer.write("</body>");
        writer.write("</html>");
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>PageServlet</servlet-name>
        <servlet-class>com.msb.PageServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>PageServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

</web-app>


mysql for java驱动下载地址:
https://downloads.mysql.com/archives/c-j/

数据库:

项目结构:

LoginServlet

package com.msb.control;

import com.msb.entity.User;
import com.msb.service.UserService;
import com.msb.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @Auther: jack.chen
 * @Date: 2023/10/15 - 10 - 15 - 20:29
 * @Description: ${PACKAGE_NAME}
 * @version: 1.0
 */
public class LoginServlet extends HttpServlet {

    UserService userService = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("post method !");
        String name = request.getParameter("name");
        String pwd= request.getParameter("pwd");

        User user = new User(name, pwd);
        User u = null;
        try {
            u = userService.checkUser(user);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        if (u!=null){
            response.getWriter().write("welcome:" + u.getName());
        }else{
            System.out.println(403);
            response.setStatus(403, "not permitted");
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

UserDaoImpl

package com.msb.dao.impl;

import com.msb.dao.UserDao;
import com.msb.entity.User;

import java.sql.*;
import java.util.Map;

/**
 * @Auther: jack.chen
 * @Date: 2023/10/15 - 10 - 15 - 20:28
 * @Description: com.msb.dao.impl
 * @version: 1.0
 */
public class UserDaoImpl implements UserDao {
    @Override
    public User checkUser(User user) throws ClassNotFoundException, SQLException {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        User u = null;

//        System.out.println("user:" + user.toString());

        // 加载包
        Class.forName("com.mysql.cj.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jackdb", "root", "");

        pstmt = conn.prepareStatement("select * from `user` where username = ? and pwd =?");

        pstmt.setString(1, user.getName());
        pstmt.setString(2, user.getPwd());

        rs = pstmt.executeQuery();
        while (rs.next()){
            u = new User(rs.getInt("id"), rs.getString("username"), rs.getString("pwd"));
        }
        return u;
    }

}

调用路径:
control --> service --> dao

终于搞定:

经验:

  1. mysql java驱动
  2. navicate 的使用
  3. mysql的使用

标签:java,tomcat,request,System,day17,println,import,servlet,javax
From: https://www.cnblogs.com/cavalier-chen/p/17766377.html

相关文章

  • Java拾贝第二天——面向对象
    Java拾贝不建议作为0基础学习,都是本人想到什么写什么特性封装性,继承性,多态性。类的组成publicclass类名{//数据类型属性名;intage;//成员变量public返回值类型方法名(传参){ Stringname;//局部变量 //方法体}}其中定义在类中的属性名也就是变......
  • Java继承的利弊和使用原则
    继承是一种提高程序代码的可重用性、以及提高系统的可扩展性的有效手段。但是,如果继承树非常复杂、或者随便扩展本来不是专门为继承而设计的类,反而会削弱系统的可扩展性和可维护性。1.继承树的层次不可太多继承树(不考虑最顶层的Object类)的层次应该尽量保持在两到三层。如果继承树......
  • JAVA - 记录
    有时,数据就是数据,而面向对象程序设计提供的数据隐藏有些碍事,考虑一个类,这个类描述平面上的一个点,有下x和y坐标packagecom.demo;publicclassPonint{privatefinaldoublex;privatefinaldoubley;publicPonint(doublex,doubley){this.x=x......
  • 单例模式--Java实现
    画类图具体代码实现//StudentNo.javapackageorg.example.design005;publicclassStudentNo{privatestaticStudentNoinstance=null;privateStudentNo(){}publicstaticStudentNogetInstance(){if(instance==null){System.ou......
  • Java 数组与List转换
    示例@Testvoidstr2arr(){Stringids="1,2,3,4,5,6";//字符串-->String数组String[]arrayStr=ids.split(",");System.out.println(arrayStr);}@Testvoidlist2Str(){List<......
  • java.lang.TypeNotPresentException: Type javax.servlet.http.HttpServletRequest no
    完整的报错信息java.lang.TypeNotPresentException:Typejavax.servlet.http.HttpServletRequestnotpresent atjava.base/sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:117)~[na:na] atjava.base/sun.reflect.generics......
  • 用Java语言简单实现MQ消息队列服务
    大致的结构:一个消息队列大致的结构:消息处理中心Brokerpackagecom.tntxia;importjava.util.concurrent.ArrayBlockingQueue;/***消息处理中心*/publicclassBroker{//队列存储消息的最大数量privatefinalstaticintMAX_SIZE=3;//保存消息数据......
  • java线程
    Java虚拟机(JVM,是运行所有Java程序的抽象计算机,是Java语言的运行环境)允许应用程序并发地运行多个线程。在Java语言中,多线程的实现一般有以下三种方法:1、实现Runnable接口,并实现该接口的run()方法。①自定义类并实现Runnable接口,实现run()方法。②创建Thread对象,用实现Ru......
  • 《Head First JavaScript程序设计》高清高质量 原版电子书PDF+源码
    下载:https://pan.quark.cn/s/9b368a216582......
  • 原型模式--Java实现
    画类图浅克隆:深克隆:具体代码实现浅克隆具体代码://Vector.javapackageorg.example.design004;importjava.lang.reflect.Array;importjava.util.Arrays;publicclassVectorimplementsCloneable{publicint[]getArray(){returnarray;}......