一个完整的web项目目录结构:在服务器端建立以下标准路径 WEB-INF,WEB-INF下为lib,classes文件夹和一个web.xml的配置文件。
Web.xml文件中的代码及其含义:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
metadata-complete="true">
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
</web-app>
Name可以随便起,servlet-class写的是类名,即servlet-class的完整路径(配置此处时是默认到classes文件夹下去找)。在配置servlet-mapping时servlet-name和上面配置的名称一样,url-pattern为从工程的根目录开始(即WEB-INF文件夹的目录)。
单独为tomcat修改JAVA_HOME,编辑tomcat bin目录下的startup文件,在开始处加入一句“setJAVA_HOME=C:\Program Files\Java\jdk1.7.0”。
页面代码:
<html>
<head>
<title>login</title>
</head>
<body>
<form action="http://127.0.0.1:8080/test-servlet/loginServlet" method="get">
用户:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
注意此处的http://127.0.0.1:8080/test-servlet/loginServlet是连接的配置文件web.xml中的url-pattern。
Servlet中代码:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException{
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username=" + username);
System.out.println("password=" + password);
response.setContentType("text/html");
response.getWriter().println("Login Success!!");
}
因为引入了servlet相关的包,所以要在classpath中配置一下,把servlet-api的路径加到classpath中,如果返回页面的为中文,要设置一下内容格式为GBK格式。设置代码为response.setContentType("text/html;charset=GBK");
几种编码的含义:GB2312:只支持简体中文
GBK:支持简体和繁体中文
GB18030:支持的更多。
三者为包含关系