创建简单servlet

在做项目中老碰见创建一个servlet的情况有时候因为不常用而忘记其相关的步骤,而创建一个简单的servlet步骤和代码内容是一样的,等以后用的时候直接用就可以了。

创建一个简单servlet步骤为:

1。创建一个类继承HttpServlet,实现相应的doGet和doPost方法,当然也可以根据情况实现其他的方法

package com.test;

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 TestServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest request ,HttpServletResponse response ) throws IOException{
		doPost(request ,response );
		
	}
	
	
	public void doPost(HttpServletRequest request ,HttpServletResponse response ) throws IOException{
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.write("<html>");
		out.write("<head>");
		out.write("<title>serlet结果</title>");
		out.write("</head>");
		out.write("<body>");
		out.write("您输入用户名为:"+request.getParameter("name"));
		out.write("<br/>您输入用密码为:"+request.getParameter("password"));
		out.write("</body>");
		out.write("<html>");
	}
	

}

 

2。在web.xml配置servlet的映射

 

<!-- 配置servlet -->	
  <servlet>
  	<servlet-name>TestServlet</servlet-name>
  	<servlet-class>com.test.TestServlet</servlet-class>
  </servlet>
  <!-- servlet映射 -->
  <servlet-mapping>
  	<servlet-name>TestServlet</servlet-name>
  	<url-pattern>/test</url-pattern>
  </servlet-mapping>

 

3。在页面中访问/test既可访问到对应的servlet

 

<form action="test" mothod="post">
    	<label>用户名</label><input type="text" name="name"/>
    	<label>密码</label><input type="password" name="password" />
    	<input type="submit" value="提交"/>
    </form>

  

你可能感兴趣的:(html,Web,xml,servlet)