Servlet基础

来源:互联网 发布:java要学多久能学会 编辑:程序博客网 时间:2024/05/01 08:47
1、什么是Servlet
2、Tomcat容器等级
3、手工编写第一个Servlet
4、使用MyEclipse编写Servlet
5、Servlet生命周期
6、Servlet获取九大内置对象
7、Servlet与表单
8、Servlet路劲跳转

9、阶段项目


一、什么是Servlet?
        jsp的前身就是Servlet
        Servlet是在服务器上运行的小程序。一个Servlet就是一个Java类,并且可以通过“请求-响应”编程模型来访问这个驻留在服务器内存里的Servlet程序。

二、Tomcat容器等级
      Tomcat的容器分为四个等级,Servlet的容器管理Context容器,一个Context对应一个Web工程。
        Engine:引擎容器
        HOST:主机容器

        

三、手工编写第一个Servlet
    步骤:
1、继承HttpServlet
2、重写doGet()或者doPost()方法
3、在web.xml中注册Servlet
    在eclipse中重写doGet()和doPost()方法:单击右键——Source——Override/Implement Methods...
    @override注解:表示重写从父类继承过来的方法

四、使用MyEclipse编写Servlet
    步骤:
1、src——new——Servlet
2、重写doGet()或者doPost()
3、部署运行
    localhost是服务器主机名,也可以是IP地址127.0.0.1;
    8080是tomcat服务器的端口号;

五、Servlet生命周期
    servlet执行的流程:
        Get方式请求HelloServlet——<a href="servlet/HelloServlet">


    Servlet生命周期:


1、初始化阶段,调用init()方法
2、响应客户端的的请求阶段,调用service()方法。有service()方法根据提交方式选择执行doGet()或者doPost()方法
3、终止阶段,调用destroy()方法
    servlet生命周期阶段包括初始化、加载、实例化、服务和销毁。
    编写Servlet的doPost方法时,需要抛出ServletExcpetion和IOException异常

    在下列时刻Servlet容器装载Servlet:
        (1)Servlet容器启动时自动装载某些Servlet,实现它只需要在web.xml文件中<Servlet></Servlet>之间添加如下代码:

                    <loadon-startup>1</loadon-startup>数字越小表示优先级别越高。
        (2)在Servlet容器启动后,客户端首次向Servlet发送请求。
        (3)Servlet类文件被更新后,重新装载Servlet。
        (4)Servlet被装载后,Servlet容器创建一个Servlet实例并且调用Servlet的init()方法进行初始化。在Servlet的整个生命周期内,init()方法只被调用一次。


六、Servlet获取九大内置对象

JSP对象
怎样获取
out
resp.getWriter
request
service方法中的req参数
response
service方法中的resp参数
session
req.getSession()函数
application
getServletContext()函数
exception
Throwable
page
this
pageContext
PageContext
Config
getServletConfig函数

七、Servlet与表单

reg.jsp

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'reg.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->    <style type="text/css"> .label{  width: 20% } .controler{  width: 80% }   </style>     <script type="text/javascript" src="js/Calendar3.js"></script>  </head>    <body>    <h1>用户注册</h1>    <hr>    <form name="regForm" action="servlet/RegServlet" method="post" >  <table border="0" width="800" cellspacing="0" cellpadding="0">    <tr>    <td class="lalel">用户名:</td>    <td class="controler"><input type="text" name="username" /></td>    </tr>    <tr>    <td class="label">密码:</td>    <td class="controler"><input type="password" name="mypassword" ></td>        </tr>    <tr>    <td class="label">确认密码:</td>    <td class="controler"><input type="password" name="confirmpass" ></td>        </tr>    <tr>    <td class="label">电子邮箱:</td>    <td class="controler"><input type="text" name="email" ></td>        </tr>    <tr>    <td class="label">性别:</td>    <td class="controler"><input type="radio" name="gender" checked="checked" value="Male">男<input type="radio" name="gender" value="Female">女</td>        </tr>       <tr>    <td class="label">出生日期:</td>    <td class="controler">      <input name="birthday" type="text" id="control_date" size="10"                      maxlength="10" onclick="new Calendar().show(this);" readonly="readonly" />    </td>    </tr>    <tr>    <td class="label">爱好:</td>    <td class="controler">    <input type="checkbox" name="favorite" value="nba"> NBA        <input type="checkbox" name="favorite" value="music"> 音乐        <input type="checkbox" name="favorite" value="movie"> 电影        <input type="checkbox" name="favorite" value="internet"> 上网      </td>    </tr>    <tr>    <td class="label">自我介绍:</td>    <td class="controler">    <textarea name="introduce" rows="10" cols="40"></textarea>    </td>    </tr>    <tr>    <td class="label">接受协议:</td>    <td class="controler">    <input type="checkbox" name="flag" value="true">是否接受霸王条款    </td>    </tr>    <tr>    <td colspan="2" align="center">    <input type="submit" value="注册"/>          <input type="reset" value="取消"/>      </td>    </tr>  </table></form>  </body></html>

userinfo.jsp

<%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'userinfo.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->    <style type="text/css"> .title{ width: 30%; background-color: #CCC; font-weight: bold; } .content{     width:70%;     background-color: #CBCFE5; }    </style>    </head>    <body>    <h1>用户信息</h1>    <hr>    <center>     <jsp:useBean  id="regUser" class="entity.Users" scope="session"/>        <table width="600" cellpadding="0" cellspacing="0" border="1">        <tr>          <td class="title">用户名:</td>          <td class="content"> <jsp:getProperty name="regUser" property="username"/></td>        </tr>        <tr>          <td class="title">密码:</td>          <td class="content"> <jsp:getProperty name="regUser" property="mypassword"/></td>        </tr>        <tr>          <td class="title">性别:</td>          <td class="content"> <jsp:getProperty name="regUser" property="gender"/></td>        </tr>        <tr>          <td class="title">E-mail:</td>          <td class="content"> <jsp:getProperty name="regUser" property="email"/></td>        </tr>        <tr>          <td class="title">出生日期:</td>          <td class="content">             <%                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");               String date = sdf.format(regUser.getBirthday());                           %>             <%=date%>          </td>        </tr>        <tr>          <td class="title">爱好:</td>          <td class="content">             <%                String[] favorites = regUser.getFavorites();               for(String f:favorites)               {            %>                <%=f%>               <%                }            %>          </td>        </tr>        <tr>          <td class="title">自我介绍:</td>          <td class="content"> <jsp:getProperty name="regUser" property="introduce"/></td>        </tr>        <tr>          <td class="title">是否介绍协议:</td>          <td class="content"> <jsp:getProperty name="regUser" property="flag"/></td>        </tr>     </table>    </center>  </body></html>


Calendar3.js

/////////////////////////调用实例//        <div>//                <span>交易查询:</span> <span>从//                    <input name="control_date" type="text" id="control_date" size="10"//                        maxlength="10" onclick="new Calendar().show(this);" readonly="readonly" />//                    <input type="button" name="button" id="button" value="button" onclick="new Calendar().show(this.form.control_date);" /></span>//                <span>至//                    <input name="control_date2" type="text" id="control_date2" size="10"//                        maxlength="10" onclick="new Calendar().show(this);" readonly="readonly" />//                    <input type="button" name="button" id="button1" value="button" onclick="new Calendar().show(this.form.control_date2);" /></span>//        </div>//<!--/** * Calendar * @param   beginYear           1990 * @param   endYear             2010 * @param   language            0(zh_cn)|1(en_us)|2(en_en)|3(zh_tw) * @param   patternDelimiter    "-" * @param   date2StringPattern  "yyyy-MM-dd" * @param   string2DatePattern  "ymd" * @version 1.0 build 2006-04-01 * @version 1.1 build 2006-12-17 * @author  KimSoft (jinqinghua [at] gmail.com) * NOTE!    you can use it free, but keep the copyright please * IMPORTANT:you must include this script file inner html body elment  */function Calendar(beginYear, endYear, language, patternDelimiter, date2StringPattern, string2DatePattern) {this.beginYear = beginYear || 1990;this.endYear   = endYear   || 2020;this.language  = language  || 0;this.patternDelimiter = patternDelimiter     || "-";this.date2StringPattern = date2StringPattern || Calendar.language["date2StringPattern"][this.language].replace(/\-/g, this.patternDelimiter);this.string2DatePattern = string2DatePattern || Calendar.language["string2DatePattern"][this.language];this.dateControl = null;this.panel  = this.getElementById("__calendarPanel");this.iframe = window.frames["__calendarIframe"];this.form   = null;this.date = new Date();this.year = this.date.getFullYear();this.month = this.date.getMonth();this.colors = {"bg_cur_day":"#00CC33","bg_over":"#EFEFEF","bg_out":"#FFCC00"}};Calendar.language = {"year"   : ["\u5e74", "", "", "\u5e74"],"months" : [["\u4e00\u6708","\u4e8c\u6708","\u4e09\u6708","\u56db\u6708","\u4e94\u6708","\u516d\u6708","\u4e03\u6708","\u516b\u6708","\u4e5d\u6708","\u5341\u6708","\u5341\u4e00\u6708","\u5341\u4e8c\u6708"],["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"],["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"],["\u4e00\u6708","\u4e8c\u6708","\u4e09\u6708","\u56db\u6708","\u4e94\u6708","\u516d\u6708","\u4e03\u6708","\u516b\u6708","\u4e5d\u6708","\u5341\u6708","\u5341\u4e00\u6708","\u5341\u4e8c\u6708"]],"weeks"  : [["\u65e5","\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d"],["Sun","Mon","Tur","Wed","Thu","Fri","Sat"],["Sun","Mon","Tur","Wed","Thu","Fri","Sat"],["\u65e5","\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d"]],"clear"  : ["\u6e05\u7a7a", "Clear", "Clear", "\u6e05\u7a7a"],"today"  : ["\u4eca\u5929", "Today", "Today", "\u4eca\u5929"],"close"  : ["\u5173\u95ed", "Close", "Close", "\u95dc\u9589"],"date2StringPattern" : ["yyyy-MM-dd", "yyyy-MM-dd", "yyyy-MM-dd", "yyyy-MM-dd"],"string2DatePattern" : ["ymd","ymd", "ymd", "ymd"]};Calendar.prototype.draw = function() {calendar = this;var _cs = [];_cs[_cs.length] = '<form id="__calendarForm" name="__calendarForm" method="post">';_cs[_cs.length] = '<table id="__calendarTable" width="100%" border="0" cellpadding="3" cellspacing="1" align="center">';_cs[_cs.length] = ' <tr>';_cs[_cs.length] = '  <th><input class="l" name="goPrevMonthButton" type="button" id="goPrevMonthButton" value="<" \/><\/th>';_cs[_cs.length] = '  <th colspan="5"><select class="year" name="yearSelect" id="yearSelect"><\/select><select class="month" name="monthSelect" id="monthSelect"><\/select><\/th>';_cs[_cs.length] = '  <th><input class="r" name="goNextMonthButton" type="button" id="goNextMonthButton" value=">" \/><\/th>';_cs[_cs.length] = ' <\/tr>';_cs[_cs.length] = ' <tr>';for(var i = 0; i < 7; i++) {_cs[_cs.length] = '<th class="theader">';_cs[_cs.length] = Calendar.language["weeks"][this.language][i];_cs[_cs.length] = '<\/th>';}_cs[_cs.length] = '<\/tr>';for(var i = 0; i < 6; i++){_cs[_cs.length] = '<tr align="center">';for(var j = 0; j < 7; j++) {switch (j) {case 0: _cs[_cs.length] = '<td class="sun"> <\/td>'; break;case 6: _cs[_cs.length] = '<td class="sat"> <\/td>'; break;default:_cs[_cs.length] = '<td class="normal"> <\/td>'; break;}}_cs[_cs.length] = '<\/tr>';}_cs[_cs.length] = ' <tr>';_cs[_cs.length] = '  <th colspan="2"><input type="button" class="b" name="clearButton" id="clearButton" \/><\/th>';_cs[_cs.length] = '  <th colspan="3"><input type="button" class="b" name="selectTodayButton" id="selectTodayButton" \/><\/th>';_cs[_cs.length] = '  <th colspan="2"><input type="button" class="b" name="closeButton" id="closeButton" \/><\/th>';_cs[_cs.length] = ' <\/tr>';_cs[_cs.length] = '<\/table>';_cs[_cs.length] = '<\/form>';this.iframe.document.body.innerHTML = _cs.join("");this.form = this.iframe.document.forms["__calendarForm"];this.form.clearButton.value = Calendar.language["clear"][this.language];this.form.selectTodayButton.value = Calendar.language["today"][this.language];this.form.closeButton.value = Calendar.language["close"][this.language];this.form.goPrevMonthButton.onclick = function () {calendar.goPrevMonth(this);}this.form.goNextMonthButton.onclick = function () {calendar.goNextMonth(this);}this.form.yearSelect.onchange = function () {calendar.update(this);}this.form.monthSelect.onchange = function () {calendar.update(this);}this.form.clearButton.onclick = function () {calendar.dateControl.value = "";calendar.hide();}this.form.closeButton.onclick = function () {calendar.hide();}this.form.selectTodayButton.onclick = function () {var today = new Date();calendar.date = today;calendar.year = today.getFullYear();calendar.month = today.getMonth();calendar.dateControl.value = today.format(calendar.date2StringPattern);calendar.hide();}};Calendar.prototype.bindYear = function() {var ys = this.form.yearSelect;ys.length = 0;for (var i = this.beginYear; i <= this.endYear; i++){ys.options[ys.length] = new Option(i + Calendar.language["year"][this.language], i);}};Calendar.prototype.bindMonth = function() {var ms = this.form.monthSelect;ms.length = 0;for (var i = 0; i < 12; i++){ms.options[ms.length] = new Option(Calendar.language["months"][this.language][i], i);}};Calendar.prototype.goPrevMonth = function(e){if (this.year == this.beginYear && this.month == 0){return;}this.month--;if (this.month == -1) {this.year--;this.month = 11;}this.date = new Date(this.year, this.month, 1);this.changeSelect();this.bindData();};Calendar.prototype.goNextMonth = function(e){if (this.year == this.endYear && this.month == 11){return;}this.month++;if (this.month == 12) {this.year++;this.month = 0;}this.date = new Date(this.year, this.month, 1);this.changeSelect();this.bindData();};Calendar.prototype.changeSelect = function() {var ys = this.form.yearSelect;var ms = this.form.monthSelect;for (var i= 0; i < ys.length; i++){if (ys.options[i].value == this.date.getFullYear()){ys[i].selected = true;break;}}for (var i= 0; i < ms.length; i++){if (ms.options[i].value == this.date.getMonth()){ms[i].selected = true;break;}}};Calendar.prototype.update = function (e){this.year  = e.form.yearSelect.options[e.form.yearSelect.selectedIndex].value;this.month = e.form.monthSelect.options[e.form.monthSelect.selectedIndex].value;this.date = new Date(this.year, this.month, 1);this.changeSelect();this.bindData();};Calendar.prototype.bindData = function () {var calendar = this;var dateArray = this.getMonthViewDateArray(this.date.getFullYear(), this.date.getMonth());var tds = this.getElementsByTagName("td", this.getElementById("__calendarTable", this.iframe.document));for(var i = 0; i < tds.length; i++) {  tds[i].style.backgroundColor = calendar.colors["bg_over"];tds[i].onclick = null;tds[i].onmouseover = null;tds[i].onmouseout = null;tds[i].innerHTML = dateArray[i] || " ";if (i > dateArray.length - 1) continue;if (dateArray[i]){tds[i].onclick = function () {if (calendar.dateControl){calendar.dateControl.value = new Date(calendar.date.getFullYear(),calendar.date.getMonth(),this.innerHTML).format(calendar.date2StringPattern);}calendar.hide();}tds[i].onmouseover = function () {this.style.backgroundColor = calendar.colors["bg_out"];}tds[i].onmouseout  = function () {this.style.backgroundColor = calendar.colors["bg_over"];}var today = new Date();if (today.getFullYear() == calendar.date.getFullYear()) {if (today.getMonth() == calendar.date.getMonth()) {if (today.getDate() == dateArray[i]) {tds[i].style.backgroundColor = calendar.colors["bg_cur_day"];tds[i].onmouseover = function () {this.style.backgroundColor = calendar.colors["bg_out"];}tds[i].onmouseout  = function () {this.style.backgroundColor = calendar.colors["bg_cur_day"];}}}}}//end if}//end for};Calendar.prototype.getMonthViewDateArray = function (y, m) {var dateArray = new Array(42);var dayOfFirstDate = new Date(y, m, 1).getDay();var dateCountOfMonth = new Date(y, m + 1, 0).getDate();for (var i = 0; i < dateCountOfMonth; i++) {dateArray[i + dayOfFirstDate] = i + 1;}return dateArray;};Calendar.prototype.show = function (dateControl, popuControl) {if (this.panel.style.visibility == "visible") {this.panel.style.visibility = "hidden";}if (!dateControl){throw new Error("arguments[0] is necessary!")}this.dateControl = dateControl;popuControl = popuControl || dateControl;this.draw();this.bindYear();this.bindMonth();if (dateControl.value.length > 0){this.date  = new Date(dateControl.value.toDate(this.patternDelimiter, this.string2DatePattern));this.year  = this.date.getFullYear();this.month = this.date.getMonth();}this.changeSelect();this.bindData();var xy = this.getAbsPoint(popuControl);this.panel.style.left = xy.x + "px";this.panel.style.top = (xy.y + dateControl.offsetHeight) + "px";this.panel.style.visibility = "visible";};Calendar.prototype.hide = function() {this.panel.style.visibility = "hidden";};Calendar.prototype.getElementById = function(id, object){object = object || document;return document.getElementById ? object.getElementById(id) : document.all(id);};Calendar.prototype.getElementsByTagName = function(tagName, object){object = object || document;return document.getElementsByTagName ? object.getElementsByTagName(tagName) : document.all.tags(tagName);};Calendar.prototype.getAbsPoint = function (e){var x = e.offsetLeft;var y = e.offsetTop;while(e = e.offsetParent){x += e.offsetLeft;y += e.offsetTop;}return {"x": x, "y": y};};/** * @param   d the delimiter * @param   p the pattern of your date * @author  meizz * @author  kimsoft add w+ pattern */Date.prototype.format = function(style) {var o = {"M+" : this.getMonth() + 1, //month"d+" : this.getDate(),      //day"h+" : this.getHours(),     //hour"m+" : this.getMinutes(),   //minute"s+" : this.getSeconds(),   //second"w+" : "\u65e5\u4e00\u4e8c\u4e09\u56db\u4e94\u516d".charAt(this.getDay()),   //week"q+" : Math.floor((this.getMonth() + 3) / 3),  //quarter"S"  : this.getMilliseconds() //millisecond}if (/(y+)/.test(style)) {style = style.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));}for(var k in o){if (new RegExp("("+ k +")").test(style)){style = style.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));}}return style;};/** * @param d the delimiter * @param p the pattern of your date * @rebuilder kimsoft * @version build 2006.12.15 */String.prototype.toDate = function(delimiter, pattern) {delimiter = delimiter || "-";pattern = pattern || "ymd";var a = this.split(delimiter);var y = parseInt(a[pattern.indexOf("y")], 10);//remember to change this next century ;)if(y.toString().length <= 2) y += 2000;if(isNaN(y)) y = new Date().getFullYear();var m = parseInt(a[pattern.indexOf("m")], 10) - 1;var d = parseInt(a[pattern.indexOf("d")], 10);if(isNaN(d)) d = 1;return new Date(y, m, d);};document.writeln('<div id="__calendarPanel" style="position:absolute;visibility:hidden;z-index:9999;background-color:#FFFFFF;border:1px solid #666666;width:200px;height:216px;">');document.writeln('<iframe name="__calendarIframe" id="__calendarIframe" width="100%" height="100%" scrolling="no" frameborder="0" style="margin:0px;"><\/iframe>');var __ci = window.frames['__calendarIframe'];__ci.document.writeln('<!DOCTYPE html PUBLIC "-\/\/W3C\/\/DTD XHTML 1.0 Transitional\/\/EN" "http:\/\/www.w3.org\/TR\/xhtml1\/DTD\/xhtml1-transitional.dtd">');__ci.document.writeln('<html xmlns="http:\/\/www.w3.org\/1999\/xhtml">');__ci.document.writeln('<head>');__ci.document.writeln('<meta http-equiv="Content-Type" content="text\/html; charset=utf-8" \/>');__ci.document.writeln('<title>Web Calendar(UTF-8) Written By KimSoft<\/title>');__ci.document.writeln('<style type="text\/css">');__ci.document.writeln('<!--');__ci.document.writeln('body {font-size:12px;margin:0px;text-align:center;}');__ci.document.writeln('form {margin:0px;}');__ci.document.writeln('select {font-size:12px;background-color:#EFEFEF;}');__ci.document.writeln('table {border:0px solid #CCCCCC;background-color:#FFFFFF}');__ci.document.writeln('th {font-size:12px;font-weight:normal;background-color:#FFFFFF;}');__ci.document.writeln('th.theader {font-weight:normal;background-color:#666666;color:#FFFFFF;width:24px;}');__ci.document.writeln('select.year {width:64px;}');__ci.document.writeln('select.month {width:60px;}');__ci.document.writeln('td {font-size:12px;text-align:center;}');__ci.document.writeln('td.sat {color:#0000FF;background-color:#EFEFEF;}');__ci.document.writeln('td.sun {color:#FF0000;background-color:#EFEFEF;}');__ci.document.writeln('td.normal {background-color:#EFEFEF;}');__ci.document.writeln('input.l {border: 1px solid #CCCCCC;background-color:#EFEFEF;width:20px;height:20px;}');__ci.document.writeln('input.r {border: 1px solid #CCCCCC;background-color:#EFEFEF;width:20px;height:20px;}');__ci.document.writeln('input.b {border: 1px solid #CCCCCC;background-color:#EFEFEF;width:100%;height:20px;}');__ci.document.writeln('-->');__ci.document.writeln('<\/style>');__ci.document.writeln('<\/head>');__ci.document.writeln('<body>');__ci.document.writeln('<\/body>');__ci.document.writeln('<\/html>');__ci.document.close();document.writeln('<\/div>');var calendar = new Calendar();//-->

Users.java

package entity;import java.util.Date;//用户实体类public class Users {private String username; //用户名private String mypassword; //密码private String email; //电子邮箱private String gender; //性别private Date birthday; //出生日期private String[] favorites; //爱好private String introduce; //自我介绍private boolean flag; //是否接受协议public Users(){}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getMypassword() {return mypassword;}public void setMypassword(String mypassword) {this.mypassword = mypassword;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String[] getFavorites() {return favorites;}public void setFavorites(String[] favorites) {this.favorites = favorites;}public String getIntroduce() {return introduce;}public void setIntroduce(String introduce) {this.introduce = introduce;}public boolean isFlag() {return flag;}public void setFlag(boolean flag) {this.flag = flag;}}


RegServlet.java

package servlet;import java.io.IOException;import java.io.PrintWriter;import java.text.SimpleDateFormat;import java.util.Date;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import entity.Users;public class RegServlet extends HttpServlet {/** * Constructor of the object. */public RegServlet() {super();}/** * Destruction of the servlet. <br> */public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request,response);}/** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");Users u = new Users();String username,mypassword,gender,email,introduce,flag;Date birthday;String[] favorites;SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");try{username = request.getParameter("username");mypassword = request.getParameter("mypassword");gender = request.getParameter("gender");email = request.getParameter("email");introduce = request.getParameter("introduce");birthday = sdf.parse(request.getParameter("birthday"));if(request.getParameterValues("flag")!=null){flag = request.getParameter("flag");}else{flag = "false";}//用来获取多个复选按钮的值favorites = request.getParameterValues("favorite");u.setUsername(username);u.setMypassword(mypassword);u.setGender(gender);u.setEmail(email);u.setFavorites(favorites);u.setIntroduce(introduce);if(flag.equals("true")){u.setFlag(true);}else{u.setFlag(false);}u.setBirthday(birthday);//把注册成功的用户对象保存在session中request.getSession().setAttribute("regUser", u);//跳转带注册成功页面request.getRequestDispatcher("../userinfo.jsp").forward(request,response);}catch(Exception ex){ex.printStackTrace();}}/** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */public void init() throws ServletException {// Put your code here}}


web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  <display-name></display-name>  <servlet>    <description>This is the description of my J2EE component</description>    <display-name>This is the display name of my J2EE component</display-name>    <servlet-name>RegServlet</servlet-name>    <servlet-class>servlet.RegServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>RegServlet</servlet-name>    <url-pattern>/servlet/RegServlet</url-pattern>  </servlet-mapping>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></web-app>

八、Servlet路劲跳转
    绝对路劲:放之四海而皆准的路劲
    相对路径:相对于当前资源的路径

index.jsp

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>    <h1>Servlet路径跳转</h1>    <hr>    <!--使用相对路径访问HelloServlet -->    <!-- /servlet/HelloServlet 第一个/表示服务器的根目录 -->    <a href="servlet/HelloServlet">访问HelloServlet!</a><br>    <!-- 使用绝对路径 访问HelloServlet,可以使用path变量:path变量表示项目的根目录-->    <a href="<%=path%>/servlet/HelloServlet">访问HelloServlet!</a><br>    <!--表单中action的URL地址写法,与超链接方式完全相同。 -->    <a href="servlet/TestServlet">访问TestServlet,跳转到Test.jsp</a>       </body></html>


web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  <display-name></display-name>  <servlet>    <description>This is the description of my J2EE component</description>    <display-name>This is the display name of my J2EE component</display-name>    <servlet-name>HelloServlet</servlet-name>    <servlet-class>servlet.HelloServlet</servlet-class>  </servlet>  <servlet>    <description>This is the description of my J2EE component</description>    <display-name>This is the display name of my J2EE component</display-name>    <servlet-name>TestServlet</servlet-name>    <servlet-class>servlet.TestServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>HelloServlet</servlet-name>    <!--url-pattern处必须以/开头,这里的/表示项目的根目录  -->    <url-pattern>/servlet/HelloServlet</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>TestServlet</servlet-name>    <url-pattern>/servlet/TestServlet</url-pattern>  </servlet-mapping>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></web-app>

test.jsp

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>    <h1>Test.jsp</h1>    <hr>  </body></html>


HttpServlet.java

package servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class HelloServlet extends HttpServlet {/** * Constructor of the object. */public HelloServlet() {super();}/** * Destruction of the servlet. <br> */public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request,response);}/** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");PrintWriter out = response.getWriter();out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");out.println("<HTML>");out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");out.println("  <BODY>");out.println("<h1>您好,我是HelloServlet!</h1>");out.println("  </BODY>");out.println("</HTML>");out.flush();out.close();}/** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */public void init() throws ServletException {// Put your code here}}

TestServlet.java

package servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class TestServlet extends HttpServlet {/** * Constructor of the object. */public TestServlet() {super();}/** * Destruction of the servlet. <br> */public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request,response);}/** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { //请求重定向方式跳转到test.jsp,当前路径是ServletPathDirection/servlet/ //response.sendRedirect("test.jsp"); //使用request.getContextPath获得上下文对象         //response.sendRedirect(request.getContextPath()+"/test.jsp");         //服务器内部跳转,这里的斜线表示项目的根目录 //request.getRequestDispatcher("/test.jsp").forward(request, response); request.getRequestDispatcher("../test.jsp").forward(request, response);}/** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */public void init() throws ServletException {// Put your code here}}


九、阶段项目
      阶段案例:使用Servlet实现用户登录小例子。
      用户名admin,密码admin,登录成功使用服务器内部转发到login_success.jsp页面,并且提示登录成功的用户名。如果登陆失败则请求重定向到login_failure.jsp页面。

login.jsp

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%   String path = request.getContextPath();   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><html><head><!-- Page title --><title>imooc - Login</title><!-- End of Page title --><!-- Libraries --><link type="text/css" href="css/login.css" rel="stylesheet" /><link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" /><script type="text/javascript" src="js/jquery-1.3.2.min.js"></script><script type="text/javascript" src="js/easyTooltip.js"></script><script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script><!-- End of Libraries --></head><body><div id="container"><div class="logo"><a href="#"><img src="assets/logo.png" alt="" /></a></div><div id="box"><form action="servlet/LoginServlet" method="post"><p class="main"><label>用户名: </label><input name="username" value="" /> <label>密码: </label><input type="password" name="password" value=""></p><p class="space"><input type="submit" value="登录" class="login" style="cursor: pointer;"/></p></form></div></div></body></html>
login_success.jsp

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%   String path = request.getContextPath();   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><html><head><!-- Page title --><title>imooc - Login</title><!-- End of Page title --><!-- Libraries --><link type="text/css" href="css/login.css" rel="stylesheet" /><link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" /><script type="text/javascript" src="js/jquery-1.3.2.min.js"></script><script type="text/javascript" src="js/easyTooltip.js"></script><script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script><!-- End of Libraries --></head><body><div id="container"><div class="logo"><a href="#"><img src="assets/logo.png" alt="" /></a></div><div id="box">  <%      String loginUser = "";     if(session.getAttribute("loginUser")!=null)     {        loginUser = session.getAttribute("loginUser").toString();     }  %>     欢迎您<font color="red"><%=loginUser%></font>,登录成功!</div></div></body></html>
login_failure.jsp

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%   String path = request.getContextPath();   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><html><head><!-- Page title --><title>imooc - Login</title><!-- End of Page title --><!-- Libraries --><link type="text/css" href="css/login.css" rel="stylesheet" /><link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" /><script type="text/javascript" src="js/jquery-1.3.2.min.js"></script><script type="text/javascript" src="js/easyTooltip.js"></script><script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script><!-- End of Libraries --></head><body><div id="container"><div class="logo"><a href="#"><img src="assets/logo.png" alt="" /></a></div><div id="box">     登录失败!请检查用户或者密码!<br>  <a href="login.jsp">返回登录</a>   </div></div></body></html>

web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  <display-name></display-name>  <servlet>    <description>This is the description of my J2EE component</description>    <display-name>This is the display name of my J2EE component</display-name>    <servlet-name>LoginServlet</servlet-name>    <servlet-class>servlet.LoginServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>LoginServlet</servlet-name>    <url-pattern>/servlet/LoginServlet</url-pattern>  </servlet-mapping>  <welcome-file-list>    <welcome-file>login.jsp</welcome-file>  </welcome-file-list></web-app>

Users.java

package com.po;//用户类public class Users {private String username;private String password;public Users(){}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}
LoginServlet.java

package servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.po.Users;public class LoginServlet extends HttpServlet {/** * Constructor of the object. */public LoginServlet() {super();}/** * Destruction of the servlet. <br> */public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request,response);}/** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {Users u = new Users();String username = request.getParameter("username");String password = request.getParameter("password");u.setUsername(username);u.setPassword(password);//判断用户名和密码是否合法if(u.getUsername().equals("admin")&&u.getPassword().equals("admin")){response.sendRedirect(request.getContextPath()+"/login_success.jsp");}else{response.sendRedirect(request.getContextPath()+"/login_failure.jsp");}}/** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */public void init() throws ServletException {// Put your code here}}



1 0
原创粉丝点击