盖伦:阿巴阿巴
哈哈哈,学了这么久的JavaEE了现在才真正开始学习servlet
这里是指编写servlet的学习
在编写servlet代码的过程中我们会使用到
我们会使用到各种的类所以要引入相应的包
import javax.servlet.;
import javax.servlet.annotation.;
import java.io.IOException;
其中我们主要会用到HttpServlet,HttpServletRequest,HttpServletResponse,IOException,PrintWriter类
- HttpServlet
我们创建的类是继承这个HttpServlet的,意思就是我们创建的类是 - HttpServletRequest
网页运行时发出一个请求 - HttpServletResponse
获得请求时,我们做出的回应 - IOException
看读写是否正常 - PrintWriter
通过servlet来写一个网页
网页运行默认是发出get请求,所以这里为是编写HttpServlet的doGet方法来实现servlet的功能与作用
下面是我doGet方法的编写
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=UTF-8");//设置回应的类型为html,为避免中文输出时出现乱码所以设置编码格式为UTF-8
PrintWriter out = response.getWriter();//申请编写
//这下面就是对要回应的html进行编写
out.println("");
out.println("" + message + "");
out.println("去往通过jsp编写的页面");
out.println("");
}
我这里进行的是servlet与一个jsp互相进行访问
下面是jsp的编写
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
DOCTYPE html>
<html>
<head>
<title>JSP - Hello Worldtitle>
head>
<body>
<h1><%= "Hello World!" %>
h1>
<br/>
<a href="hello-servlet">去往通过servlet编写的页面a>
body>
html>
总的servelt代码如下(我这里没用编写init()与destroy()方法)
package com.example.aaa;
//引入所需要的包
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
//给servelt进行注解,是我们可以直接通过注解来调用servlet,这样就不需要web.xml中进行配置了
@WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet {
private String message="\"Hello World!\"";//其中的”\”是转义符
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=UTF-8");//设置回应的类型为html,为避免中文输出时出现乱码所以设置编码格式为UTF-8
PrintWriter out = response.getWriter();//申请编写
//这下面就是对要回应的html进行编写
out.println("");
out.println("" + message + "");
out.println("去往通过jsp编写的页面");
out.println("");
}
}
哈哈哈,谢谢你的观看!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)