JAVA servlet学习

1.代码示例

输出打印

// 实际的逻辑是在这里
PrintWriter out = response.getWriter();
out.println("

" + message + "

"); out.println("

" + username + "

"); out.println("

" + url + "

");

配置文件 web.xml


    
        
            url
            jdc:mysql://localhost:3306/mybatis
        
        
        
            1
        
        
        
            hellServlet
            com.findcn.servlet.HelloServlet
        
        
            hellServlet
            /kkk
        
    

1.设置头部

    // 设置响应内容类型
    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");
    //浏览器刷新 每三秒
    response.setHeader("refresh","3");
    response.setHeader("Content-Disposition","attachment;filenam="+ URLEncoder.encode(fileName,"UTF-8"));
    response.setContentType("image/jpeg");//设置输出为图片
    response.setDateHeader("expires",-1);//浏览器不去缓存
    response.setHeader("Cache-Control","no-Cache");
    response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);//设置请求状态
    

2.使用 ServletContext

    ServletContext context = this.getServletContext();
    String uuname = "1223";
    // 设置用户名
    context.setAttribute("username",uuname);
    // 获取设置用户名
    String username =  (String) context.getAttribute("username");
    // 获取配置
    String url = context.getInitParameter("url");

3.转发

    //请求转发 链接不变
    RequestDispatcher requestDispatcher=context.getRequestDispatcher("/pp");
    requestDispatcher.forward(request,response);
    
    //重定向链接跳转
    response.sendRedirect("/ddd");

4.下载文件

//1.获取下载路径
String realPath = "";
//2.获取文件名
String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
//3.设置文件下载头部
response.setHeader("Content-Disposition","attachment;filenam="+ URLEncoder.encode(fileName,"UTF-8"));
//4.获取下载文件输入流
FileInputStream in = new FileInputStream(realPath);
//5.创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
//6.获取OutputStream对象
ServletOutputStream dout = response.getOutputStream();
//7.写入缓冲区
while((len=in.read(buffer))>0){
    dout.write(buffer,0,len);
}
in.close();
dout.close();

5.验证码生成

    // # 验证码
    BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
    Graphics2D g = (Graphics2D) image.getGraphics();
    g.setColor(Color.WHITE);//设置背景
    g.fillRect(0,0,80,20);
    g.setColor(Color.BLUE);//设置文字颜色
    g.setFont(new Font(null,Font.BOLD,20));
    g.drawString(makeNum(),0,20);//写入随机数
    response.setContentType("image/jpeg");//设置输出为图片
    response.setDateHeader("expires",-1);//浏览器不去缓存
    response.setHeader("Cache-Control","no-Cache");
    ImageIO.write(image,"jpg",response.getOutputStream());//浏览器输出

6.生成随机数

    private String makeNum(){
        Random random = new Random();
        String num = random.nextInt(9999999)+"";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 7-num.length(); i++) {
            sb.append("0");
        }
        num = sb.toString()+num;
        return  num;
    }

7.获取request数据参数

String userName = request.getParameter("username");//获取请求参数
String[] uArr = request.getParameterValues("ids");//获取数组

8.Cookie 操作

//获取cookie
Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
    Cookie cookie = cookies[i];
    cookie.getName();//获取key
    cookie.getValue();//获取value
    System.out.println(cookie.getName());
    cookie.getName().equals("name");//判断 是否等于
}
//写入cookie
Cookie cookie =  new Cookie("cname","到底是啥事");
cookie.setMaxAge(24*60*60);
response.addCookie(cookie);

9.Session

// 时间戳转换
String nowTime = System.currentTimeMillis()+"";//时间戳字符串
Long longTime = Long.getLong(nowTime);//转化为长整型
Date longDate = new Date(longTime);//转化时间日期

SpringBoot

1.简单示例

加载

@Component
// 加载主配置文件
@ConfigurationProperties(prefix = "dog")
// 加载指定配置文件
@PropertySource(value = "classpath:dog.properties")
@Value("阿黄") //赋值变量
// 数据校验
@Validated   @Email()//校验数据
// 加载控制器
@RestController 
// 路由设置
@RequestMapping("/hello")

测试控制器 Dog

@RestController // 加载控制器
public class HelloController {
  @RequestMapping("/hello") //路由设置
  public String hello() {
    return "hhhha";
  }
}

测试用例

@Autowired
private Dog dog; // 自动加载测试类

@Test
void contextLoads() {
    System.out.println(dog);
}

2.配置文件

// properties 格式
application.properties
//多环境配置(spring.profiles.active=test)
application-test.properties  (server.port=8081)
application-dev.properties   (server.port=8082)


//yaml 格式
application.yaml
//多环境配置  --- 分块
    spring:
      profiles:
        active: test
    #debug: true
    ---
    server:
      port: 8081
    spring:
      profiles: test
    dog:
      name: 阿黄
      age: 3
    ---
    server:
      port: 8082
    spring:
      profiles: dev
    
    dog:
      name: 阿黄
      age: 3

3.简单类 示例

package com.lyb.api.pogo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
// 加载主配置文件
@ConfigurationProperties(prefix = "dog")
public class Dog {
  
  private String name;
  
  private Integer age;

  public Dog() {}

  public Dog(String name, Integer age) {
    this.name = name;
    this.age = age;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Integer getAge() {
    return age;
  }

  public void setAge(Integer age) {
    this.age = age;
  }

  @Override
  public String toString() {
    return "Dog{" + "name='" + name + '\'' + ", age=" + age + '}';
  }
}

你可能感兴趣的:(JAVA servlet学习)