注解的方式配置servlet以及获取表单中提交的元素(单值元素和多值元素)

Servlet3.0是Java EE6规范的一部分所以说使用注解需要在JAVA EE6以上 (Tomact7.0全面支持注解)
package servlet;

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;
@WebServlet("/reg")
public class StuRegServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 设置请求字符集
		req.setCharacterEncoding("UTF-8");
		// 获取表单提交的元素(单值元素)
		String name = req.getParameter("stuName");
		String sex = req.getParameter("sex");
		String city = req.getParameter("city");
		String comment = req.getParameter("comment");
		// 获取表单提交的元素(多值元素)
		String[] subArr = req.getParameterValues("subject");
		// 设置响应内容类型和字符集
		resp.setContentType("text/html;charset=UTF-8");
		// 获取响应输出流
		PrintWriter out = resp.getWriter();
		out.write("");
		out.write("	");
		out.write("		");
		out.write("			学生信息页面");
		out.write("			");
		out.write("		");
		out.write("		");
		out.write("			

学生信息如下:

"); String subjectString = "暂无所学课程"; if (subArr != null) { subjectString = ""; for (String s : subArr) { subjectString += s + ","; } } out.write("

" + name + sex + "居住地为:" + city + "所学课程有:" + subjectString + " 个人介绍:" + comment + "

"); out.write(" "); out.write(" "); out.flush(); out.close(); } }

你可能感兴趣的:(注解的方式配置servlet以及获取表单中提交的元素(单值元素和多值元素))