javaServlet 的核心思想是web服务器端创建用来响应客户端请求的对象,该对象被称为一个server对象。jsp技术以javaserver 为基础,当客户端请求一个jsp页面时,Web服务器会自动生成一个对应的java文件,编译该java文件,并用编译得到的字节码文件在服务器端创建一个Servlet对象。但实际的web应用需要Servlet对象具有特定的功能,这时就需要web开发人员编写创建Servlet对象的类。
1)创建 第一个 FirstServlet 类
2)
3)
勾选上 点击完成 就可以了
4)
5)接下来 会报一个 错 及解决方法
解决方法
6)填充 java 代码
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
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 implementation class FirstServlet
*/
@WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
// 设置响应的内容类型
response.setContentType("text/html;charset=utf-8");
// 取得输出对象
PrintWriter out = response.getWriter();
out.println("");
// 在浏览器中显示 第一个Servlet类
out.println("第一个Servlet类");
out.println("");
}
}
至此一个 简单的Servlet 类 就 创建 完成了 ,
要想 让web 服务器使用 Servlet 类编译后的字节码文件创建Servlet 对象处理用户请求,必须先为web部署Servlet 。部署Servlet 有两种 方式 一是在 web.xml 中 二是基于注解的方式 部署
1)在 web.xml中 部署
代码
ch06
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
firstServlet
servlet.FirstServlet
firstServlet
/firstServlet
②运行 之前的FirstServlet 文件 结果
③如果出现 无法启动 Tomcat 错误 及解决 方法 (Maven项目:基础环境(依赖,基本配置文件)搭建完成,前端页面都导入,部署测试项目环境,出现该问题 没有 勾选)
解决
2)基于注解的方式部署Servlet
①注解介绍:从前面的学习可以知道 ,每开发一个Servlet,都要在web.xml文件中部署Servlet才能够使用,这样会给web工程的维护带来非常大的麻烦,在Servlet3.0中 提供了注解@webServlet,使得不在需要web.xml文件中进行Servlet的部署描述,简化了 开发流程。注意 为了 后期维护建议开发人员 部署Servlet时@WebServlet的属性 URLPatterns的值设置为Servlet类的名字。
② 创建一个SecondServlet.java
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
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 implementation class SecondServlet
*/
@WebServlet(name = "SecondServlet",urlPatterns = {"/SecondServlet"})
public class SecondServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SecondServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
// 设置响应的内容类型
response.setContentType("text/html;charset=utf-8");
// 取得输出对象
PrintWriter out = response.getWriter();
out.println("");
// 在浏览器中显示 第二个Servlet类
out.println("第二个Servlet类");
out.println("");
}
}
结果
课本6.23 实验环节 类似于 SecondServlet
源码
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
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 implementation class FirstServlet
*/
@WebServlet(name = "FirstServlet",urlPatterns = {"/FirstServlet"})
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
// 设置响应的内容类型
response.setContentType("text/html;charset=utf-8");
// 取得输出对象
PrintWriter out = response.getWriter();
out.println("");
// 在浏览器中显示 第一个Servlet类
out.println("第一个Servlet类");
out.println("");
}
}
一个Servlet对象的生命周期主要由下列3个过程组成。
①初始化Servlet对象
当Servlet对象第一次被请求加载时,服务器会创建一个Servlet对象,该Servlet对象调用init()方法完成必要的初始化工作
②service()方法响应请求
创建的Servlet对象在调用service()方法响应客户的请求
③Servlet对象消亡
当服务器关闭时,Servlet对象调用destroy()方式使用自己消亡。、
从上面3个过程来看,init()方法只被调用一次,即在Servlet第一次被请求加载时调用。当客户端请求Servlet服务时,服务器将启用一个新的线程,在该线程中,Servlet对象调用service()方法响应客户端请求,那么 多用户请求Servlet服务时,服务器会怎么办呐?服务器会为每一个线程启动一个新的线程,在每个线程中,Servlet对象调用service()方法响应客户端请求。也就是说,每个客户端请求都会导致service()方法被调用执行,分别运用在不同的线程中。通过以下 代码 来看一下
例:6——3 ThirdServlet.java
首先 我们在 initParams 中 有两个值 分别为 one 和 two
initParams= {@WebInitParam(name = "firstParam",value = "one"),
@WebInitParam(name = "secondParam",value = "two")})
然后再 在ThirdServlet 类下 弄几个 String 类型的 属性
public class ThirdServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String first = null;
private String second = null;
private static int count = 0;
之后 在 init 方法后面 通过 Servletconfig 的对象 config调用getInitparameter() 方法俩获取 参数的值 如果结果值打印 一次 那么init方法 只执行一次
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
//获得参数firstParam的值
first = config.getInitParameter("firstParam");
second = config.getInitParameter("secondParam");
System.out.println("第一个参数值:"+ first);
System.out.println("第二个参数值:"+ second);
}
最后 我们在service方法 后面 写入count 计数 如果 不断的请求 不断的执行 就会不断的累加
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
count++;
System.out.println("您是第"+count+"个客户端请求该Servlet!");
}
下面为全部代码
package servlet;
import java.io.IOException;
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;
import javax.swing.JInternalFrame;
/**
* Servlet implementation class ThirdServlet
*/
@WebServlet(name = "ThirdServlet",urlPatterns = {"/ThirdServlet"},
initParams= {@WebInitParam(name = "firstParam",value = "one"),
@WebInitParam(name = "secondParam",value = "two")})
public class ThirdServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String first = null;
private String second = null;
private static int count = 0;
/**
* @see HttpServlet#HttpServlet()
*/
public ThirdServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
//获得参数firstParam的值
first = config.getInitParameter("firstParam");
second = config.getInitParameter("secondParam");
System.out.println("第一个参数值:"+ first);
System.out.println("第二个参数值:"+ second);
}
/**
* @see Servlet#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
count++;
System.out.println("您是第"+count+"个客户端请求该Servlet!");
}
}
运行结果
可以通过jsp页面的表单或超链接请求某个Servlet。通过jsp页面访问Servlet的好处是:jsp页面只负责页面的静态信息处理,而动态信息处理由Servlet完成
通过 例6_4来 感觉一下
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
login.jsp
LoginServlet.java
package servlet;
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 implementation class LoginServlet
*/
@WebServlet(name = "LoginServlet",urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//支持的打开类型
response.setContentType("text/html;charset=utf-8");
//通过这种方式,客户端就可以接受到数据了。客户端读取数据有多种方式,可以通过ajax读,也可以通过GetPostUtil来读取返回的数据。
PrintWriter out = response.getWriter();
//设置编码,放置中文乱码
request.setCharacterEncoding("utf-8");
//获取客户提交信息
String name = request.getParameter("user");
//获取客户提交信息
String password = request.getParameter("pwd");
out.println("");
if (name==null || name.length() == 0) {
out.println("请输入用户名");
}else if (password == null || password.length() == 0) {
out.println("请输入密码");
}else if (name.length()>0 && password.length()>0) {
if (name.equals("zhangsan") && password.equals("lisi")) {
out.println("信息输入正确");
}else {
out.println("信息输入错误");
}
}
out.println("");
}
}
结果图
注意的事项 这三句话 是 必不可少的 少一个 都可能 报错
//支持的打开类型
response.setContentType("text/html;charset=utf-8");
//通过这种方式,客户端就可以接受到数据了。客户端读取数据有多种方式,可以通过ajax读,也可以通过GetPostUtil来读取返回的数据。
PrintWriter out = response.getWriter();
//设置编码,放置中文乱码
request.setCharacterEncoding("utf-8");
当服务器收到一个Servlet请求时,就会产生一个新的线程,在这个线程中Servlet对象调用service()方法请求作出相应。service() 方法首先检查Http请求类型(get或者Post),然后在service()方法中根据用户的请求方式,对应地调用doGet()或dopost()方法。
一般情况下,如果不论用户请求类型是get还是post,服务器的处理过程完全相同。
通过例6-5 体会一下
inputLader.jsp 代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
inputLader.jsp
输入矩形的长和宽,提交给Servlet(post方式)求面积:
GetLengthOrAreaServlet代码
package servlet;
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 implementation class GetLengthOrAreaServlet
*/
@WebServlet(name = "GetLengthOrAreaServlet",urlPatterns = {"/GetLengthOrAreaServlet"})
public class GetLengthOrAreaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GetLengthOrAreaServlet() {
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
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String l = request.getParameter("length");
String w = request.getParameter("width");
out.println("");
double m = 0,n=0;
try {
m = Double.parseDouble(l);
n = Double.parseDouble(w);
out.println("矩形的周长是:"+(m+n)*2);
} catch (NumberFormatException e) {
// TODO: handle exception
out.println("请输入数字字符!");
}
out.println("");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String l = request.getParameter("length");
String w = request.getParameter("width");
out.println("");
double m = 0,n=0;
try {
m = Double.parseDouble(l);
n = Double.parseDouble(w);
out.println("矩形的周长是:"+(m+n)*2);
} catch (NumberFormatException e) {
// TODO: handle exception
out.println("请输入数字字符!");
}
out.println("");
}
}
结果图:
重定向是将用户当前jsp页面或Servlet定向到另一个jsp页面或Servlet,以前的request中存放的信息全部失效,并进去一个全新的request作用域;转发是将用户对当前jsp页面或Servlet的请求转发给另一个jsp页面或Servlet,以前的request中存放的信息不会失效。
通过6-6 编写jsp页面redirectForward.jsp 在该jsp页面中通过表单向URLPatterns为“{“/redirectForwaedServlet”}”的Servlet提交用户账户和密码 如果用户输入的数据不完整 redirectForwardServlet将用户重定向到redirectForward.jsp页面;如果用户输入的数据完整,redirectForwardServlet 将用户定向到redirectForward.jsp页面 页面请求转发给URLPatterns为“{“/showServlet”}”的Servlet,showServlet显示用户输入信息。
redirectForward.jsp 代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
redirectForWard.jsp
RedirectForWardServlet.java 代码
package servlet;
import java.io.IOException;
import javax.security.auth.message.callback.PrivateKeyCallback.Request;
import javax.servlet.RequestDispatcher;
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 implementation class RedirectForWardServlet
*/
//基于注解的部署
@WebServlet( name = "RedirectForWardServlet",urlPatterns = {"/RedirectForWardServlet"})
public class RedirectForWardServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RedirectForWardServlet() {
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
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
String name = request.getParameter("user");
String password = request.getParameter("pwd");
if (name == null || name.length() == 0) {
//使用response 调用sendRedirect方法重定向到redirectForward.jsp中
response.sendRedirect("redirectForward.jsp");
}else if (password == null ||password.length() == 0) {
response.sendRedirect("redirectForward.jsp");
}else if (name.length() > 0 && password.length()>0) {
RequestDispatcher dis = request.getRequestDispatcher("ShowServlet");
dis.forward(request, response);
}
}
}
ShowServlet.java 代码
package servlet;
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;
import org.apache.jasper.tagplugins.jstl.core.Out;
/**
* Servlet implementation class ShowServlet
*/
//基于注解的部署
@WebServlet(name = "ShowServlet",urlPatterns = {"/ShowServlet"})
public class ShowServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ShowServlet() {
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
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
request.setCharacterEncoding("utf-8");
String name = request.getParameter("pwd");
String password = request.getParameter("pwd");
out.println("您的用户名是:"+name);
out.println("
您的密码是:"+password);
}
}
运行 结果
总结:重定向 总结 两个转向分别是 jsp 转向 和 Servlet 转向
//使用response 调用sendRedirect方法重定向到redirectForward.jsp中
response.sendRedirect("redirectForward.jsp");
1)在当前jsp页面或Servlet中,使用request对象调用public RequestDisPatchgetPequestDispatch(Sting url) 方法返回一个RequestDispatch对象,其中参数url就是要转发的jsp页面或者Servlet的地址
2)获得ResquestDispatch 对像之后,就可以使用该对象调用 public void forward(ServletRequest request,ServletResponse response) 方法将用户对当前jsp 页面或者Servlet的请求发送给RequestDispatch对象所指定的jsp页面或者Servlet
RequestDispatcher dis = request.getRequestDispatcher("ShowServlet");
dis.forward(request, response);
编写登录页面login_1.jsp,在该jsp页面中通过表单向 urlPatterns 为“{“/loginServlet_1”}” 的Servlet(由LoginServlet_1类负责创建) 提交用户名和密码。如果用户输入数据不完整,LoginServlet_1将用户定向到login_1.jsp页面 ;如果用户输入数据完整且正确(用户名 zhangsan 密码123) LoginServlet_1将用户的请求转发给LoginSuccess_1.jsp页面,loginSuccess_1.jsp显示用户输入的信息
1)login_1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
login_1.jsp
2)LoginServlet_1
package servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 implementation class LoginServlet_1
*/
@WebServlet(name = "LoginServlet_1",urlPatterns = {"/LoginServlet_1"})
public class LoginServlet_1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet_1() {
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
doGet(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
String name = request.getParameter("user");
String password = request.getParameter("pwd");
if (name == null || name.length() == 0) {
//使用response 调用sendRedirect方法重定向到redirectForward.jsp中
response.sendRedirect("login_1.jsp");
}else if (password == null ||password.length() == 0) {
response.sendRedirect("login_1.jsp");
}else if (name.length() > 0 && password.length()>0) {
if (name.equals("zhangsan") && password.equals("123")) {
RequestDispatcher dis = request.getRequestDispatcher("loginSuccess_1.jsp");
dis.forward(request, response);
}
}
}
}
3)loginSuccess_1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
loginSuccess_1.jsp
<%
request.setCharacterEncoding("utf-8");
String name = request.getParameter("user");
String password = request.getParameter("pwd");
out.println("您的用户名是:" + name);
out.println("
您的密码是:" + password);
%>
运行结果
通过 例6-7了解一下
编写jsp页面useSession.jsp 在该页面中通过表单向用户名存入用户的Servlet对象(由UseSessionServlet类负责创建)提交用户useSession将用户名存入用户的sessionshowName从用户的session对象中取出存储的用户名,并显示在浏览器中。
页面文件 useSession.jsp 代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
useSession.jsp
2)UseSessionServlet.java 代码
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class UseSessionServlet
*/
@WebServlet(name = "UseSessionServlet",urlPatterns = {"/UseSessionServlet"})
public class UseSessionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UseSessionServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
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
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//文件 支持的打开 方式
response.setContentType("text/html;charset=utf-8");
//允许拼写 out
PrintWriter out = response.getWriter();
//这个页面支持 中文
request.setCharacterEncoding("utf-8");
String name = request.getParameter("user");
if (null==name || name.trim().length()==0) {
//如果 名字为空 继续留在 原界面
response.sendRedirect("userSession.jsp");
}else {
//条件 不为空
//若存在会话则返回该会话,否则新建一个会话
HttpSession session = request.getSession(true);
//获取本Servlet页面的name 并存放
session.setAttribute("myName", name);
out.println("");
out.println("您请求的Servlet对象是:"+getServletName());
out.println("
您的会话ID是:"+session.getId());
out.println("
请单击请求另一个Servlet:");
out.println("
请求另一个Servlet");
out.println("");
}
}
}
3)ShowNameServlet 的代码 如下:
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class ShowNameServlet
*/
@WebServlet(name = "ShowNameServlet",urlPatterns = {"/ShowNameServlet"})
public class ShowNameServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ShowNameServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
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
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
//访问前面 保存在Session中的内容 并修改 里面的name 就是 本Servlet的名字
String name = (String) session.getAttribute("myName");
session.setAttribute("myName", name);
out.println("");
//所以这里的getServletName 变成了 本页面的 名字
out.println("您请求的Servlet对象是:"+getServletName());
//下面这两个 还是 原来 存储的信息
out.println("
您的会话ID是:"+session.getId());
out.println("
您的会话中存储的用户名是:"+name);
out.println("");
}
}
运行结果图
1)mvc的概念
MVC是model、view、controller的缩写,分别代表了web应用程序中的3种职责。
①模型:用于存储数据以及处理用户请求的业务逻辑。
②视图:向控制器提交数据,显示模型中的数据。
③控制器:根据视图提出的请求,判断将请求和数据交给那个模型处理,处理后的有关结果交给那个视图更新显示。
2)基于Servlet的MVC模式
基于Servlet的MVC模式的具体实现如下:
①模型:一个或多个JavaBean对象,用于存储数据(实体模型,由JavaBean类创建)和处理业务逻辑(业务模型,由一般的java类创建)。
②视图:一个或多个jsp页面,向控制器提交数据和为模型提供数据显示,jsp页面只要使用HTML标记和JavaBean标记来显示数据。
③控制器:一个或多个Servlet对象,根据视图提交的请求进行控制,即将请求转发给处理业务逻辑的JavaBean,并处理记过存放到实体模型JavaBean中,输出给视图显示。
例:6——8 使用 jsp 、Servlet、JavaBean实现MVC
1)User.java
package servlet;
public class User {
private String name;
private String pwd;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
2)UserCheck.java
package servlet;
public class UserCheck {
//判断方法validate 参数是 前面的java 类 user
public boolean validate(User user) {
//判断名字 是否为空 如果名字不为空 且 名字 = jspMVC
if (user !=null && user.getName().equals("jspMVC")) {
//and == MVc 返回正确 否则 返回 错误
if (user.getPwd().equals("MVC")) {
return true;
}
return false;
}
return false;
}
}
3)LoginCheckServlet.java
package servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 implementation class LoginCheckServlet
*/
@WebServlet(name ="LoginCheckServlet" ,urlPatterns = {"/LoginCheckServlet"})
public class LoginCheckServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
//实例化实体模型 user
User user = new User();
//将数据存储在user中
user.setName(name);
user.setPwd(pwd);
//实例化业务模型 userCheck
UserCheck uc = new UserCheck();
if (uc.validate(user)==true) {
//将装有数据的实体模型user存储到request范围内
request.setAttribute("user",user);
//RequestDispatcher 代表请求的派发者。它有2个动作:forward 和 include 。
//客户端对于任何一个请求,可以根据业务逻辑需要,选择不同的处理办法:
/*RequestDispatcher 有一个特点,就是浏览器上显示的URL是最先请求的目标资源的URL,
* 不会因为使用了forward、include方法而改变。因此forward和include的调用对于用户
* 来说是透明的。RequestDispatcher 实质是一个接口,*/
RequestDispatcher dis = request.getRequestDispatcher("loginSuccess.jsp");
/*Java代码中request.getRequestDispatcher(" ").forward(request,response),
* 也即是请求转发。*/
dis.forward(request, response);
}else {
response.sendRedirect("loginCheck.jsp");
}
}
}
4)loginCheck.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
loginCheck.jsp
5)loginSuccess.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
loginSuccess.jsp
结果图
用户通过jsp页面inputNumber.jsp 输入两个操作数,并选择一种运算符,单击提交按钮后,调用HandleComputer.java 这个Servlet。在HandleComputer中首先获取用户输入的数字和运算符并将这些内容存入实体模型(由Computer.java创建)中,然后调用业务模型(由CalculateBean.java创建)进行计算并将结果存入实体模型中,在showResult.jsp中调用JavaBean显示结果。
1)Computer.java 实体模型
package servlet;
//实体模型
public class Computer {
private double number3;
private double number1;
private double number2;
private String operation;
public Computer() {
super();
}
public Computer(double number3, double number1, double number2, String operation) {
super();
this.number3 = number3;
this.number1 = number1;
this.number2 = number2;
this.operation = operation;
}
public double getNumber3() {
return number3;
}
public void setNumber3(double number3) {
this.number3 = number3;
}
public double getNumber1() {
return number1;
}
public void setNumber1(double number1) {
this.number1 = number1;
}
public double getNumber2() {
return number2;
}
public void setNumber2(double number2) {
this.number2 = number2;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
}
2)CalculateBean.java 实体模型处理
package servlet;
//处理逻辑思维
public class CalculateBean {
public boolean judge1(Computer computer) {
if (computer !=null) {
return true;
}
return false;
}
public double judge(Computer computer) {
if (computer.getOperation().equals("+")) {
return computer.getNumber1()+computer.getNumber2();
}
if (computer.getOperation().equals("-")) {
return computer.getNumber1()-computer.getNumber2();
}
if (computer.getOperation().equals("*")) {
return computer.getNumber1()*computer.getNumber2();
}
if (computer.getOperation().equals("/")) {
return computer.getNumber1()/computer.getNumber2();
}
return 0;
}
// public double judge(String operation,int number1,int number2) {
//
// if (operation.contains("+")) {
// return number1+number2;
// }else if(operation.contains("-")) {
// return number1-number2;
// }else if (operation.contains("*")) {
// return number1*number2;
// }else if (operation.contains("/")) {
// return number1/number2;
// }else {
// return 0;
// }
//
// }
}
3)HandleComputer Servlet (上面注释掉的和下面注释掉的 可以另一种写法)
package servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 implementation class HandleComputer
*/
@WebServlet(name ="HandleComputer",urlPatterns = {"/HandleComputer"})
public class HandleComputer extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
int number1 =Integer.parseInt(request.getParameter("number1"));
int number2 =Integer.parseInt(request.getParameter("number2"));
String operation = request.getParameter("operation");
//实例化 实体逻辑模型
// CalculateBean calculateBean = new CalculateBean();
// //获得了 实体模型中 number3的值
// double number4 = calculateBean.judge(operation, number1, number2);
//实例化实体模型
//将数据 存储到computer中
Computer computer = new Computer();
computer.setNumber1(number1);
computer.setNumber2(number2);
computer.setOperation(operation);
// computer.setNumber3(number4);
CalculateBean calculateBean = new CalculateBean();
if (calculateBean.judge1(computer)==true) {
computer.setNumber3(calculateBean.judge(computer));
request.setAttribute("computer", computer);
RequestDispatcher dispatcher = request.getRequestDispatcher("showResult.jsp");
dispatcher.forward(request, response);
}else {
response.sendRedirect("inputNumber.jsp");
}
}
}
4)inputNumber.jsp 用户界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
inputNumber.jsp
5)showResult.jsp 显示用户界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
showResult.jsp
您的计算结果为:
运行结果图
终于结束了 !