使用参数和接收表单数据

获取请求参数:

  请求参数可分为两种:

    1.查询参数,它直接显示在请求URL上,例如:http://localhost:8080/Hello-User/greeting?user=radiam,其中user就是请求参数

    2.请求正文,参数被包含在post请求中,这些参数可以通过web开发者工具进行查看

例子:获取单值请求参数

package cn.example;

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;

//使用注解部署servlet
@WebServlet(
		name = "helloServlet",
		urlPatterns = {"/greeting", "/salutation", "/wazzup"},
		loadOnStartup = 1
)
public class HelloServlet extends HttpServlet{
	// 设置一个默认的用户名
	private static final String DEFAULT_USER = "Guest";
	
	/*
	 * 功能:
	 * 检测请求中是否带有user参数,若没有,就使用常量值
	 * 设置响应内容的类型和字符编码
	 * 从响应中获得一个PrintWriter,并输出一个html文档
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 获取请求参数中的user
		String user = req.getParameter("user");
		if(user == null)
			user = HelloServlet.DEFAULT_USER;
		
		// 设置响应内容的类型是html文本
		resp.setContentType("text/html");
		// 设置响应内容的字符编码为utf-8
		resp.setCharacterEncoding("utf-8");
		
		// 获得响应的字符输出流
		PrintWriter writer = resp.getWriter();
		// 向字符输出流中输入html文本
		writer.append("<!DOCTYPE html>\r\n")
			.append("<html>\r\n")
			.append("	<head>\r\n")
			.append(" 		<title>Hello User Application</title>\r\n")
			.append("	</head>\r\n")
			.append("	<body>\r\n")
			.append(" 		Hello, ").append(user).append("!<br/>\r\n")
			.append("		<form action=\"greeting\" method=\"post\" >\r\n")
			.append("			Entry your name: <br/>\r\n")
			.append("			<input type=\"text\" name=\"user\" />\r\n")
			.append("			<input type=\"submit\" value=\"Submit\" />\r\n")
			.append("		</form>\r\n")
			.append("	</body>\r\n")
			.append("</html>\r\n");
	}
	
	/*
	 * 处理以post方法提交的表单
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 简单地把任务委托给doGet()方法
		this.doGet(req, resp);
	}
}

 

例子:获取多值请求参数

package cn.example;

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(
		name = "multivalueParameterServlet",
		urlPatterns = {"/checkbox"}
)
public class MultiValueParameterServlet extends HttpServlet{
	/*
	 * 创建一个html页面,询问用户喜欢哪些水果
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置响应内容的类型和字符编码
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		
		// 获得响应的PrintWriter对象
		PrintWriter writer = resp.getWriter();
		// 往输出流输入html文本
		writer.append("<!DOCTYPE html>\r\n")
			.append("<html>\r\n")
			.append("	<head>\r\n")
			.append("		<title>Hello User Application</title>\r\n")
			.append("	</head>\r\n")
			.append("	<body>\r\n")
			.append("		<form action=\"checkbox\" method=\"post\" />\r\n")
			.append("		Selection the fruits you like to eat:<br/>\r\n")
			.append("		<input type=\"checkbox\" name=\"fruit\" value=\"Banana\" /> Banana <br/>\r\n")
			.append("		<input type=\"checkbox\" name=\"fruit\" value=\"Orange\" /> Orange <br/> \r\n")
			.append("		<input type=\"checkbox\" name=\"fruit\" value=\"Guava\" /> Guava <br/> \r\n")
			.append("		<input type=\"checkbox\" name=\"fruit\" value=\"Kiwi\" /> Kiwi <br/> \r\n")
			.append("		<input type=\"submit\" value=\"submit\" />\r\n")
			.append("	</body>\r\n")
			.append("</html>\r\n");
	}
	
	/*
	 * 处理用户提交的表单
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 从请求正文中获得复选框中的选择
		String[] fruits = req.getParameterValues("fruit");
		//设置响应内容的类型和字符编码
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		
		// 获得响应的PrintWriter对象
		PrintWriter writer = resp.getWriter();
		writer.append("<!DOCTYPE html>\r\n")
		.append("<html>\r\n")
		.append("	<head>\r\n")
		.append("		<title>Hello User Application</title>\r\n")
		.append("	</head>\r\n")
		.append("	<body>\r\n")
		.append("		<h2>Your Selections</h2> \r\n");
		
		if(fruits == null)
			writer.append("		You did not select any fruits \r\n");
		else{
			writer.append("		<ul> \r\n");
			for(String fruit : fruits){
				writer.append("		<li>").append(fruit).append("</li> \r\n");
			}
			writer.append("		</ul>\r\n");
		}
		
		writer.append("		</body>\r\n")
			.append("</html>\r\n");
	}
}

 

使用初始化参数配置应用程序:

  有两种方式:

    1.使用上下文初始化参数,结果是:在servlet的任何地方都可以轻松获得这些初始化参数,它们不是某个servlet特有的,应用程序中的所有servlet都共享这些参数,可通过ServletContext对象调用getInitParameter(name)获得

    2.使用servlet初始化参数,结果是:这些参数是某个servlet特有的,可以从ServletConfig对象调用 getInitParameter(name) 获得,无需经过ServletContext对象

 

例子:获取上下文初始化参数:

/*
 * 获取上下文初始化参数
 */
@WebServlet(
        name = "contextParameterServlet",
        urlPatterns = {"/contextParameter"}
)
public class ContextParameterServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取ServletContext对象
        ServletContext context = this.getServletContext();
        
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        
        writer.append("settingOne: ").append(context.getInitParameter("settingOne"))
            .append(", settingTwo: ").append(context.getInitParameter("settingTwo"));
        
    }
}

在web.xml中配置

        <!-- 
 		使用上下文初始化参数,在这里的两个参数在Servlet代码的任何地方都可以轻松地访问和使用
 	 -->
 	 <context-param>
 	 	<param-name>settingOne</param-name>
 	 	<param-value>foo</param-value>
 	 </context-param>
 	 <context-param>
 	 	<param-name>settingTwo</param-name>
 	 	<param-value>bar</param-value>
 	 </context-param>    

 

例子:使用Servlet初始化参数

/*
 * 获取Servlet初始化参数,该参数是某个serlvet特有的,可以从ServletConfig对象中获取
 */
@WebServlet(
        name = "servletParameterServlet",
        urlPatterns = {"/servletParameters"},
        initParams = {
                @WebInitParam(name = "database", value = "CustomerSupport"),
                @WebInitParam(name = "server", value = "10.0.12.5")
        }
)
public class ServletParameterServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取ServletConfig对象
        ServletConfig config = this.getServletConfig();
        
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        
        writer.append("database: ").append(config.getInitParameter("database"))
            .append(", server: ").append(config.getInitParameter("server"));
    }
}

其中注解部分也可以在web.xml中配置,如下:

       <servlet>
          <servlet-name>servletParameterServlet</servlet-name>
          <servlet-class>cn.exampke.ServletParameterServlet</servlet-class>
          <init-param>
              <param-name>database</param-name>
              <param-value>CustomerSupport</param-value>
          </init-param>
          <init-param>
              <param-name>server</param-name>
              <param-value>10.0.12.5</param-value>
          </init-param>
      </servlet>
      <servlet-mapping>
          <servlet-name>servletParameterServlet</servlet-name>
          <url-pattern>/servletParameters</url-pattern>
      </servlet-mapping>    

 

使用注解和部署文件配置servlet的比较:

  1.使用注解:

    优点:避免xml配置,非常直接和简洁;

    缺点:当它修改时,需要重新编译应用程序;

       有些事情它不能办到,比如:创建单个servlet的多个实例,安排过滤器的执行顺序

  2.使用web.xml:

    优点:当它修改时,只需重启应用就可以使配置文件生效,不需要重新编译应用程序

       它可以做一些注解无法完成的事情

    缺点:比较繁琐

posted @ 2017-12-07 20:52  Aristole  阅读(1322)  评论(0编辑  收藏  举报