Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tomcat 手工编译及部署动态网站(Servlet & Spring Core) #115

Open
JasonWu73 opened this issue Jun 10, 2020 · 0 comments
Open
Labels
参考 示例程序

Comments

@JasonWu73
Copy link
Owner

JasonWu73 commented Jun 10, 2020

D:.
│   pom.xml
│
└───src
    ├───main
    │   ├───java
    │   │   └───net
    │   │       └───wuxianjie
    │   │           └───demo
    │   │                   MyFilter.java
    │   │                   MyListener.java
    │   │                   MyServlet.java
    │   │                   User.java
    │   │
    │   └───resources
    │           spring.xml
    │
    └───test
        └───java

添加 Maven 依赖

创建一个空的 Maven 项目,在 pom.xml 中添加类似如下的内容:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>net.wuxianjie</groupId>
  <artifactId>demo-java-web</artifactId>
  <version>1.0-SNAPSHOT</version>

  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <!-- 解决执行 `maven test` 时,控制台中文乱码的问题 -->
    <argLine>-Dfile.encoding=UTF-8</argLine>
  </properties>

  <dependencies>
    <!-- Java Servlet API -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <!-- Spring Core -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <!-- 拷贝依赖文件 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>3.1.1</version>
        <executions>
          <execution>
            <id>copy-dependencies</id>
            <phase>package</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <!-- 排除 JUnit 等运行时依赖 -->
              <includeScope>runtime</includeScope>
              <outputDirectory>${project.build.directory}/lib/</outputDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

</project>

Spring Bean

package net.wuxianjie.demo;

public class User {

  private int userId;

  private String userName;

  public User(int userId, String userName) {
    this.userId = userId;
    this.userName = userName;
  }

  public int getUserId() {
    return userId;
  }

  public void setUserId(int userId) {
    this.userId = userId;
  }

  public String getUserName() {
    return userName;
  }

  public void setUserName(String userName) {
    this.userName = userName;
  }
}

src/main/resources/spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="user" class="net.wuxianjie.demo.User">
    <constructor-arg index="0" value="101"/>
    <constructor-arg index="1" value="吴仙杰"/>
  </bean>

</beans>

Servlet

package net.wuxianjie.demo;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 监听器
 *
 * <p>{@code ServletContext} 是一个全局的储存信息的空间。
 * 服务只要存在它就存在,服务关闭它就也没有了
 */
public class MyListener implements ServletContextListener {

  public void contextInitialized(ServletContextEvent sce) {

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");

    sce.getServletContext().setAttribute("spring", applicationContext);
  }

  public void contextDestroyed(ServletContextEvent sce) {

  }
}
package net.wuxianjie.demo;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 自定义过滤器(调用链)
 */
public class MyFilter implements Filter {

  /**
   * 初始化,在第一次 {@code doFilter()} 调用前调用
   *
   * <p>可获取 web.xml 文件中指定的参数
   */
  public void init(FilterConfig filterConfig) throws ServletException {

  }

  /**
   * 过滤行为,其中引入的 {@code FilterChain} 对象提供了后续过滤器信息
   *
   */
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    // 需要设置两个编码,以防在某些条件下,其中一个未生效
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    if (httpServletRequest.getHeader("User-Agent").toLowerCase().indexOf("chrome") > 0) {
      response.getWriter().write("不支持 Chrome 访问");
    } else {
      chain.doFilter(request, response);
    }
  }

  /**
   * {@code doFilter()} 中的所有活动都被该实例终止后,调用该方法
   */
  public void destroy() {

  }
}
package net.wuxianjie.demo;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;

public class MyServlet extends HttpServlet {

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

    ApplicationContext applicationContext = (ApplicationContext) req.getServletContext().getAttribute("spring");

    User user = applicationContext.getBean("user", User.class);

    String userName = req.getParameter("user_name");

    String resultUserName = userName == null || userName.trim().length() <= 0 ? user.getUserName() : userName;

    resp.getWriter().write("你好," + resultUserName);
  }
}

手工编译及部署

1、编译项目:

$ mvn package

2、在 $CATALINA_HOME/webapps 目录创建一个空的 myweb 文件夹

3、在 myweb 文件夹中再创建一个空的 WEB-INF 文件夹

WEB-INF 是 Tomcat 的安全目录。该目录中的文件不能被浏览器直接访问,如 web.xmlclasseslib 等都是放在该目录中的。

4、将项目编译生成的 classeslib 文件夹拷贝到 $CATALINA_HOME/webapps/myweb/WEB-INF

5、在 $CATALINA_HOME/webapps/myweb/WEB-INF 中创建 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_3_1.xsd"
  version="3.1">

  <!-- My Filter -->
  <filter>
    <filter-name>myFilter</filter-name>
    <filter-class>net.wuxianjie.demo.MyFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>*.do</url-pattern>
  </filter-mapping>
  <!-- ./My Filter -->

  <!-- My Servlet -->
  <servlet>
    <servlet-name>myServlet</servlet-name>
    <servlet-class>net.wuxianjie.demo.MyServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>myServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <!-- ./My Servlet -->

  <!-- My Listener -->
  <listener>
    <listener-class>net.wuxianjie.demo.MyListener</listener-class>
  </listener>
  <!-- ./My Listener -->

</web-app>

6、启动 Tomcat,然后通过浏览器等 HTTP 工具访问我们的服务,例如:GET http://localhost:8080/myweb/abc.do?user_name=张三

@JasonWu73 JasonWu73 added the 参考 示例程序 label Jun 10, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
参考 示例程序
Projects
None yet
Development

No branches or pull requests

1 participant