第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

publicclassTestServletextendsHttpServlet{@OverrideprotectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{// TODO Auto-generated method stubsuper.doGet(req,resp);}@OverrideprotectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{// TODO Auto-generated method stubsuper.doPost(req,resp);}}

2)web.xml里配置对外暴露的地址。

web.xml在WebContent\WEB-INF\web.xml

TestServletcom.neuedu.javaweb.chap02.TestServletTestServlet/test.do

servlet3.0自动创建

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

@WebServlet("/regServlet")publicclassRegServletextendsHttpServlet{privatestaticfinallongserialVersionUID=1L;/**

* @see HttpServlet#HttpServlet()

*/publicRegServlet(){super();// TODO Auto-generated constructor stub}/**

    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

    */protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{// TODO Auto-generated method stubSystem.out.println("doGet被调用");response.getWriter().append("Served at: ").append(request.getContextPath());}/**

    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

    */protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{// TODO Auto-generated method stubdoGet(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")})publicclassRegServletextendsHttpServlet{privatestaticfinallongserialVersionUID=1L;/**

* @see HttpServlet#HttpServlet()

*/publicRegServlet(){super();// TODO Auto-generated constructor stub}@Overridepublicvoidinit(ServletConfigconfig)throwsServletException{// TODO Auto-generated method stubSystem.out.println(config.getInitParameter("userName"));super.init(config);}/**

    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{// TODO Auto-generated method stubSystem.out.println("doGet被调用");//response.getWriter().append("Served at: ").append(request.getContextPath());PrintWriterout=response.getWriter();out.println("success");}/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{// TODO Auto-generated method stubdoGet(request,response);}

}

注册程序

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

com.neuedu.dao.impl

目录结构如图

image.png

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

servlet

packagecom.neuedu.javaweb.chap02;importjava.io.IOException;importjava.io.PrintWriter;importjavax.servlet.ServletConfig;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebInitParam;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.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")})publicclassRegTestServletextendsHttpServlet{privatestaticfinallongserialVersionUID=1L;/**

* @see HttpServlet#HttpServlet()

*/publicRegTestServlet(){super();// TODO Auto-generated constructor stub}@Overridepublicvoidinit(ServletConfigconfig)throwsServletException{// TODO Auto-generated method stubSystem.out.println(config.getInitParameter("userName"));super.init(config);}/**

    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

    */protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}/**

    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

    */protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{System.out.println("doPost方法被调用");//获取前台输入的信息Stringname=request.getParameter("username");Stringpassword=request.getParameter("password");//checkbox数据String[]hobbys=request.getParameterValues("hobby");//打包userUseruser=newUser();user.setUserName(name);......//调用service进行处理IUserServiceuserService=newUserServiceImpl();inti=userService.addUser(user);//返回处理结果response.setContentType("text/html;charset=utf-8");PrintWriterout=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());Enumerationheaders=request.getHeaderNames();while(headers.hasMoreElements()){Stringkey=headers.nextElement();Stringvalue=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请求方式POSTorg.apache.tomcat.util.http.NamesEnumerator@3c32a826key---->hostvalue-->localhost:8081key---->connectionvalue-->keep-alivekey---->content-lengthvalue-->31key---->cache-controlvalue-->max-age=0key---->originvalue-->http://localhost:8081key---->upgrade-insecure-requestsvalue-->1key---->content-typevalue-->application/x-www-form-urlencodedkey---->user-agentvalue-->Mozilla/5.0(Windows NT6.1;WOW64)AppleWebKit/537.36(KHTML,like Gecko)Chrome/70.0.3538.16Safari/537.36key---->acceptvalue-->text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8key---->referervalue-->http://localhost:8081/myproject/login.htmlkey---->accept-encodingvalue-->gzip,deflate,brkey---->accept-languagevalue-->zh-CN,zh;q=0.9key---->cookievalue-->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人点赞

java web

作者:wqjcarnation

链接:https://www.jianshu.com/p/6742b3dfee7e

来源:

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

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