JavaWeb(JSP&Sqrvlet)入门

Posted 师兄白泽

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaWeb(JSP&Sqrvlet)入门相关的知识,希望对你有一定的参考价值。


在这之前需要搞定tomcat和maven的配置

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"
         metadata-complete="true">
    
</web-app>

解决maven资源导出失败的问题

    <!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
  <resources>
    <resource>
      <directory>src/main/resources</directory>
      <excludes>
        <exclude>**/*.properties</exclude>
        <exclude>**/*.xml</exclude>
      </excludes>
      <filtering>false</filtering>
    </resource>
    <resource>
      <directory>src/main/java</directory>
      <includes>
        <include>**/*.properties</include>
        <include>**/*.xml</include>
      </includes>
      <filtering>false</filtering>
    </resource>
  </resources>
</build>

1.helloServlet创建过程(详见Practice001)

  1. 在pom.xml中导入依赖
   <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  1. 新建HelloServlet(java文件)继承HttpServlet类以及继承get与post方法
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HelloServlet extends HttpServlet {
    //继承方法快捷键 Ctrl+o
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        writer.println("hello world");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
  1. 在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"
         metadata-complete="true">
    <!--添加映射-->
    <servlet>
        <servlet-name>Hello</servlet-name>
        <servlet-class>HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

2.ServletContext对象(详见Practice002)

web容器在启动时,会为每一个程序都创建一个ServletContext对象,它代表了当前的web应用。

2-1 共享数据(HelloServlet GetServlet)

  • 我在这个Servlet中保存的数据可以在另一个Servlet中拿到
  1. 放置数据(HelloServlet)
//放置数据的类
public class HelloServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        this.getInitParameter();初始化参数
//        this.getServletContext();Servlet上下文
//        this.getServletConfig();Servlet配置
//        重点
    ServletContext context = this.getServletContext();
    String userName = "白泽";//数据
    context.setAttribute("userName",userName);//将一个数据保存在ServletContext中,名字为userName 值为"白泽"
    System.out.println("进入了HelloServlet的get");
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

  }
}
  1. 读取数据(GetServlet)
//读取数据的类
public class GetServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext context = this.getServletContext();
    String name = (String) context.getAttribute("userName");
    //解决页面显示乱码的问题(显示大多数为问号?)
    resp.setContentType("text/html");
    resp.setCharacterEncoding("UTF-8");
    System.out.println(name);
    resp.getWriter().println("名字"+name);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

  }
}
  1. 添加映射(注册)
<?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"
         metadata-complete="true">
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.baize.Servlet.HelloServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>get</servlet-name>
    <servlet-class>com.baize.Servlet.GetServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>get</servlet-name>
    <url-pattern>/get</url-pattern>
  </servlet-mapping>
</web-app>

2-2 获取初始化参数(DemoServlet)

  1. 配置参数
    <!--配置一些web应用初始化context参数-->
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
    </context-param>
  1. 读取参数
public class DemoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        //获取初始化参数
        String url = context.getInitParameter("url");
        resp.getWriter().println(url);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}

2-3 请求转发 (RequestServlet)

/**
 * 转发请求的类
 * 转发到DemoServlet类
 * 注意:转发(request)时路径不会改变
 */
public class RequestServlet extends HelloServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入了RequestServlet方法");
        ServletContext context = this.getServletContext();
//        RequestDispatcher dispatcher = context.getRequestDispatcher("/url");//转发到请求路径
//        dispatcher.forward(req,resp);//调用forward实现请求转发
        context.getRequestDispatcher("/url").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}

2-4 读取资源文件Properties(PropertiesServlet)

  • 在java中新建properties
  • 在resources中新建properties

发现:都被打包到了同一个路径下:classes,俗称这个路径为类路径classpath;

注:有时候会出现打包不成功的情况,请自行百度

  1. 在resources文件夹中创建db.properties(打包后会生成在/WEB-INF/classes/db.properties中)
#mysql连接参数
username=root
password=12345678
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/school?serverTimezone=GMT
  1. 读取properties文件
/**
 * 操作读取properties的类
 */
public class PropertiesServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //将properties转换为一个流
        //注意写对路径(在target中查看路径)此处的路径为当前web项目下的classes中的properties
        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
        //操作properties的类
        Properties properties = new Properties();
        //加载流
        properties.load(is);
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
        resp.getWriter().println("username:"+username);
        resp.getWriter().println("password:"+password);
        resp.getWriter().println("url:"+url);
        resp.getWriter().println("driver:"+driver);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}

3.HttpServletResponse响应(详见Practice003)

Web客户端接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse

  • 如果要获取客户端请求过来的参数,用HttpServletRequest
  • 如果要给客户端响应一些信息,用HttpServletResponse

3-1.简单分类

负责向浏览器发送数据的方法

ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;

负责向浏览器发送响应头的方法(HttpServletResponse源码)

    void setCharacterEncoding(String var1);
    void setContentLength(int var1);
    void setContentType(String var1);
    void setBufferSize(int 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);
    void setStatus(int var1);
    /** @deprecated */
    //设置状态码
    void setStatus(int var1, String var2);

响应的状态码(HttpServletResponse源码)

    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 = javaweb dev 入

JavaWeb从零到一会话技术Cookie&Session&JSP

04-JavaWeb开发JSP&EL&JSTL&MVC&Bootstrap前端框架

JavaWeb-10(会话技术之session&amp;JSP)

JavaWeb开发之JSP&EL&JSTL

javaweb-cookie&session(未处理)