web.xml配置

修改默认首页

web.xml中使用<welcome-file-list>标签来设置首页,即:

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
</welcome-file-list>

设置首页后服务端会自动寻找该名称的文件作为首页,同样的在二级目录中也会以该名称的文件作为首页。

Servlet通配符映射

在为Servlet绑定url时,可以使用通配符*使得包含该路径的页面都可以被Servlet拦截。
示例:

package com.servlet.patten;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class EmployeeControl extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求地址
        String path = req.getRequestURL().toString();
        System.out.println(path);

        // 获取最后一个/后的值
        String id = path.substring(path.lastIndexOf("/") + 1);

        // 根据id输出不同员工的信息
        String name;
        if (id.equals("1"))
            name = "张三";
        else if (id.equals("2"))
            name = "李四";
        else
            name = "其他员工";

        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().println("<h1>" + id + ":" + name + "</h1>");
    }
}
<?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-name>EmployControl</servlet-name>
        <servlet-class>com.servlet.patten.EmployControl</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>EmployControl</servlet-name>
        <url-pattern>/employee/*</url-pattern>
    </servlet-mapping>
</web-app>

用浏览器进行访问
在这里插入图片描述
可以看到根据浏览器最后的值可以获得不同的结果。

设置异常页面

对于服务器返回的异常页面例如404、500等都会带有一些后台信息,所以一般来说会对这类页面进行重新定义。这时就需要在web.xml中配置<error-page>标签定义状态码和其对应的页面地址。
示例:

<error-page>
  	<error-code>404</error-code>
  	<location>/error/404.html</location>
</error-page>
<error-page>
  	<error-code>500</error-code>
  	<location>/error/500.jsp</location>
</error-page>

当访问的页面不存在即响应返回404异常,会在web.xml中找到对应的页面返回给浏览器。

数据初始化

可以在web.xml中使用<context-param>标签定义全局属性。

<context-param>
	<param-name>copyright</param-name>
	<param-value>© 2018 imooc.com  京ICP备 12003892号-22</param-value>
</context-param>
<context-param>
	<param-name>title</param-name>
	<param-value>CSDN</param-value>
</context-param>

在代码中可以直接通过getInitParamter(String var1)获取属性值。通过这种方式可以更加灵活的配置一些长时间不变化的数据。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	ServletContext context = request.getServletContext();
	String copyright = context.getInitParameter("copyright");
	context.setAttribute("copyright", copyright);
	String title = context.getInitParameter("title");
	context.setAttribute("title", title);
	response.getWriter().println("init success");
}

JSP的九大内置对象

对象描述
request请求对象(HttpServletRequest)
response响应对象(HttpServletResponse)
session用户会话(HttpSession)
application应用全局对象(ServletContext)
out输出对象(PrintWriter)
page当前页面对象(this)
pageContext页面上下文对象(PageContext)
config应用配置对象(ServletConfig)
exception应用异常对象(Throwable)

示例:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String url = request.getRequestURL().toString(); // HttpServletRequest
		response.getWriter().println(url);//HttpServletResponse
	%>
	<% out.println("<br>ABCCC"); 
		session.setAttribute("user", "张三");
		out.println((String)session.getAttribute("user"));
	%>
	<%
		String cp = application.getInitParameter("copyright") ; //ServletContext
		out.println("<hr/>");
		out.println(cp);
		pageContext.getRequest();
		pageContext.getResponse();
		pageContext.getSession();
		pageContext.getServletContext();
	%>
</body>
</html>

小程序

在XML中编辑好员工信息,通过浏览器的访问地址的不同显示相应的员工信息。

  • 创建员工的实体类
package com.servlet.employee;

public class Employee {
    private String id;
    private String name;
    private String salary;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSalary() {
        return salary;
    }

    public void setSalary(String salary) {
        this.salary = salary;
    }
}

  • 创建员工信息保存在XML中
<?xml version="1.0" encoding="utf-8" ?>
<employees>
    <employee id="3001">
        <name>Tom</name>
        <salary>3000</salary>
    </employee>
    <employee id="3002">
        <name>Jack</name>
        <salary>4000</salary>
    </employee>
    <employee id="3003">
        <name>Mary</name>
        <salary>5000</salary>
    </employee>
</employees>

  • 创建获取实现类,用于根据浏览器发出的请求读取对应员工信息表中的信息
package com.servlet.employee;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class EmployeeServerImp {
    public Employee getEmployee(String empId) {
        SAXReader saxReader = new SAXReader();
		// 获取资源文件employee.xml的路径并打印在控制台 
        URL url = EmployeeServerImp.class.getResource("/employee.xml");
        System.out.println(url);

        Employee emp = null;
        try {
            Document document = saxReader.read(url);
            Element root = document.getRootElement();

            // 获取所有的employee元素
            List<Element> list = root.elements("employee");

            if (list == null)
                return null;

            for (Element employee : list) {
                if (empId.equals(employee.attributeValue("id"))) {
                    // 获取该员工的属性
                    emp = new Employee();

                    emp.setId(employee.attributeValue("id"));
                    emp.setName(employee.elementText("name"));
                    emp.setSalary(employee.elementText("salary"));

                    break;
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
            return null;
        }

        return emp;
    }
}

  • Servlet实现类,完成数据的接收也响应
package com.servlet.employee;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class EmployeeControl extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        EmployeeServerImp employeeServerImp = new EmployeeServerImp();

        // 获取浏览器的访问地址
        String url = req.getRequestURL().toString();

        // 获取地址最后的员工信息
        String empId = url.substring(url.lastIndexOf("/") + 1);

        Employee employee = employeeServerImp.getEmployee(empId);

        resp.setContentType("text/html;charset=utf-8");
        if (employee != null) {
            // 将查询到的employee对象添加到请求属性中
            req.setAttribute("employee", employee);
            // 将请求转发给info.jsp界面
            req.getRequestDispatcher("/info.jsp").forward(req, resp);
        } else {
            resp.getWriter().println("未找到员工" + empId);
        }
    }
}

  • 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-name>employee</servlet-name>
        <servlet-class>com.servlet.patten.EmployeeControl</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>employee</servlet-name>
        <url-pattern>/employee/*</url-pattern>
    </servlet-mapping>
</web-app>
  • info.jsp结果展示界面
<%@ page import="com.servlet.employee.Employee" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>infor</title>
</head>
<body>
    <%
        Employee employee = (Employee) request.getAttribute("employee");
    %>
    <table>
        <tr>
            <th>姓名</th>
            <th>工资</th>
        </tr>
        <tr>
            <td><%=employee.getName() %></td>
            <td><%=employee.getSalary() %></td>
        </tr>
    </table>
</body>
</html>

注意:

  1. 引入的jar包如何添加到项目中
    点击File–>Project Structure,在Libraries中点击"+"选择Java,找到需要导入的jar包,导入项目。
    在这里插入图片描述在这里插入图片描述
    向项目引入jar包后,点击Artifacts,在右侧选中要添加到项目的jar包,右键选择"Put into /WEB-INF/lib"就可以将jar包添加进项目中并自动创建lib目录。
    在这里插入图片描述
  2. Tomcat的路径问题
    Tomcat部署项目后并不会把编译后的项目复制到tomcat的webapps目录下,但是它会把编译好的项目路径告诉Tomcat,让Tomcat来找到这个项目,其它的项目比如Tomcat的主页项目ROOT是打不开的,因为intellij idea 只让Tomcat运行了一个项目。因此在解析XML时无法通过相对路径来获取XML,所以需要将employee.xml放到src/resources路径下,并将该路径设置为资源文件,这样就可以通过getResource()方法来获取XML的位置。
    在这里插入图片描述
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值