第2,8章 servlet 开发技术(12课时)

第2章 servlet开发技术

Servlet是什么

servlet是基于java语言的web服务器端编程技术。按照一定规则定义的java类。他有约定好的一些方法。get post init destroy

servlet作用

无论是get/post方法都至少有两个参数,一个叫HttpServletRequest(请求对象),一个叫HttpServletResponse(响应对象)
他对外暴露一个地址,可以用于页面访问的。

servlet如何创建和定义

有两种创建方式servlet2.5以前半自动创建 (.java+web.xml)
servlet2.5注解方式创建 (
.java+注解)

第一种方式:servlet2.5以前是手动创建

1)写一个servlet类(java)继承HttpServlet

public class TestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doPost(req, resp);
    }

}

2)web.xml里配置对外暴露的地址。
web.xml在WebContent\WEB-INF\web.xml

 
 TestServlet
 com.neuedu.javaweb.chap02.TestServlet
  
 
 TestServlet
 /test.do
 

servlet3.0自动创建

包名-new -servlet-输入servlet文件名称-下一步-urlmapping里可以更改映射地址-finish

@WebServlet("/regServlet")
public class RegServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
   
/**
 * @see HttpServlet#HttpServlet()
 */
public RegServlet() {
super();
// TODO Auto-generated constructor stub
}

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("doGet被调用");
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

servlet生命周期关键方法

init()初始化方法
service()服务方法
doGet()
doPost()
......根据method不同,service将请求分发到不同方法
destory()销毁方法

注意:init()和destory()方法整个生命周期中只执行一次。service等方法可以执行多次

初始化带参数以及init里获取参数

@WebServlet(value="/regServlet",initParams={@WebInitParam(name="driver",value="com.mysql.jdbc.Driver"),
        @WebInitParam(name="userName",value="root"),
        @WebInitParam(name="passWord",value="root")}
)
public class RegServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
   
/**
 * @see HttpServlet#HttpServlet()
 */
public RegServlet() {
super();
// TODO Auto-generated constructor stub
}

    

    @Override
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub
        System.out.println(config.getInitParameter("userName"));
        super.init(config);
    }



    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    System.out.println("doGet被调用");
    //response.getWriter().append("Served at: ").append(request.getContextPath());
    PrintWriter out=response.getWriter();
    out.println("success");
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}

}

注册程序

新建包 com.neuedu.service com.neuedu.service.impl  com.neuedu.dao 

com.neuedu.dao.impl
目录结构如图


第2,8章 servlet 开发技术(12课时)_第1张图片
image.png




注册页面


注册页面
账号:
密码:
爱好:打篮球 踢足球 烫头

servlet

package com.neuedu.javaweb.chap02;

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

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class RegServlet
 */
@WebServlet(value="/regServlet",initParams={@WebInitParam(name="driver",value="com.mysql.jdbc.Driver"),
        @WebInitParam(name="userName",value="root"),
        @WebInitParam(name="passWord",value="root")}
)
public class RegTestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
   
/**
 * @see HttpServlet#HttpServlet()
 */
public RegTestServlet() {
super();
// TODO Auto-generated constructor stub
}

    

    @Override
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub
        System.out.println(config.getInitParameter("userName"));
        super.init(config);
    }



    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
        
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost方法被调用");
        //获取前台输入的信息
        String name=request.getParameter("username");
        String password=request.getParameter("password");
        //checkbox数据
           String[] hobbys=request.getParameterValues("hobby");
          //打包user
    User user=new User();
    user.setUserName(name);
    ......
    //调用service进行处理
    IUserService userService=new UserServiceImpl();
    int i=userService.addUser(user);
    //返回处理结果
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out=response.getWriter();
    if(i>0){
        out.println("success");
    }else{
        out.println("failure");
    }
    }
}

解决中文乱码问题

request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");

request里能获取什么

应用程序上下文 request.getContextPath()
客户端ip request.getRemoteAddr()
客户端端口 request.getRemotePort()
本地地址 request.getLocalAddr()
相对路径 request.getRequestURI()
请求方式 request.getMethod()
头信息(了解,是枚举类型)
request.getHeaderNames()

    //上下文路径
    System.out.println("应用程序上下文"+request.getContextPath());
            System.out.println("客户端ip"+request.getRemoteAddr());
            System.out.println("端口"+request.getRemotePort());
    System.out.println("本地addr"+request.getLocalAddr());
    System.out.println("相对路径"+request.getRequestURI());
    System.out.println("请求方式"+request.getMethod());
    //以下了解
    System.out.println(request.getHeaderNames());
    Enumeration headers=request.getHeaderNames();
    while(headers.hasMoreElements()){
        String key=headers.nextElement();
        String value=request.getHeader(key);
        System.out.println("key--->"+key);
        System.out.println("value--->"+value);
        
    }

打印结果:

应用程序上下文/myproject
客户端ip0:0:0:0:0:0:0:1
端口51784
本地addr0:0:0:0:0:0:0:1
相对路径/myproject/loginServlet
请求方式POST
org.apache.tomcat.util.http.NamesEnumerator@3c32a826
key---->host
value-->localhost:8081
key---->connection
value-->keep-alive
key---->content-length
value-->31
key---->cache-control
value-->max-age=0
key---->origin
value-->http://localhost:8081
key---->upgrade-insecure-requests
value-->1
key---->content-type
value-->application/x-www-form-urlencoded
key---->user-agent
value-->Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.16 Safari/537.36
key---->accept
value-->text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
key---->referer
value-->http://localhost:8081/myproject/login.html
key---->accept-encoding
value-->gzip, deflate, br
key---->accept-language
value-->zh-CN,zh;q=0.9
key---->cookie
value-->Webstorm-a327319a=cc9d0535-8c62-45c6-91d2-ba803bc9a72d

转发和重定向

转发:只发一次请求 地址栏的地址不变 只能转发到内部地址 效率高 request转发 request可以带参数
重定向:两次请求 地址栏地址会变化 可以请求外部地址 效率低 responset重定向 只能在url地址里带参数(如果重定向到的页是用html的IFRAME开发的,只能用redirect)
应用技巧:
如果请求外部地址或者跳转时不需要携带原始请求用重定向。否则用转发
重定向时加上上下文路径

response.sendRedirect(request.getContextPath()+"/user/index.html");

转发写法

request.getRequestDispatcher("/login.html").forward(request, response);

代码详见第2章代码样例(注册登录)

你可能感兴趣的:(第2,8章 servlet 开发技术(12课时))