前面两节已经学习了什么是Servlet,Servlet接口函数是哪些、怎么运行、Servlet生命周期是什么? 以及Servlet中的模式匹配URL,web.xml配置和HttpServlet。怎么在Eclipse中新建一个Servlet工程项目。 今天这里主要是创建一个Servlet+JSP的例子。
一、学习之前补充一下web.xml中配置问题
web.xml中<welcome-file-list>配置((web欢迎页、首页))
用于当用户在url中输入工程名称或者输入web容器url(如http://localhost:8080/)时直接跳转的页面.
welcome-file-list的工作原理是,按照welcome-file的.list一个一个去检查是否web目录下面存在这个文件,如果存在,继续下面的工作(或者跳转到index.html页面,或者配置有的,会直接struts的过滤工作).如上例,先去webcontent(这里是Eclipse的工程目录根目录)下是否真的存在index.html这个文件,如果不存在去找是否存在index.jsp这个文件,。
还要说的是welcome-file不一定是html或者jsp等文件,也可以是直接访问一个action。就像我上面配置的一样,但要注意的是,一定要在webcontent下面建立一个index.action的空文件,然后使用struts配置去跳转,不然web找不到index.action这个文件,会报404错误,
如果配置了servlet的url-pattern是/*,那么访问localhost:8080/会匹配到该servlet上,而不是匹配welcome-file-list;如果url-pattern是/(该servlet即为默认servlet),如果其他匹配模式都没有匹配到,则会匹配welcome-file-list。
例如:
FirstServlet.java
1 package servlet; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.annotation.WebServlet; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest;10 import javax.servlet.http.HttpServletResponse;11 //@WebServlet("/Firstservlet")12 public class FirstServlet extends HttpServlet {13 14 /* (non-Javadoc)15 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)16 */17 @Override18 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {19 System.out.println("处理get()的请求。。。");20 PrintWriter pw = resp.getWriter();21 pw.write("hello!");22 }23 24 /* (non-Javadoc)25 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)26 */27 @Override28 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {29 30 }31 }
web.xml 配置
1 23 ServletTest 45 12index.html 6index.htm 7index.jsp 8default.html 9default.htm 10default.jsp 1115 ServletTest 13servlet.FirstServlet 1416 19ServletTest 17/* 18
index.jsp
1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 2 pageEncoding="ISO-8859-1"%> 3 4 5 6 7Insert title here 8 9 10 get this first servlet11 12
如果在上面web.xml里面配置<url-pattern>/*</url-pattern>, 在浏览器输入:直接匹配到Servlet
如果在上面web.xml里面配置<url-pattern>/</url-pattern>, 在浏览器输入:可以看出匹配到index.jsp
正常在web.xml里面配置<url-pattern>/FirstServlet</url-pattern>,会先匹配到index.jsp
二、Servlet+JSP
直接加例子:
1 package com.ht.servlet; 2 3 public class AccountBean { 4 private String username; 5 private String password; 6 /** 7 * @return the username 8 */ 9 public String getUsername() {10 return username;11 }12 /**13 * @param username the username to set14 */15 public void setUsername(String username) {16 this.username = username;17 }18 /**19 * @return the password20 */21 public String getPassword() {22 return password;23 }24 /**25 * @param password the password to set26 */27 public void setPassword(String password) {28 this.password = password;29 }30 }31 32 package com.ht.servlet;33 34 import java.io.IOException;35 36 import javax.servlet.ServletException;37 import javax.servlet.annotation.WebServlet;38 import javax.servlet.http.HttpServlet;39 import javax.servlet.http.HttpServletRequest;40 import javax.servlet.http.HttpServletResponse;41 import javax.servlet.http.HttpSession;42 43 /**44 * Servlet implementation class AccountBean45 */46 @WebServlet("/CheckAccount")47 public class CheckAccount extends HttpServlet {48 private static final long serialVersionUID = 1L;49 50 /**51 * @see HttpServlet#HttpServlet()52 */53 public CheckAccount() {54 super();55 // TODO Auto-generated constructor stub56 }57 58 /**59 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)60 */61 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {62 HttpSession sessionzxl = request.getSession();63 AccountBean account = new AccountBean();64 String username = request.getParameter("username");65 String pwd = request.getParameter("pwd");66 account.setPassword(pwd);67 account.setUsername(username);68 System.out.println("username :"+ username + " password :" + pwd);69 if((username != null)&&(username.trim().equals("jspp"))) {70 System.out.println("username is right!");71 if((pwd != null)&&(pwd.trim().equals("1"))) {72 System.out.println("success");73 sessionzxl.setAttribute("account", account);74 String login_suc = "success.jsp";75 response.sendRedirect(login_suc);76 return;77 }78 }79 System.out.println("fail!");80 String login_fail = "fail.jsp";81 response.sendRedirect(login_fail);82 return; 83 }84 85 /**86 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)87 */88 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {89 90 doGet(request, response);91 }92 93 }
登录的jsp页面如下Login.jsp
1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 2 pageEncoding="UTF-8"%> 3 4 <% 5 String path = request.getContextPath(); 6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 7 %> 8 9 10 1122 2312 13 My JSP 'login.jsp' starting page 14 15 16 This is my JSP page. 17
登录成功界面如下success.jsp:
1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 2 pageEncoding="UTF-8"%> 3 4 <%@ page import="com.ht.servlet.AccountBean"%> 5 6 <% 7 String path = request.getContextPath(); 8 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 9 %>10 11 12 1314 15 My JSP 'success.jsp' starting page 16 17 18 <%AccountBean account = (AccountBean)session.getAttribute("account");%>19 username:<%= account.getUsername()%> 20 password:<%= account.getPassword() %> 21 basePath: <%=basePath%>22 path:<%=path%>23 24
登录失败的jsp页面如下:fail.jsp
1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 2 pageEncoding="UTF-8"%> 3 4 <% 5 String path = request.getContextPath(); 6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 7 %> 8 9 10 1112 13 My JSP 'fail.jsp' starting page 14 15 16 Login Failed! 17 basePath: <%=basePath%>18 path:<%=path%>19 20
web.xml配置如下:
1 23 ServletTest 45 7 8Login.jsp 69 14This is the description of my J2EE component 10This is the display name of my J2EE component 11CheckAccount 12com.ht.servlet.CheckAccount 1315 18CheckAccount 16/login 17
描述一下上面运行过程:
在浏览器输入:http://localhost:8080/ServletTest/ 会通过欢迎页面welcome-file-list找到登录页面Login.jsp, 界面显示如下:
在登录页面输入用户名和密码,点击登录,找到对应的action, 会去运行/login其对应的servlet, 找到doGet()方法,判断用户名和密码
如果用户名密码不是jspp和1,就会跳转到失败页面fail.jsp
如果用户名等于jspp和1,则跳转到成功页面success.jsp
Session
上面就是一个最简单的JSP和servlet例子。在运行上面例子中,有一个概念session.
在checkAccount.java中,直接通过request获取session
HttpSession sessionzxl = request.getSession();
后面将定义的变量存储到session中:sessionzxl.setAttribute("account", account);
在jsp中怎么获取session?
在success.jsp中,有这么一行<%AccountBean account = (AccountBean)session.getAttribute("account");%>,那么session来至于哪儿?
查看资料后得知,session是jsp隐式对象。
JSP隐式对象是JSP容器为每个页面提供的Java对象,开发者可以直接使用它们而不用显式声明。JSP隐式对象也被称为预定义变量。
JSP所支持的九大隐式对象:
对象 | 描述 |
---|---|
request | HttpServletRequest 接口的实例 |
response | HttpServletResponse 接口的实例 |
out | JspWriter类的实例,用于把结果输出至网页上 |
session | HttpSession类的实例 |
application | ServletContext类的实例,与应用上下文有关 |
config | ServletConfig类的实例 |
pageContext | PageContext类的实例,提供对JSP页面所有对象以及命名空间的访问 |
page | 类似于Java类中的this关键字 |
Exception | Exception类的对象,代表发生错误的JSP页面中对应的异常对象 |
session是jsp的内置对象,所以你可以直接写在jsp的 <% session.setAttribute("a", b); //把b放到session里,命名为a, String M = session.getAttribute(“a”).toString(); //从session里把a拿出来,并赋值给M %>
下节添加一个Servlet+jsp+SQL例子。
https://blog.csdn.net/superit401/article/details/51974409