java基础(swing+jsp+mybatis配置)
阅读原文时间:2021年09月12日阅读:1

JAVA

GUI编程(swing)

#

组件

描述

1

JFrame

一个普通的窗口(绝大多数 Swing 图形界面程序使用 JFrame 作为顶层容器)

2

JDialog

对话框

常用的中间容器(面板):

#

组件

描述

1

JPanel

一般轻量级面板容器组件

2

JScrollPane

带滚动条的,可以水平和垂直滚动的面板组件

3

JSplitPane

分隔面板

4

JTabbedPane

选项卡面板

5

JLayeredPane

层级面板

特殊的中间容器:

#

组件

描述

1

JMenuBar

菜单栏

2

JToolBar

工具栏

3

JPopupMenu

弹出菜单

4

JInternalFrame

内部窗口

(3)基本组件

基本组件是直接实现人机交互的组件。

常用的简单的基本组件:

#

组件

描述

1

JLabel

标签

2

JButton

按钮

3

JRadioButton

单选按钮

4

JCheckBox

复选框

5

JToggleButton

开关按钮

6

JTextField

文本框

7

JPasswordField

密码框

8

JTextArea

文本区域

9

JComboBox

下拉列表框

10

JList

列表

11

JProgressBar

进度条

12

JSlider

滑块

选取器组件:

#

组件

描述

1

JFileChooser

文件选取器

2

JColorChooser

颜色选取器

其他较为复杂的基本组件:

#

组件

描述

1

JTable

表格

2

JTree

常用的布局管理器:

#

布局管理器

描述

1

FlowLayout

流式布局,按组件加入的顺序,按水平方向排列,排满一行换下一行继续排列。

2

GridLayout

网格布局,把Container按指定行列数分隔出若干网格,每一个网格按顺序放置一个控件。

3

GridBagLayout

网格袋布局,按网格划分Container,每个组件可占用一个或多个网格,可将组件垂直、水平或沿它们的基线对齐。

4

BoxLayout

箱式布局,将Container中的多个组件按 水平 或 垂直 的方式排列。

5

GroupLayout

分组布局,将组件按层次分组(串行 或 并行),分别确定 组件组 在 水平 和 垂直 方向上的位置。

6

CardLayout

卡片布局,将Container中的每个组件看作一张卡片,一次只能显示一张卡片,默认显示第一张卡片。

7

BorderLayout

边界布局,把Container按方位分为 5 个区域(东、西、南、北、中),每个区域放置一个组件。

8

SpringLayout

弹性布局,通过定义组件四条边的坐标位置来实现布局。

9

null

绝对布局,通过设置组件在Container中的坐标位置来放置组件。

    //在标签中添加图片
    label.setIcon(new ImageIcon("xxx.png"));
    //Cursor类表示鼠标的各种形状,可以通过Cursor类的静态属性当作参数指定形状
    label.setCursor(new Cursor(Cursor.HAND_CURSOR));
    //为标签添加tip提示框:即鼠标放在标签上,就会显示提示框
    label.setToolTipText("这是一个Tip");
    //setFont是很多组件都有的
    label.setFont(new Font("微软雅黑", Font.BOLD, 40));
    //设置字体颜色
    setForeground()
    //设置窗体居中
    this.setLocationRelativeTo(null);
    //设置点击窗体x号时退出程序
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    //自动聚焦
    requestFocus()
    //自动换行
    setLineWrap(true)
    //关闭但不退出
    dispose();
    //(30,30) 是你要设置按钮的大小
    button.setPreferredSize(new Dimension(30,30));
    按钮设置为透明,这样就不会挡着后面的背景
    button.setContentAreaFilled(false);
    //去掉按钮边框
    button.setBorderPainted(false);
    //dimension 宽高对象
    new dimension(w,h);

        // 创建 弹出菜单 对象
        JPopupMenu popupMenu = new JPopupMenu();

        // 创建 一级菜单
        JMenuItem copyMenuItem = new JMenuItem("复制");
        JMenuItem pasteMenuItem = new JMenuItem("粘贴");
        JMenu editMenu = new JMenu("编辑");   // 需要 添加 二级子菜单 的 菜单,使用 JMenu
        JMenuItem fileMenu = new JMenuItem("文件");

        // 创建 二级菜单
        JMenuItem findMenuItem = new JMenuItem("查找");
        JMenuItem replaceMenuItem = new JMenuItem("替换");
        // 添加 二级菜单 到 "编辑"一级菜单
        editMenu.add(findMenuItem);
        editMenu.add(replaceMenuItem);

        // 添加 一级菜单 到 弹出菜单
        popupMenu.add(copyMenuItem);
        popupMenu.add(pasteMenuItem);
        popupMenu.addSeparator();       // 添加一条分隔符
        popupMenu.add(editMenu);
        popupMenu.add(fileMenu);

网络编程(socket)

  1. 客户端

    import java.io.*;
    import java.net.Socket;

    public class Client {
    public static void main(String[] args) {
    try {
    Socket socket = new Socket("localhost",8080);
    OutputStream outputStream = socket.getOutputStream();
    String info = "你好啊!";
    //输出!
    outputStream.write(info.getBytes());
    socket.shutdownOutput();
    //接收服务器端的响应
    InputStream inputStream = socket.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
    while ((info = br.readLine())!=null){
    System.out.println("接收到了服务端的响应!" + info);
    }
    //刷新缓冲区
    outputStream.flush();
    outputStream.close();
    inputStream.close();
    socket.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }

  2. 服务端

    import java.io.*;
    import java.net.ServerSocket;
    import java.net.Socket;

    class Serve {
    public static void main(String[] args) {
    try {
    ServerSocket serverSocket = new ServerSocket(8080);
    System.out.println("服务器启动完成…监听启动!");
    //开启监听,等待客户端的访问
    Socket socket = serverSocket.accept();
    // 获取输入流,因为是客户端向服务器端发送了数据
    InputStream inputStream = socket.getInputStream();
    // 创建一个缓冲流
    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
    String info = null;
    while ((info = br.readLine()) != null) {
    System.out.println("这里是服务端 客户端是:" + info);
    }
    //向客户端做出响应
    OutputStream outputStream = socket.getOutputStream();
    info = "这里是服务器端,我们接受到了你的请求信息,正在处理…处理完成!";
    outputStream.write(info.getBytes());
    outputStream.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }

多线程

  1. 实现

  2. 状态:新生->就绪->运行->阻塞->死亡

  3. 线程的操作

  4. 守护线程: setDaemon(true)

  5. Synchronized方法和代码块

  6. RenntrantLock类的锁调用lock() unlock()

注解与反射

注解

内置注解:

@Override 重写

@Deprecated 过时

@SuppressWarnings("all")镇压警告

元注解

@Target({ElementType.METHOD,ElementType.TYPE}) 定义注解用在何处

@Retention(RetentionPolicy.RUNTIME) 注解有效域

@Documented 是否生成DOC

@inhrited 子类继承父注解

注解自定义

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface name{
    String name() default "";//注解的参数 调用@name(name="bob")
}

反射

//获得
Person
Class c=Class.forName("Person");
Class c=Person.getClass();
Class c=p.getClass();

c.getDeclaredField("字段");
c.getDeclaredFields();
c.getDeclaredMethods();
c.getDeclaredMethod("","");
(Persion)c.newInstance()//调用无参构造
 invok()
("x")c.getAnnotation("x").value;
c.getDeclaredField("字段").getAnnotation("").xxx;
field.setAccessible(true);  //  该方法表示取消java语言访问检查 

指令

指令

描述

<%@ page ... %>

定义网页依赖属性,比如脚本语言、error页面、缓存需求等等

<%@ include ... %>

包含其他文件

<%@ taglib ... %>

引入标签库的定义

Page指令
<%@ page attribute="value" %>

属性

描述

buffer

指定out对象使用缓冲区的大小

autoFlush

控制out对象的 缓存区

contentType

指定当前JSP页面的MIME类型和字符编码

errorPage

指定当JSP页面发生异常时需要转向的错误处理页面

isErrorPage

指定当前页面是否可以作为另一个JSP页面的错误处理页面

extends

指定servlet从哪一个类继承

import

导入要使用的Java类

info

定义JSP页面的描述信息

isThreadSafe

指定对JSP页面的访问是否为线程安全

language

定义JSP页面所用的脚本语言,默认是Java

session

指定JSP页面是否使用session

isELIgnored

指定是否执行EL表达式

isScriptingEnabled

确定脚本元素能否被使用

Include指令
<%@ include file="文件相对 url 地址" %>
Taglib指令
<%@ taglib uri="uri" prefix="prefixOfTag" %>

动作元素

<jsp:action_name attribute="value" />

语法

描述

jsp:include

在页面被请求的时候引入一个文件。

jsp:useBean

寻找或者实例化一个JavaBean。

jsp:setProperty

设置JavaBean的属性。

jsp:getProperty

输出某个JavaBean的属性。

jsp:forward

把请求转到一个新的页面。

jsp:plugin

根据浏览器类型为Java插件生成OBJECT或EMBED标记。

jsp:element

定义动态XML元素

jsp:attribute

设置动态定义的XML元素属性。

jsp:body

设置动态定义的XML元素内容。

jsp:text

在JSP页面和文档中使用写入文本的模板

JSP 隐式对象

对象

描述

request

HttpServletRequest 接口的实例

response

HttpServletResponse 接口的实例

out

JspWriter类的实例,用于把结果输出至网页上

session

HttpSession类的实例

application

ServletContext类的实例,与应用上下文有关

config

ServletConfig类的实例

pageContext

PageContext类的实例,提供对JSP页面所有对象以及命名空间的访问

page

类似于Java类中的this关键字

Exception

Exception类的对象,代表发生错误的JSP页面中对应的异常对象

JSP 客户端请求

序号

方法****& 描述

1

Cookie[] getCookies()返回客户端所有的Cookie的数组

2

Enumeration getAttributeNames()返回request对象的所有属性名称的集合

3

Enumeration getHeaderNames()返回所有HTTP头的名称集合

4

Enumeration getParameterNames()返回请求中所有参数的集合

5

HttpSession getSession()返回request对应的session对象,如果没有,则创建一个

6

HttpSession getSession(boolean create)返回request对应的session对象,如果没有并且参数create为true,则返回一个新的session对象

7

Locale getLocale()返回当前页的Locale对象,可以在response中设置

8

Object getAttribute(String name)返回名称为name的属性值,如果不存在则返回null。

9

ServletInputStream getInputStream()返回请求的输入流

10

String getAuthType()返回认证方案的名称,用来保护servlet,比如 "BASIC" 或者 "SSL" 或 null 如果 JSP没设置保护措施

11

String getCharacterEncoding()返回request的字符编码集名称

12

String getContentType()返回request主体的MIME类型,若未知则返回null

13

String getContextPath()返回request URI中指明的上下文路径

14

String getHeader(String name)返回name指定的信息头

15

String getMethod()返回此request中的HTTP方法,比如 GET,,POST,或PUT

16

String getParameter(String name)返回此request中name指定的参数,若不存在则返回null

17

String getPathInfo()返回任何额外的与此request URL相关的路径

18

String getProtocol()返回此request所使用的协议名和版本

19

String getQueryString()返回此 request URL包含的查询字符串

20

String getRemoteAddr()返回客户端的IP地址

21

String getRemoteHost()返回客户端的完整名称

22

String getRemoteUser()返回客户端通过登录认证的用户,若用户未认证则返回null

23

String getRequestURI()返回request的URI

24

String getRequestedSessionId()返回request指定的session ID

25

String getServletPath()返回所请求的servlet路径

26

String[] getParameterValues(String name)返回指定名称的参数的所有值,若不存在则返回null

27

boolean isSecure()返回request是否使用了加密通道,比如HTTPS

28

int getContentLength()返回request主体所包含的字节数,若未知的返回-1

29

int getIntHeader(String name)返回指定名称的request信息头的值

30

int getServerPort()返回服务器端口号

服务端响应

序号

方法 & 描述

1

String encodeRedirectURL(String url)对sendRedirect()方法使用的URL进行编码

2

String encodeURL(String url)将URL编码,回传包含Session ID的URL

3

boolean containsHeader(String name)返回指定的响应头是否存在

4

boolean isCommitted()返回响应是否已经提交到客户端

5

void addCookie(Cookie cookie)添加指定的cookie至响应中

6

void addDateHeader(String name, long date)添加指定名称的响应头和日期值

7

void addHeader(String name, String value)添加指定名称的响应头和值

8

void addIntHeader(String name, int value)添加指定名称的响应头和int值

9

void flushBuffer()将任何缓存中的内容写入客户端

10

void reset()清除任何缓存中的任何数据,包括状态码和各种响应头

11

void resetBuffer()清除基本的缓存数据,不包括响应头和状态码

12

void sendError(int sc)使用指定的状态码向客户端发送一个出错响应,然后清除缓存

13

void sendError(int sc, String msg)使用指定的状态码和消息向客户端发送一个出错响应

14

void sendRedirect(String location)使用指定的URL向客户端发送一个临时的间接响应

15

void setBufferSize(int size)设置响应体的缓存区大小

16

void setCharacterEncoding(String charset)指定响应的编码集(MIME字符集),例如UTF-8

17

void setContentLength(int len)指定HTTP servlets中响应的内容的长度,此方法用来设置 HTTP Content-Length 信息头

18

void setContentType(String type)设置响应的内容的类型,如果响应还未被提交的话

19

void setDateHeader(String name, long date)使用指定名称和值设置响应头的名称和内容

20

void setHeader(String name, String value)使用指定名称和值设置响应头的名称和内容

21

void setIntHeader(String name, int value)指定 int 类型的值到 name 标头

22

void setLocale(Locale loc)设置响应的语言环境,如果响应尚未被提交的话

23

void setStatus(int sc)设置响应的状态码

序号

方法 & 描述

1

public void setDomain(String pattern)设置 cookie 的域名,比如 runoob.com

2

public String getDomain()获取 cookie 的域名,比如 runoob.com

3

public void setMaxAge(int expiry)设置 cookie 有效期,以秒为单位,默认有效期为当前session的存活时间

4

public int getMaxAge()获取 cookie 有效期,以秒为单位,默认为-1 ,表明cookie会活到浏览器关闭为止

5

public String getName()返回 cookie 的名称,名称创建后将不能被修改

6

public void setValue(String newValue)设置 cookie 的值

7

public String getValue()获取cookie的值

8

public void setPath(String uri)设置 cookie 的路径,默认为当前页面目录下的所有 URL,还有此目录下的所有子目录

9

public String getPath()获取 cookie 的路径

10

public void setSecure(boolean flag)指明 cookie 是否要加密传输

11

public void setComment(String purpose)设置注释描述 cookie 的目的。当浏览器将 cookie 展现给用户时,注释将会变得非常有用

12

public String getComment()返回描述 cookie 目的的注释,若没有则返回 null

Cookie cookie = new Cookie("key","value");


cookie.setMaxAge(60*60*24);


response.addCookie(cookie);

session

序号

方法 & 描述

1

public Object getAttribute(String name)返回session对象中与指定名称绑定的对象,如果不存在则返回null

2

public Enumeration getAttributeNames()返回session对象中所有的对象名称

3

public long getCreationTime()返回session对象被创建的时间, 以毫秒为单位,从1970年1月1号凌晨开始算起

4

public String getId()返回session对象的ID

5

public long getLastAccessedTime()返回客户端最后访问的时间,以毫秒为单位,从1970年1月1号凌晨开始算起

6

public int getMaxInactiveInterval()返回最大时间间隔,以秒为单位,servlet 容器将会在这段时间内保持会话打开

7

public void invalidate()将session无效化,解绑任何与该session绑定的对象

8

public boolean isNew()返回是否为一个新的客户端,或者客户端是否拒绝加入session

9

public void removeAttribute(String name)移除session中指定名称的对象

10

public void setAttribute(String name, Object value) 使用指定的名称和值来产生一个对象并绑定到session中

11

public void setMaxInactiveInterval(int interval)用来指定时间,以秒为单位,servlet容器将会在这段时间内保持会话有效

页面重定向

public void response.sendRedirect(String location)

自动刷新

public void setIntHeader(String header, int headerValue)
public void setIntHeader("Refush", 5)

JSTL

JDBC

 package com.botao.dao;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
    private static final String driver;
    private static final String url;
    private static final String username;
    private static final String password;

    static {
        Properties properties = new Properties();
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    public static void closs(Connection connection, Statement statement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Servlet

// 导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// 扩展 HttpServlet 类
public class HelloWorld extends HttpServlet {

  private String message;

  public void init() throws ServletException
  {
      // 执行必需的初始化
      message = "Hello World";
  }

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // 设置响应内容类型
      response.setContentType("text/html");

      // 实际的逻辑是在这里
      PrintWriter out = response.getWriter();
      out.println("<h1>" + message + "</h1>");
  }

  public void destroy()
  {
      // 什么也不做
  }
}


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**

 * @author cbt28
   */
   @WebFilter(filterName = "Test")
   public class GlobalCharSetFilter implements Filter {
   @Override
   public void destroy() {
   }

   @Override
   public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
       req.setCharacterEncoding("UTF-8");
       resp.setContentType("text/html;charset:UTF-8");
       chain.doFilter(req, resp);
   }

   @Override
   public void init(FilterConfig config) throws ServletException {

   }

}

配置文件:

      <filter>
        <filter-name>GlobalCharSetFilter</filter-name>
        <filter-class>GlobalCharSetFilter</filter-class>
        </filter>
        <filter-mapping>
        <filter-name>GlobalCharSetFilter</filter-name>
        <url-pattern>/*</url-pattern>
        </filter-mapping>

    <servlet>
        <servlet-name>HelloWorld</servlet-name>
        <servlet-class>HelloWorld</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/HelloWorld</url-pattern>
    </servlet-mapping>

mybatis

安装

pom.xml部分

 <build>
        <!--设置版本-->
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>14</source>
                    <target>14</target>
                </configuration>
            </plugin>
        </plugins>
      <resources>
          <resource>
          <directory>src/main/resources</directory>
          <includes> <include>**/*.properties</include>
           <include>**/*.xml</include> </includes>
           <filtering>true</filtering>
            </resource>
             <resource>
                 <directory>src/main/java</directory>
                 <includes> <include>**/*.properties</include>
                 <include>**/*.xml</include> </includes>
                  <filtering>true</filtering> </resource>
            </resources>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
     <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!-- 数据库环境 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/apiserve?useSSL=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 映射文件 -->
    <mappers>
        <mapper resource="UserMapper.xml" />
    </mappers>

</configuration>

工具类

package botao.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author cbt28
 */
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            String resources="mybatis.xml";
            InputStream io = Resources.getResourceAsStream(resources);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(io);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

映射

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="botao.dao.UserMapper">
    <select id="findById" resultType="botao.pojo.User" parameterType="int">
        select * from  user where id=#{id}
    </select>
</mapper>

spring

待更新···