在 Tomcat 下运行第一个Servlet

前提,配好JDK环境,下载6.0以上版本Tomcat绿色版。


新建文件夹:...apache-tomcat-6.0.37\webapps\myApp

新建文件夹:...myApp\WEB-INF

新建文件夹:...WEB-INF/classes

新建文件:    ...WEB-INF/web.xml


web.xml

<?xml version="1.0" encoding="UTF-8"?> 
<web-app version="2.5" 
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_2_5.xsd"> 


<servlet>

<servlet-name>Login</servlet-name>
<servlet-class>LoginServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>

</servlet-mapping>


</web-app> 

LoginServlet.java

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

public class LoginServlet extends HttpServlet {

    public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {

        process(httpServletRequest,httpServletResponse);
    }

    @Override
    protected  void doPost(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException{

        process(httpServletRequest,httpServletResponse);
    }

    public void process(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {

        String username = httpServletRequest.getParameter("username");
        String password = httpServletRequest.getParameter("password");

        httpServletResponse.setContentType("text/html");

        PrintWriter printWriter = httpServletResponse.getWriter();
        printWriter.println("<html><head><title>login</title></head>");
        printWriter.println("<body>username: " + username + "<br>");
        printWriter.println("password: " + password + "</body></html>");
    }
}


LoginServlet.java依赖于servlet-api.jar,可以在...apache-tomcat-6.0.37\lib下找到。
将LoginServlet.java编译后的LoginServlet.class放到WEB-INF/classes下。


最后,新建文件:  ...myApp/index.jsp

index.jsp

<body>

<form action="Login" method="post">

	username: <input type="username" name="username"> <br>
	password: <input type="password" name="password"> <br>
	
	<input type="submit" value="submit">   
	<input type="reset" value="reset"> <br>
	
</form>

</body>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值