今天我刚上了第一堂关于 Java ee 和动态 Web 项目的课程……我有一个问题要问你。
我的老师要求我们在一个非常基本的 mvc 概念中创建一个控制器。
她给了我们一些代码示例,并要求我们从控制器调用视图。好的,它有效!但是,如果我尝试添加图像<img src="images/img.jpg" />
,我认为我的控制器会重新路由文件夹 images/img.jpg 并且我的 images/img.jpg 是文件标题中的类型文本......
任何帮助,将不胜感激...
这是我的 servlet Controller.java
package ca.qc.lacmegantic.ville;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Controller
*/
@WebServlet("/Controller")
public class Controller extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String urlCP = request.getRequestURI();
String url = urlCP.substring(request.getContextPath().length());
if (url.equals("/") || url.equals(""))
{
request.getRequestDispatcher("WEB-INF/views/view.jsp").forward(request, response);
}
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
processRequest(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
processRequest(request, response);
}
}
这是我的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>Controller</servlet-name>
<servlet-class>ca.qc.lacmegantic.ville.Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Controller</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
这是我的view.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<img src="images/img.jpg" />
</body>
</html>
文件结构: