前面两节已经学习了什么是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的,会直接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

 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;
//@WebServlet("/Firstservlet")
public class FirstServlet extends HttpServlet { /* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("处理get()的请求。。。");
PrintWriter pw = resp.getWriter();
pw.write("hello!");
} /* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { }
}

web.xml 配置

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ServletTest</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet><servlet-name>ServletTest</servlet-name>
<servlet-class>servlet.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletTest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>

index.jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href = "/ServletTest/FirstServlet">get this first servlet</a>
</body>
</html>

如果在上面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

直接加例子:

 package com.ht.servlet;

 public class AccountBean {
private String username;
private String password;
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
} package com.ht.servlet; import java.io.IOException; 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 AccountBean
*/
@WebServlet("/CheckAccount")
public class CheckAccount extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public CheckAccount() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession sessionzxl = request.getSession();
AccountBean account = new AccountBean();
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
account.setPassword(pwd);
account.setUsername(username);
System.out.println("username :"+ username + " password :" + pwd);
if((username != null)&&(username.trim().equals("jspp"))) {
System.out.println("username is right!");
if((pwd != null)&&(pwd.trim().equals("1"))) {
System.out.println("success");
sessionzxl.setAttribute("account", account);
String login_suc = "success.jsp";
response.sendRedirect(login_suc);
return;
}
}
System.out.println("fail!");
String login_fail = "fail.jsp";
response.sendRedirect(login_fail);
return;
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response);
} }

登录的jsp页面如下Login.jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My JSP 'login.jsp' starting page</title>
</head>
<body>
This is my JSP page. <br>
<form action="login">
username:<input type="text" name="username"><br>
password:<input type="password" name="pwd"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

登录成功界面如下success.jsp:

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="com.ht.servlet.AccountBean"%> <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My JSP 'success.jsp' starting page</title>
</head>
<body>
<%AccountBean account = (AccountBean)session.getAttribute("account");%>
username:<%= account.getUsername()%> <br>
password:<%= account.getPassword() %> <br>
basePath: <%=basePath%><br>
path:<%=path%><br>
</body>
</html>

登录失败的jsp页面如下:fail.jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My JSP 'fail.jsp' starting page</title>
</head>
<body>
Login Failed! <br>
basePath: <%=basePath%><br>
path:<%=path%><br>
</body>
</html>

web.xml配置如下:

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ServletTest</display-name>
<welcome-file-list>
<welcome-file>Login.jsp</welcome-file>
</welcome-file-list> <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>CheckAccount</servlet-name>
<servlet-class>com.ht.servlet.CheckAccount</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckAccount</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>

描述一下上面运行过程:

在浏览器输入: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

Servlet+JSP例子的更多相关文章

  1. javaweb学习总结(二十二)——基于Servlet+JSP+JavaBean开发模式的用户登录注册

    一.Servlet+JSP+JavaBean开发模式(MVC)介绍 Servlet+JSP+JavaBean模式(MVC)适合开发复杂的web应用,在这种模式下,servlet负责处理用户请求,jsp ...

  2. servlet&jsp高级:第三部分

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  3. Servlet & JSP系列文章总结

    前言 谢谢大家的捧场,真心感谢我的阅读者. @all 下一期,重点在  数据结构和算法  ,希望给大家带来开心.已经出了几篇,大家爱读就是我的开心. Servlet & JSP系列总结 博客, ...

  4. JavaWeb学习 (二十一)————基于Servlet+JSP+JavaBean开发模式的用户登录注册

    一.Servlet+JSP+JavaBean开发模式(MVC)介绍 Servlet+JSP+JavaBean模式(MVC)适合开发复杂的web应用,在这种模式下,servlet负责处理用户请求,jsp ...

  5. 基于Servlet+JSP+JavaBean开发模式的用户登录注册

    http://www.cnblogs.com/xdp-gacl/p/3902537.html 一.Servlet+JSP+JavaBean开发模式(MVC)介绍 Servlet+JSP+JavaBea ...

  6. javaweb(二十二)——基于Servlet+JSP+JavaBean开发模式的用户登录注册

    一.Servlet+JSP+JavaBean开发模式(MVC)介绍 Servlet+JSP+JavaBean模式(MVC)适合开发复杂的web应用,在这种模式下,servlet负责处理用户请求,jsp ...

  7. servlet简单例子1

    servlet简单例子1 分类: servlet jsp xml2012-04-18 21:54 3646人阅读 评论(3) 收藏 举报 servletloginjspaction浏览器 LoginS ...

  8. JavaWeb实现用户登录注册功能实例代码(基于Servlet+JSP+JavaBean模式)

    一.Servlet+JSP+JavaBean开发模式(MVC)介绍 Servlet+JSP+JavaBean模式(MVC)适合开发复杂的web应用,在这种模式下,servlet负责处理用户请求,jsp ...

  9. NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config

    今天调试SSM框架项目后台JSOn接口,报出来一个让人迷惑的错误:NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config 上网查了一下别人的博 ...

随机推荐

  1. spark2.1源码分析4:spark-network-common模块的设计原理

    spark-network-common模块底层使用netty作为通讯框架,可以实现rpc消息.数据块和数据流的传输. Message类图: 所有request消息都是RequestMessage的子 ...

  2. numpy学习笔记(四)

    (1)NumPy - 矩阵库 NumPy 包包含一个 Matrix库numpy.matlib.此模块的函数返回矩阵而不是返回ndarray对象. matlib.empty()返回一个新矩阵,而不初始化 ...

  3. Java ---- 遍历链表(递归与非递归实现)

    package test; //前序遍历的递归实现与非递归实现 import java.util.Stack; public class Test { public static void main( ...

  4. django rest framework serializer中获取request中user方法

    views.py   serializer = self.get_serializer(data=request.data, context={'request': request}) seriali ...

  5. 通过阿里云ECS服务器公网ip访问tomcat,nginx

    一.概述 1.操作系统:centos7 2.安装nginx方法:https://www.cnblogs.com/boonya/p/7907999.html,亲测可用. 3.tomcat版本:apach ...

  6. Quick Search Articles in My Blog

    === Quickly Search Articles in My Blog: === 本文介绍了如何快速在主流搜索引擎搜索本专栏内文章的方法. Use Google's Search :  pres ...

  7. 【学习】数据规整化:清理、转换、合并、重塑(续)【pandas】

    @合并重叠数据 还有一种数据组合问题不能用简单的合并或连接运算来处理.比如说,你可能有索引全部或部分重叠的两个数据集 使用numpy的where函数,它用于表达一种矢量化的if - else a = ...

  8. Jmeter之数据库性能测试

    公司的**产品急待上线,但查询订单操作响应很慢,为了准确定位问题,特对几个大数据查询语句进行性能测试. 环境介绍:数据库用的MYSQL,采用分布式布置,本次单压测一台数据库服务器,查询待支付订单.待消 ...

  9. iOS Simulator version 11 or later is currently not supported.

    iOS Simulator version 11 or later is currently not supported.You can open Xcode > Preferences > ...

  10. C 语言能不能在头文件定义全局变量?

    可以,但一般不会将全局变量的定义写在头文件中. 因为如果多个 C 源文件都添加了头文件,很容易引起重定义的问题.这时候一般编译器都会提示:“multiple definition of... firs ...