第一个Servlet程序

1、编写Servlet程序的步骤

(1)新建一个Java类,该类继承HttpServlet接口,并重写doGet和doPost方法。

(2)在web.xml文件中注册Servlet。

 

2、Servlet类的实现代码

package com.keke.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//解决post方式请求的中文乱码问题
		request.setCharacterEncoding("UTF-8");
		//处理输出到浏览器的中文乱码问题
		response.setContentType("text/html;charset=utf-8");
		
		//接收前台的数据
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println("接收前台的数据:username="+username+",password="+password);
		
		//向页面输出信息
		PrintWriter out = response.getWriter();
		out.println("<font color='red'>嗨,你好</font>");
		out.flush();
		out.close();
	}
	
}

 

3、web.xml文件中的注册信息

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

	<!-- 注册servlet -->
	<servlet>
		<servlet-name>loginServlet</servlet-name>
		<servlet-class>com.keke.servlet.LoginServlet</servlet-class>
	</servlet>	
	<servlet-mapping>
		<servlet-name>loginServlet</servlet-name>
		<url-pattern>/login</url-pattern>
	</servlet-mapping>
	
  	<welcome-file-list>
   	 	<welcome-file>index.jsp</welcome-file>
  	</welcome-file-list>
  	
</web-app>

 

你可能感兴趣的:(浏览器)