今天在jsp上机实验遇到一些问题,从jsp页面转发数据到servlet处理数据的时候出现404错误

代码和目录如下

jsp页面转发数据到servlet报404

inputWord.jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="word" method=post>
        输入英文句子:
        <br>
        <textArea name="english" rows=5 cols=30></textArea>
        <br>
        <input type=submit value="提交">
    </form>
</body>
</html>

Decompose.java 代码如下:

package myservlet.control;

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;


/**
 * Servlet implementation class Decompose
 */
@WebServlet(urlPatterns = "/word",name="word")
public class Decompose extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Decompose() {
        super();
    }

    /**
     * @see HttpServlet#init()
     */
    public void init(ServletConfig config) throws ServletException{
        super.init(config);
    }
    
    /**
     * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
     */
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<html><body bgcolor=yellow>");
        String str = request.getParameter("english");
        if(str == null || str.length()==0){
            return;
        }
        String[] word = str.split("[^a-zA-Z]+");
        int n = 0;
        try{
            for(int i = 0; i < word.length; i++){
                if(word[i].length()>=1){
                    n++;
                    out.print("<br>"+word[i]);
                }
            }
        }catch(NumberFormatException e){    
            out.print(""+e);
        }
        out.print("<h2>句子中单词数目:"+n);
        out.println("</body></html>);

}

}

在查询了一些文章之后 将WEB-INF下的classes文件夹设置好了jsp页面转发数据到servlet报404

但是运行之后依然是404

jsp页面转发数据到servlet报404jsp页面转发数据到servlet报404

 

请教老师后。

是路径的问题。

/word写法是相对路径的写法,书上的代码是将servlet文件放在了web-inf文件夹下,而eclipse是将servlet文件放在java resources文件夹下,因此要采用绝对路径的写法。

“${pageContext.request.contextPath}/word”

该写法可获取项目路径。能访问项目下的资源文件。

用在action里面会去寻找servlet requestMapping是word的servlet。

相关文章: