Servlet具体开发
包括Servlet语义等
目录
一、ServletContext
Web容器在启动的时候,它会为每个web程序创建一个对应的ServletContext对象,它代表了当前的web应用。
功能:
1.共享不同servlet的数据。这样在一个服务器中放入数据后在另一个服务器中也可以使用。
ServletContext的初始化和调用、context.setAttribute和context.getAttribute:
public class helloservlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//this.getServletConfig(); Servlet配置
ServletContext context = this.getServletContext();//初始化一个Servlet上下文
String username="应";//数据
context.setAttribute("username",username);
//将一个数据保存在了ServletContext中,名字为username(前者),值为username“后者”
System.out.println("hello");
}
}
public class getServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();//获取servlet上下文
String username=(String)context.getAttribute("username");
//取到context中的名为username(后者)的数据,帮将它赋值给username(前者)。getAttribute()方法返回的是object对象,可以强转成String
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter().print("名字"+username);
}
}
servlet注册略
测试方法:先启动helloservlet,再启动getServlet
测试结果:后台显示“hello”,getServlet显示“应”
2.获取初始化参数
context.getInitParameter(“url”):
web.xml:
<!--配置一些web应用的初始化参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
public class servletdemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");//获取初始化参数
resp.getWriter().print(url);
}
测试结果:servletdemo03显示“jdbc:mysql://localhost:3306/mybatis”
3.请求转发(在一个servlet上运行另一个servlet)
context.getRequestDispatcher(“”).forward(req,resp):
在servletdemo03的基础上(/gp为servletdemo03的url地址),
public class servletdemo04 extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");//转发的请求路径
requestDispatcher.forward(req,resp);//调用forward实现请求转发
//或者直接:context.getRequestDispatcher("/gp").forward(req,resp);
System.out.println("进入了s4");
}
测试结果:servletdemo04显示“jdbc:mysql://localhost:3306/mybatis”
4.读取资源文件
properties文件、context.getServletContext().getResourceAsStream()、properties.load()和properties.getProperty()
- 在java目录下或者在resources目录下新建properties文件
- 可以编写properties文件内容为:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is= this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
//获取context中的资源流
Properties prop= new Properties();//初始化一个properties对象
prop.load(is);//将获取的资源流加载到该properties对象中
String user= prop.getProperty("username");
String pwd= prop.getProperty("password");//获取properties中的名为“username”和“password”的资源内容
resp.getWriter().print(user+":"+pwd);
}
如果要获取的properties文件在resources目录下,则无需修改pom文件(若添加了下面的resources内容,则无法在classpath中导出该文件);
如果要获取的properties文件在java目录下,则需在pom中的build中配置resources,来防止我们资源导出失败的问题,配置内容见作者的《学习JavaWeb》中“二、Maven 7.分析pom文件”的第二块代码。此时获取资源流时寻找properties导出文件的路径变为了
“/WEB-INF/classes/com/y/db.properties”,这里/com/y指代的是target中properties所在的packet。换句话说,两个所在位置不同的properties都被打包到了同一个路径下,即target中的classes,我们俗称这个路径为classpath。
二、HttpServletResponse(extends ServletResponse)
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse。如果要获取客户端请求过来的参数,找HttpServletRequest;如果要给客户端响应一些信息,找HttpServletResponse
1.分类
负责向浏览器发送数据的方法:
ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;
负责向浏览器发送响应头的方法
void setCharacterEncoding(String var1);
void setContentLength(int var1);
void setContentLengthLong(long var1);
void setContentType(String var1);
void setDateHeader(String var1, long var2);
void addDateHeader(String var1, long var2);
void setHeader(String var1, String var2);
void addHeader(String var1, String var2);
void setIntHeader(String var1, int var2);
void addIntHeader(String var1, int var2);
响应状态码
int SC_CONTINUE = 100;
int SC_SWITCHING_PROTOCOLS = 101;
int SC_OK = 200;
int SC_CREATED = 201;
int SC_ACCEPTED = 202;
int SC_NON_AUTHORITATIVE_INFORMATION = 203;
int SC_NO_CONTENT = 204;
int SC_RESET_CONTENT = 205;
int SC_PARTIAL_CONTENT = 206;
int SC_MULTIPLE_CHOICES = 300;
int SC_MOVED_PERMANENTLY = 301;
int SC_MOVED_TEMPORARILY = 302;
int SC_FOUND = 302;
int SC_SEE_OTHER = 303;
int SC_NOT_MODIFIED = 304;
int SC_USE_PROXY = 305;
int SC_TEMPORARY_REDIRECT = 307;
int SC_BAD_REQUEST = 400;
int SC_UNAUTHORIZED = 401;
int SC_PAYMENT_REQUIRED = 402;
int SC_FORBIDDEN = 403;
int SC_NOT_FOUND = 404;
int SC_METHOD_NOT_ALLOWED = 405;
int SC_NOT_ACCEPTABLE = 406;
int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
int SC_REQUEST_TIMEOUT = 408;
int SC_CONFLICT = 409;
int SC_GONE = 410;
int SC_LENGTH_REQUIRED = 411;
int SC_PRECONDITION_FAILED = 412;
int SC_REQUEST_ENTITY_TOO_LARGE = 413;
int SC_REQUEST_URI_TOO_LONG = 414;
int SC_UNSUPPORTED_MEDIA_TYPE = 415;
int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
int SC_EXPECTATION_FAILED = 417;
int SC_INTERNAL_SERVER_ERROR = 500;
int SC_NOT_IMPLEMENTED = 501;
int SC_BAD_GATEWAY = 502;
int SC_SERVICE_UNAVAILABLE = 503;
int SC_GATEWAY_TIMEOUT = 504;
int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
2.常见应用
- 向浏览器输出消息(前述)
- 下载文件
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 下载文件
// 1.获取文件路径(确保文件在resources中,可以直接复制粘贴进去),这里的路径最好给绝对路径,指代明确
String realPath ="F:\\IJ IDEA\\Projects\\javaweb04-servlet\\response\\target\\classes\\1.jpg";
System.out.println("下载文件的路径:"+realPath);
// 2.获取下载的文件名
String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
// 3.设置消息头,让浏览器能支持该文件的下载(Content-Disposition)
resp.setHeader("Content-Disposition","attachment;filename="+filename);
//若文件名有中文,则需加上编码方式
// resp.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
// 4.获取文件的输入流
FileInputStream in = new FileInputStream(realPath);
// 5.创建缓冲区
int len=0;
byte[] buffer = new byte[1024];
// 6.获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
// 7.将FileOutputStream流写入到buffer缓冲区
while ((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
// 8.使用OutputStream将缓冲区中的数据输出到客户端
}
- 验证码功能
· 前端实现
· 后端实现,需要用到java的图片类
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//让浏览器3秒自动刷新一次
resp.setHeader("refresh","3");
//1.在内存中创建一个图片
BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
//2.画图
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(makenumber(),0,20);
//3.告诉浏览器,这个请求以图片的方式打开
resp.setContentType("image/jpg");
//4.网站存在缓存,不让浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
//5.把图片写给浏览器
ImageIO.write(image,"jpg", resp.getOutputStream());
}
- 实现重定向
客户端A请求一个web资源B后,B会通知A去访问另一个web资源C,该过程叫重定向。
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("/resp/img");//重定向(/img为上一个的url-pattern)
/*相当于:
*resp.setHeader("Location","/resp/img");
*resp.setStatus(302);
*/
}
重定向和转发的区别:
相同点:页面都会实现跳转
不同点:
- 请求转发的url不会发生变化,响应状态码为302
- 重定向的url会发生变化,响应状态码为307
三、HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest方法获得客户端的所有信息。
1、获取前端传递的参数,并请求转发
以登录系统为例:
第一步,写登陆界面
删除重建index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<h1>登录</h1>
<div style="text-align: center">
<%--这里表单的意思是:以post方法提交表单,提交到我们的login请求--%>
<form action="${pageContext.request.contextPath}/login" method="post"><%--创建一个表单,并:获取服务器的请求路径为“/login”;调用方法为“post”--%>
用户名:<input type="text" name="username"><br><%--创建一个text文本框,变量名为username;<br>是换行操作--%>
密码:<input type="password" name="password"><br><%--创建一个password密码框,变量名为password--%>
爱好:
<input type="checkbox" name="hobbies" value="女人">女人<%--创建checkbox多选框,以该选项框为例,变量名为hobby,其值为女人(前一个),在前端显示为“女人”(后一个)--%>
<input type="checkbox" name="hobbies" value="足球">足球
<input type="checkbox" name="hobbies" value="音乐">音乐
<br>
<input type="submit"><%--创建一个submit提交框--%>
</form>
</div>
</body>
</html>
第二步,写登陆后的界面:
在webapp下新建success.jsp:
<body>
<h1>登录成功</h1>
</body>
第三步,获取前端传递的参数,并打印到后台,然后请求转发success.jsp:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String username = req.getParameter("username");//获取名为"username"的参数
String password = req.getParameter("password");
String[] hobbies = req.getParameterValues("hobbies");
System.out.println("==================");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbies));//打印数组
System.out.println("==================");
/*通过请求转发*/
req.getRequestDispatcher("/success.jsp").forward(req,resp);//"/success.jsp"中的/就代表当前的web应用,因此也可以写为:
//req.getRequestDispatcher(req.getContextPath()+"success.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}