java web-01-servlet
2021/10/11 20:14:39
本文主要是介绍java web-01-servlet,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1、helloservlet
在浏览器中输出 hello servlet!
1.1、创建一个maven项目,连接Tomcat
public class HelloServlet extends HttpServlet { //Art+Ins //由于get或者post只是请求实现的不同的方式,可以相互调用,业务逻辑都一样 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter();//响应流 writer.println("hello servlet!!!"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
1.2、在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"> <!--注册servlet--> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.feng.servlet.HelloServlet</servlet-class> </servlet> <!--mapping:映射--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>
为什么需要映射:我们写的是java程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要在web服务器中注册我们写的Servlet,还需给他一个浏览器能够访问的路径
如果项目没有web,直接项目右键添加即可!
2、ServletContext
web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用;
2.1、共享数据
public class SetServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //this.getInitParameter();初始化参数 //this.getServletConfig();Servlet配置 //this.getServletContext();Servlet上下文 ServletContext context = this.getServletContext(); String name = "bitwind"; //将一个数据保存在了ServletContext中 context.setAttribute("username",name);//setAttribute : 设置属性 } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
public class GetServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取ServletContext中的值 ServletContext context = this.getServletContext(); String name = (String) context.getAttribute("username"); resp.getWriter().println("name = "+name); System.out.println(name); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
添加映射
启动Tomcat,访问!
注意:要先访问GetServlet类,否则name=null,要先存进ServletContext,才有得拿!
2.2、获取初始化参数
public class GetInitParameter extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); //this.getInitParameter();初始化参数 //this.getServletConfig();Servlet配置 //this.getServletContext();Servlet上下文 ServletContext context = this.getServletContext(); String name = context.getInitParameter("Tom"); resp.getWriter().println(name); System.out.println(name); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
在web.xml中设置初始化参数
<!--初始化参数--> <context-param> <param-name>Tom</param-name> <param-value>这是javaweb,这是servlet,这是初始化参数!</param-value> </context-param>
添加映射
启动Tomcat,访问!
2.3、请求转发
public class GetRequestDispatcher extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); System.out.println("这是GetRequestDispatcher!!!"); RequestDispatcher dispatcher = context.getRequestDispatcher("/init");//这是web设置的url路径 dispatcher.forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
添加映射
启动Tomcat,访问!
2.4、读取资源文件
target*是用来存放项目构建后的文件和目录、jar包、war包、编译的class*文件
Properties
- 在java目录下新建properties文件
- 在resources目录新建properties文件
username=张三 password=123456
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath;
public class GetProperties extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); //第一条“/”不能省略,代表真当前web项目 InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties"); Properties prop = new Properties(); prop.load(is);//获取文件流 String user = prop.getProperty("username"); String pwd = prop.getProperty("password"); resp.getWriter().print(user+":"+pwd); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
注意:"/WEB-INF/classes/db.properties"这是target 下的项目同名的目录路径!
添加映射
启动Tomcat,访问!
注意:要用maven模板新建的项目,这个target 目录下才有项目同名的包!
3、HttpServletRespouse
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse;
- 如果要获取客户端请求过来的参数:找HttpServletRequest
- 如果要给客户端响应一些信息:找HttpServletResponse
3.1、下载文件
- 要获取下载文件的路径
- 下载的文件名是什么?
- 设置想办法让浏览器能够支持下载我们需要的东西
- 获取下载文件的输入流
- 创建缓冲区
- 获取OutputStream对象
- 将FileOutputStream流写入buffer缓冲区
- 使用OutputStream将缓冲区中的数据输出到客户端!
response下载文件
public class HSResponse extends HelloServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String realPath = "文件路径\\文件名.文件类型"; //2. 下载的文件名是什么? String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1); resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")); FileInputStream fileInputStream = new FileInputStream(realPath); int len = 0; byte[] buffer = new byte[1024]; ServletOutputStream outputStream = resp.getOutputStream(); while ((len = fileInputStream.read(buffer)) > 0){ outputStream.write(buffer,0,len); } fileInputStream.close(); outputStream.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
添加映射
启动Tomcat,访问!
3.2、实现重定向
一个web资源收到客户端请求后,它会通知客户端去访问另一个web资源,这个过程叫重定向:
void sendRedirect(java.lang.String s) throws java.io.IOException;
public class Send extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.sendRedirect("/init");//路径发生变化 } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
4、HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServlet,通过这个HttpServlet的方法,获得客户端的所有信息;
4.1、获取前端传递的参数和请求转发
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>HSRequest</title> </head> <body> <div> <form action="${pageContext.request.contextPath}/request" method="post"> 用户名:<input type="text" name="username"><br> 密码:<input type="password" name="password"><br> 爱好: <input type="checkbox" name="hobbys" value="java">java <input type="checkbox" name="hobbys" value="JavaScript">JavaScript <input type="checkbox" name="hobbys" value="Oracle">Oracle <input type="checkbox" name="hobbys" value="Python">Python <br> <input type="submit"> </form> </div> </body> </html>
public class HSRequest extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); String password = req.getParameter("password"); String[] hobbys = req.getParameterValues("hobbys"); System.out.println(username+"\t"+password+"\t"+ Arrays.toString(hobbys)); req.getRequestDispatcher("/success.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>成功页面</title> </head> <body> <h1>登录成功</h1> <a href="${pageContext.request.contextPath}/index.jsp">首页</a> </body> </html>
这篇关于java web-01-servlet的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-01后台管理开发学习:新手入门指南
- 2024-11-01后台管理系统开发学习:新手入门教程
- 2024-11-01后台开发学习:从入门到实践的简单教程
- 2024-11-01后台综合解决方案学习:从入门到初级实战教程
- 2024-11-01接口模块封装学习入门教程
- 2024-11-01请求动作封装学习:新手入门教程
- 2024-11-01登录鉴权入门:新手必读指南
- 2024-11-01动态面包屑入门:轻松掌握导航设计技巧
- 2024-11-01动态权限入门:新手必读指南
- 2024-11-01动态主题处理入门:新手必读指南