Servlet+JSP例子
前面两节已经学习了什么是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例子的更多相关文章
- javaweb学习总结(二十二)——基于Servlet+JSP+JavaBean开发模式的用户登录注册
一.Servlet+JSP+JavaBean开发模式(MVC)介绍 Servlet+JSP+JavaBean模式(MVC)适合开发复杂的web应用,在这种模式下,servlet负责处理用户请求,jsp ...
- servlet&jsp高级:第三部分
声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...
- Servlet & JSP系列文章总结
前言 谢谢大家的捧场,真心感谢我的阅读者. @all 下一期,重点在 数据结构和算法 ,希望给大家带来开心.已经出了几篇,大家爱读就是我的开心. Servlet & JSP系列总结 博客, ...
- JavaWeb学习 (二十一)————基于Servlet+JSP+JavaBean开发模式的用户登录注册
一.Servlet+JSP+JavaBean开发模式(MVC)介绍 Servlet+JSP+JavaBean模式(MVC)适合开发复杂的web应用,在这种模式下,servlet负责处理用户请求,jsp ...
- 基于Servlet+JSP+JavaBean开发模式的用户登录注册
http://www.cnblogs.com/xdp-gacl/p/3902537.html 一.Servlet+JSP+JavaBean开发模式(MVC)介绍 Servlet+JSP+JavaBea ...
- javaweb(二十二)——基于Servlet+JSP+JavaBean开发模式的用户登录注册
一.Servlet+JSP+JavaBean开发模式(MVC)介绍 Servlet+JSP+JavaBean模式(MVC)适合开发复杂的web应用,在这种模式下,servlet负责处理用户请求,jsp ...
- servlet简单例子1
servlet简单例子1 分类: servlet jsp xml2012-04-18 21:54 3646人阅读 评论(3) 收藏 举报 servletloginjspaction浏览器 LoginS ...
- JavaWeb实现用户登录注册功能实例代码(基于Servlet+JSP+JavaBean模式)
一.Servlet+JSP+JavaBean开发模式(MVC)介绍 Servlet+JSP+JavaBean模式(MVC)适合开发复杂的web应用,在这种模式下,servlet负责处理用户请求,jsp ...
- NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config
今天调试SSM框架项目后台JSOn接口,报出来一个让人迷惑的错误:NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config 上网查了一下别人的博 ...
随机推荐
- Angular Beijing 发布
为了帮助 Angular 在国内的推广,申请了一个新的域名 www.ngbeijing.cn, 我将 Angular 相关的优秀文章集中在这个站点,欢迎大家访问. 刚刚转载了几篇优秀的文章. Ang ...
- Python数据类型的内置函数之list(列表)
Python数据类型内置函数 - str(字符串) - list(列表) - tuple(元组) - dict(字典) - set(收集) list(列表)的操作 - (append)在列表最后追加指 ...
- LayaAir疑难杂症之三:1.7版本click()、execCommand('copy')函数不生效
问题描述 在使用Laya1.7引擎开发H5游戏时,引入Js原生函数click( ),模拟一次点击事件,发现无效.在使用Laya1.7引擎开发H5游戏时,引入Js原生函数execCommand('cop ...
- 微信公众号openid处理的一些笔记
每个用户对每个公众号的OpenID是唯一的.对于不同公众号,同一用户的openid不同.如果公司有多个公众号,可以通过开放平台关联,这样同一用户,对同一个微信开放平台下的不同应用,unionid是相同 ...
- SecureCR 控制台输出行数设置
1.Options –>Session Options–>Terminal–>Emulation 2.在Scrollback输入你需要的最大显示行数,最大行数是128000,修改完全 ...
- 彻底搞懂Scrapy的中间件(一)
中间件是Scrapy里面的一个核心概念.使用中间件可以在爬虫的请求发起之前或者请求返回之后对数据进行定制化修改,从而开发出适应不同情况的爬虫. "中间件"这个中文名字和前面章节讲到 ...
- 从客户端出现小于等于公式符号引发检测到有潜在危险的Request.Form 值
可以在处理Post方法的Action添加一个特性:[ValidateInput(false)],这样处理就更加有针对性,提高页面的安全性. [HttpPost][ValidateInput(false ...
- endnote将参考文献导入word中
在endnote中将目标文献选中 然后返回word 将光标放到目标位置 个人网盘,endnoteX7资源 链接:https://pan.baidu.com/s/1lEocicehiPm1Ypkw768 ...
- sys.exit(main(sys.argv[1:]))
sys.argv sys.argv[]说白了就是一个从程序外部获取参数的桥梁. 首先我们需要import sys,sys是python3的一个标准库,也就是一个官方的模块.封装了一些系统的信息和接口, ...
- 获取用户登陆所在的ip及获取所属信息
package com.tcl.topsale.download.entity; public class GeoLocation { private String countryCode; priv ...