小白刚学javaWeb,这个问题研究一下午了还是没搞明白,想请大家指点一下。
主要问题是:servlet(servlet.java)编写好之后,到底应该放在哪个文件夹中?
文件目录:
在index.jsp中有一个表单,准备使用servlet来处理。
index.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>登录</title>
</head>
<body>
<center>
<form action="MyServlet/servlet1" method="get">
<table border=2 style="background-color: lightskyblue; margin: auto">
<tr>
<td>姓名:</td>
<td><input type="text" name="userName"></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="userInfo"></td>
</tr>
<tr>
<tr>
<td>身高:</td>
<td><input type="text" name="userInfo"></td>
</tr>
<tr>
<tr>
<td>体重:</td>
<td><input type="text" name="userInfo"></td>
</tr>
<tr>
<td colspan=2 align=center><input type="submit" value="提交"></td>
</tr>
</table>
</form>
</center>
</body>
</html>
servlet.java内容:
import java.io.IOException;
import java.io.PrintWriter;
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 servlet1
*/
@WebServlet("/MyServlet/servlet1")
public class servlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public servlet1() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// 设置输入的编码格式为GBK
request.setCharacterEncoding("GBK");
// 设置输入的编码格式为GBK
response.setCharacterEncoding("GBK");
// 给浏览器的标示,该字体为text/html
response.setContentType("text/html");
String Name=request.getParameter("userName");
String []Info=request.getParameterValues("userInfo");
PrintWriter out=response.getWriter();
out.println("<html><head><title>接收成功</title></head><body>");
out.println("接收到来自于"+Name+"的消息,他的信息是:"+"<br>");
out.println("年龄:"+Info[0]+"<br>");
out.println("身高:"+Info[1]+"<br>");
out.println("体重:"+Info[2]+"<br>");
out.println("</body></html>");
}
}
当我启动tomcat之后,访问:
http://localhost:8080/servletTest/index.jsp
这样是可以访问到index页面的,当我填完表单,点击提交之后,就显示404错误了。请问一下,是我servlet放置的位置不对吗,还是因为我servlet的@WebServlet()注解写的不对?还是因为我表单action=""这个地方写的不对?正确的情况应该怎么写啊?谢谢大家