码迷,mamicode.com
首页 > 其他好文 > 详细

ServletRequest和ServletResponse

时间:2014-12-31 22:45:25      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

1 两个接口的实现类都是服务器给予实现的,并在服务器调用service方法传入

2 ServletRequest 可以获取任何请求信息:

1)获取请求参数:

   String getParameter(String name):根据请求参数名字,返回参数值

   若请求参数有多个值(checkbox),只能取到第一个提交的值

  String[] getParameterValues(String name)

  Enumeration getParameterNames()

  Map getParameterMap()

2) 获取请求的URI,请求参数的字符串等等用HttpServletRequest下的方法

public class TranServlet implements Servlet {

    /**
     * Constructor of the object.
     */
    public TranServlet() {
        super();
    }
    public ServletConfig getServletConfig() {
        // TODO Auto-generated method stub
        return null;
    }

    public String getServletInfo() {
        // TODO Auto-generated method stub
        return null;
    }

    public void init(ServletConfig config) throws ServletException {
        System.out.println("init");
        
    }

    public void service(ServletRequest req, ServletResponse res)
            throws ServletException, IOException {
        System.out.println("service");
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        System.out.println(account+" "+password);
        
        String[] hobbies = req.getParameterValues("hobby");
        for(String h:hobbies){
            System.out.println(h);
        }
        Enumeration<String> en = req.getParameterNames();
        while(en.hasMoreElements()){
            String name = en.nextElement();
            String value = req.getParameter(name);
            System.out.println(name+"+++"+value);
        }
        Map<String,String[]> map = req.getParameterMap();
        for(Map.Entry<String, String[]> entry: map.entrySet()){
            String key = entry.getKey();
            List<String> values = Arrays.asList(entry.getValue());
            System.out.println(key+"***"+values);
        }
        HttpServletRequest hsr = (HttpServletRequest)req;
        String uri = hsr.getRequestURI();
        String method = hsr.getMethod();
        String querystring = hsr.getQueryString();
        System.out.println(uri);
        System.out.println(method);
        System.out.println(querystring);
    }
    public void destroy() {
        
    }

}

ServletRequest和ServletResponse

标签:

原文地址:http://www.cnblogs.com/yjtm53/p/4196713.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!