会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132885个问题
JAVA 全系列/第三阶段:数据库编程/JDBC技术(旧) 17116楼
JAVA 全系列/第十八阶段:亿级高并发电商项目_架构/编码(旧)/电商:基于SpringSecurity实现后台登录功能 17117楼

只要链接就报错:

请输入:server,<port>或者:<ip>,<port>

192.168.174.1,8888

java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1

at cxh.InetTest.GoodTCP.main(GoodTCP.java:122)



//发送消息线程
class Send1 extends  Thread{
    private Socket socket;
    private Scanner scanner;
    public Send1(Socket socket,Scanner scanner) {
        this.socket = socket;
        this.scanner = scanner;
    }

    public void run(){
        this.sendMsg();
    }
    //发送消息
    public void sendMsg(){

        PrintWriter pw = null;
        try{
            //创建Scanner对象
            scanner = new Scanner(System.in);
            //创建向对方输出消息的流对象
            pw = new PrintWriter(this.socket.getOutputStream());
            //发送消息
            while (true){
                String msg = scanner.nextLine();
                pw.println(msg);
                pw.flush();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(scanner != null){
                scanner.close();
            }
            if(pw != null){
                pw.close();
            }
            if(this.socket != null){
                try {
                    this.socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
/*
 * 接收消息的线程
 * */
class Receive1 extends Thread{

    private Socket socket;
    public Receive1(Socket socket){
        this.socket = socket;
    }

    public void run() {
        this.receiveMsg();
    }
    /*
     * 用于接收对方的消息
     * */
    private void receiveMsg(){
        BufferedReader br = null;
        try{
            //创建用于接收对方发送消息的流对象
            br = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            while (true){
                String msg = br.readLine();
                System.out.println("他说:"+msg);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(this.socket != null){
                    try {
                        this.socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

public class GoodTCP {
    public static void main(String[] args) {
        Scanner scanner = null;
        ServerSocket serverSocket = null;
        Socket socket = null;
        try{
            scanner = new Scanner(System.in);
            System.out.println("请输入:server,<port>或者:<ip>,<port>");
            String str = scanner.nextLine();
            String[] arr = str.split(",");
            if("server".equals(arr[0])){
                //启动服务端
                System.out.println("TCP Server Listen at"+arr[1]+"........");
                serverSocket = new ServerSocket(Integer.parseInt(arr[1]));
                socket = serverSocket.accept();
                System.out.println("链接成功!");

            }else {
                //启动客户端
                socket = new Socket(arr[0],Integer.parseInt(arr[1]));
                System.out.println("链接成功!");
            }
            //启动发送消息的线程
            new Send1(socket,scanner).start();
            //启动接收消息的线程
            new Receive1(socket).start();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

JAVA 全系列/第二阶段:JAVA 基础深化和提高/网络编程(旧) 17118楼

错误:Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
 at fly.FlyGameFrame.paint(FlyGameFrame.java:25)
 at fly.FlyGameFrame.update(FlyGameFrame.java:75)
 at java.desktop/sun.awt.RepaintArea.updateComponent(RepaintArea.java:255)
 at java.desktop/sun.awt.RepaintArea.paint(RepaintArea.java:232)
 at java.desktop/sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:358)
 at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5072)
 at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2321)
 at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2772)
 at java.desktop/java.awt.Component.dispatchEvent(Component.java:4843)
 at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
 at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
 at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
 at java.base/java.security.AccessController.doPrivileged(Native Method)
 at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
 at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
 at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
 at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
 at java.base/java.security.AccessController.doPrivileged(Native Method)
 at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
 at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
 at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
 at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
 at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
 at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
 at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.ja



代码:

package fly;

 
import javax.xml.crypto.Data;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Date;
 
public class FlyGameFrame extends Frame {
 
    Image plane = GameUil.getImage("image/plane.png");
    Image bg = GameUil.getImage("image/bg.jpg");
 
Shell []shells=new Shell[50];
explode explod;
Date start=new Date();
Date end;
long period;
 
 
plant p1=new plant(plane,100,100,10);
 
    @Override
    public void paint(Graphics g) {
        g.drawImage(bg, 00, constant.Game_Width,constant.Game_Height, null);
        g.setColor(Color.green);
        if(p1.live){
            period=(System.currentTimeMillis()-start.getTime())/1000;
            g.drawString("坚持"+period,30,50);
        }else {
            if(end==null){
                end=new Date();
                period=(end.getTime()-start.getTime())/1000;
            }
            g.setColor(Color.red);
            g.setFont(new Font("微软雅黑",Font.BOLD,30));
            g.drawString("最终时间"+period,200,200);
        }
           p1.Drawmyself(g);
        for (int i = 0; i < shells.length; i++) {
            shells[i].Drawmyself(g);
            boolean peng=shells[i].getRect().intersects(p1.getRect());
            if(peng){
 
                p1.live=false;
                if(explod==null){
 
                explod=new explode(p1.x,p1.y);}
                explod.drawmyself(g);
            }
        }
    }
 
    public void launchFrame() {
        this.setTitle("飞机大战");
        setVisible(true);
        setSize(constant.Game_Width, constant.Game_Height);
        setLocation(100100);
        //增加关闭窗口
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        new PaintThread().start();//线程
        this.addKeyListener(new KeyMonitor());//启动键盘
        for (int i = 0; i < 50; i++) {
            shells[i]=new Shell();
 
        }
    }
    //方便直接使用窗口的相关方法
    class PaintThread extends Thread{
        @Override
        public void run() {
            while (true){
                repaint();
                try{
                    Thread.sleep(50);
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    class KeyMonitor extends KeyAdapter{
        @Override
        public void keyPressed(KeyEvent e) {
p1.addDirection(e);
        }
 
        @Override
        public void keyReleased(KeyEvent e) {
            p1.munisDirection(e);
        }
    }
private Image offscreenimage =null;
    public void update(Graphics g){
        if (offscreenimage==null)
            offscreenimage=this.createImage(constant.Game_Width,constant.Game_Height);
        Graphics goff=offscreenimage.getGraphics();
        paint(goff);
        g.drawImage(offscreenimage,0,0,null);
 
    }
    public static void main(String[] args) {
        FlyGameFrame gameFrame = new FlyGameFrame();
        gameFrame.launchFrame();
    }
}
package fly;
 
import java.awt.*;
 
public class GameObject {
    Image img;
    double x,y;
    int spead;
    int width,height;
public GameObject(){
 
}
    public GameObject(Image img, double x, double y, int spead, int width, int height) {
        this.img = img;
        this.x = x;
        this.y = y;
        this.spead = spead;
        this.width = width;
        this.height = height;
    }
 
    public GameObject(Image img, double x, double y, int spead) {
        this.img = img;
        this.x = x;
        this.y = y;
        this.spead = spead;
        this.width=img.getWidth(null);
        this.height=img.getHeight(null);
    }
 
    public void Drawmyself(Graphics g) {
        g.drawImage(img,(int)x, (int)y, width,height, null);
 
    }
    public  Rectangle getRect(){
        return new Rectangle((int)x,(int)y,width,height);
    }
}
package fly;
 
import java.awt.*;
 
public class Shell extends GameObject{
    double degreee;//角度,炮弹沿着固定方向飞行
    public Shell(){
        x=200;
        y=200;
        degreee=Math.random()*Math.PI*2;
        width=10;
        height=10;
        spead=7;
    }
 
    @Override
    public void Drawmyself(Graphics g) {
        Color c=g.getColor();
        g.setColor(Color.blue);
        g.fillOval((int)x,(int)y,width,height);
        g.setColor(c);
        //根据自己的算法去指定移动路径
        x+=spead*Math.cos(degreee);
 
        y+=spead*Math.sin(degreee);
        if(y>constant.Game_Height-this.height||y<40){
            degreee=-degreee;
        }
        if(x<0||x>constant.Game_Width){
            degreee=Math.PI-degreee;
        }
    }
}
package fly;
 
import java.awt.*;
 
public class explode {
    double x,y;
    static Image []imgs=new Image[16];
    int count;
    static {
        for (int i = 0; i < 16; i++) {
            imgs[i]=GameUil.getImage("image/e"+"i+1"+".gif");
 
        }
    }
    public void drawmyself(Graphics g){
        if(count<16){
            g.drawImage(imgs[count],(int)x ,(int)y,null);
            count++;
        }
    }
    public explode(){
 
    }
    public explode(double x,double y){
        this.x=x;
        this.y=y;
    }
}
package fly;
 
import java.awt.*;
import java.awt.event.KeyEvent;
 
public class plant extends GameObject{
    boolean left,right,up,down;
    boolean live=true;
    @Override
    public void Drawmyself(Graphics g) {
       if(live){ super.Drawmyself(g);
        if(left){
            x-=spead;
        }
        if(right){
            x+=spead;
 
        }
        if (up){
            y-=spead;
        }
        if (down){
            y+=spead;
        }}
    }
    public void addDirection(KeyEvent e){
        if(e.getKeyCode()== KeyEvent.VK_LEFT){
            left=true;
        }
        if(e.getKeyCode()==KeyEvent.VK_RIGHT){
            right=true;
        }
        if(e.getKeyCode()==KeyEvent.VK_UP){
            up=true;
        }
        if(e.getKeyCode()==KeyEvent.VK_DOWN){
            down=true;
        }
    }
    public void munisDirection(KeyEvent e){
        if(e.getKeyCode()==KeyEvent.VK_LEFT){
            left=false;
        }
        if(e.getKeyCode()==KeyEvent.VK_RIGHT){
            right=false;
        }
        if(e.getKeyCode()==KeyEvent.VK_UP){
            up=false;
        }
        if(e.getKeyCode()==KeyEvent.VK_DOWN){
            down=false;
        }
    }
 
    public plant(Image img, double x, double y, int spead) {
        super(img, x, y, spead);
    }
}
package fly;
 
public class constant {
    public static final int Game_Width=500;
    public static final int Game_Height=500;
}
package fly;
 
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.net.URL;
 
 
public class GameUil {
    private GameUil(){
 
    }
  public static Image getImage(String path){
      BufferedImage img = null;
      URL u = GameUil.class.getClassLoader().getResource(path);
      try {
          img = ImageIO.read(u);
      catch (IOException e) {
          e.printStackTrace();
      }
      return img;
  }
 
    public static void main(String[] args) {
        Image img=GameUil.getImage("image/plane.png");
        System.out.println(img);
    }
}


JAVA 全系列/第一阶段:JAVA 快速入门/飞机大战小项目训练 17119楼
JAVA 全系列/第三阶段:数据库编程/Oracle 数据库的使用 17120楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/网络编程(旧) 17121楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/容器(旧) 17122楼
JAVA 全系列/第十六阶段:前后端分离技术VUE/Vue框架 17123楼
JAVA 全系列/第八阶段:Linux入门到实战/Maven 17126楼
Python 全系列/第一阶段:Python入门/面向对象 17128楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 17129楼

老师,请教一下,我获取的 servletConfig对象是倒序的,帮忙看看哪里的问题?


Java源码:

package com.gdyj.demo;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet {
    private String message;

   /* public void init() {
        message = "Hello World!";
    }*/

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

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    //    getRequestInfo(request, response);
    //    getRequestAllKeys(request, response);
    //    this.getServletInfomation(request, response);

    //    this.getWebInformation(request, response);
        this.getServletConfigInformation(request,response);

    }


    void getServletConfigInformation(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletConfig servletConfig = this.getServletConfig();
        Enumeration<String> initParamNames =  servletConfig.getInitParameterNames();

     /*   List<String> list = new ArrayList<>();

        while(initParamNames.hasMoreElements()) {
            list.add(initParamNames.nextElement());
        }*/

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.0 Transitional//EN'>");
        out.println("<html><HEAD><TITLE>jacymin</TITLE></HEAD><body>");


    /*    out.println("list: " + list + "<br/>");
        out.println("<br/>");*/

        while(initParamNames.hasMoreElements()) {
            String str = initParamNames.nextElement();
            out.println("key: " + str);
            out.println(", value: " + servletConfig.getInitParameter(str) + "<br/>");
        }

        out.println("<br/>");
        out.println("<br/>");
        out.println("<br/>");
        out.println("end!!!<br/>");

        out.println("</body></html>");

        out.flush();
        out.close();
    }
}



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">

    <context-param>
        <param-name>key1</param-name>
        <param-value>value01</param-value>
    </context-param>

    <context-param>
        <param-name>key2</param-name>
        <param-value>value02</param-value>
    </context-param>

    <servlet>
        <servlet-name>demoServlet</servlet-name>
        <servlet-class>com.gdyj.demo.HelloServlet</servlet-class>
        <init-param>
            <param-name>key001</param-name>
            <param-value>value001</param-value>
        </init-param>
        <init-param>
            <param-name>key002</param-name>
            <param-value>value002</param-value>
        </init-param>
        <init-param>
            <param-name>key003</param-name>
            <param-value>value003</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>demoServlet</servlet-name>
        <url-pattern>/demo.do</url-pattern>
    </servlet-mapping>

</web-app>






搜狗浏览器输出结果:

image.png




换了 Chrome 浏览器,也是一样的:

image.png

JAVA 全系列/第五阶段:JavaWeb开发/Servlet技术详解(旧) 17130楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637