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 上网查了一下别人的博 ...
 
随机推荐
- 利用checkbox自带属性indeterminate构建含部分选中状态的树状结构
			
本来上个月就像发的,但是一直忙啊忙的也没时间整理,所以拖到了现在. 好吧上面这句就是废话,我就是感概下.下面是正文. 前段时间在弄一个轻量级的web项目,要构建一个树状结构目录,同时希望能把部分选中的 ...
 - Java Native调用C方法
			
1.通过JNI生成C调用的头文件:Java源码: import java.io.File; public class Test { static { System.load("D:" ...
 - frist Django app — 三、 View
			
前面已经说过了Django中model的一些用法,包括orm,以及操作的api,接下来就是搭一些简单的界面学习view——Django中的view.主要介绍以下两个方面: url映射 请求处理 模板文 ...
 - 页面跳转、URL直接访问限制
			
问题 URL控制是为了避免以下错误 当前页需要读取上一页缓存,但是当前页直接通过URL访问无法获得相应的缓存 当前页需要通过入口,清楚历史中保留的缓存,但是当前页直接通过URL访问没有清除 本质上是为 ...
 - java List<Map<String,Object>遍历的方法
			
public static void main(String[] args) { List<HashMap<String, Object>> list = new ArrayL ...
 - 微信小程序自定义组件实现
			
官方从 1.6.3 开始对于自定义组件这一块有了比较大的变动,首先比较明显的感觉就是文档比以前全多了,有木有!,现在小程序支持简洁的组件化编程,可以将页面内的功能模块抽象成自定义组件,以便在不同的页面 ...
 - P4136 谁能赢呢?
			
题目描述 小明和小红经常玩一个博弈游戏.给定一个n×n的棋盘,一个石头被放在棋盘的左上角.他们轮流移动石头.每一回合,选手只能把石头向上,下,左,右四个方向移动一格,并且要求移动到的格子之前不能被访问 ...
 - MySql TIMEDIFF做计算之后,后台报Illegal hour value '24' for java.sql.Time type 问题
			
页面需要显示这种格式:31:01:20 但是后台Springboot会提示Illegal hour value '24' for java.sql.Time type in value '24:00: ...
 - 腾讯基于Kubernetes的企业级容器云平台GaiaStack (转)
			
GaiaStack介绍 GaiaStack是腾讯基于Kubernetes打造的容器私有云平台.这里有几个关键词: 腾讯:GaiaStack可服务腾讯内部所有BG的业务: Kubernetes:Gaia ...
 - Java学习--枚举
			
枚举类型enum,地位等同于class,interface 使用enum定义的枚举类型,也是一种变量类型,可用于声明变量 枚举的一些特征 1.它不能有public的构造函数,这样做可以保证客户代码没有 ...