zoukankan      html  css  js  c++  java
  • 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

     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     @Override
    18     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     @Override
    28     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    29 
    30     }
    31 }

    web.xml 配置

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <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">
     3   <display-name>ServletTest</display-name>
     4   <welcome-file-list>
     5     <welcome-file>index.html</welcome-file>
     6     <welcome-file>index.htm</welcome-file>
     7     <welcome-file>index.jsp</welcome-file>
     8     <welcome-file>default.html</welcome-file>
     9     <welcome-file>default.htm</welcome-file>
    10     <welcome-file>default.jsp</welcome-file>
    11   </welcome-file-list>
    12   <servlet><servlet-name>ServletTest</servlet-name>
    13   <servlet-class>servlet.FirstServlet</servlet-class>
    14   </servlet>
    15   <servlet-mapping>
    16       <servlet-name>ServletTest</servlet-name>
    17       <url-pattern>/*</url-pattern>
    18   </servlet-mapping>
    19 </web-app>

    index.jsp

     1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
     2     pageEncoding="ISO-8859-1"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
     7 <title>Insert title here</title>
     8 </head>
     9 <body>
    10 <a href = "/ServletTest/FirstServlet">get this first servlet</a>
    11 </body>
    12 </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

     直接加例子:

     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 set
    14      */
    15     public void setUsername(String username) {
    16         this.username = username;
    17     }
    18     /**
    19      * @return the password
    20      */
    21     public String getPassword() {
    22         return password;
    23     }
    24     /**
    25      * @param password the password to set
    26      */
    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 AccountBean
    45  */
    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 stub
    56     }
    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 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <%
     5 String path = request.getContextPath();
     6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     7 %>
     8 
     9 <html>
    10 <head>
    11 <base href="<%=basePath%>">
    12 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    13 <title>My JSP 'login.jsp' starting page</title>
    14 </head>
    15 <body>
    16     This is my JSP page. <br>
    17     <form action="login">
    18     username:<input type="text" name="username"><br>
    19     password:<input type="password" name="pwd"><br>
    20     <input type="submit" value="Submit">
    21     </form>
    22 </body>
    23 </html>

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

     1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     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 <html>
    12 <head>
    13 <base href="<%=basePath%>">
    14 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    15 <title>My JSP 'success.jsp' starting page</title>
    16 </head>
    17 <body>
    18 <%AccountBean account = (AccountBean)session.getAttribute("account");%>
    19 username:<%= account.getUsername()%> <br>
    20 password:<%= account.getPassword() %> <br>
    21 basePath: <%=basePath%><br>
    22 path:<%=path%><br>
    23 </body>
    24 </html>

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

     1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <%
     5 String path = request.getContextPath();
     6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     7 %>
     8 
     9 <html>
    10 <head>
    11 <base href="<%=basePath%>">
    12 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    13 <title>My JSP 'fail.jsp' starting page</title>
    14 </head>
    15 <body>
    16     Login Failed! <br>
    17     basePath: <%=basePath%><br>
    18     path:<%=path%><br>
    19 </body>
    20 </html>

     web.xml配置如下:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <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">
     3   <display-name>ServletTest</display-name>
     4   <welcome-file-list>
     5     <welcome-file>Login.jsp</welcome-file>
     6   </welcome-file-list>
     7   
     8   <servlet>
     9        <description>This is the description of my J2EE component</description>
    10        <display-name>This is the display name of my J2EE component</display-name>
    11     <servlet-name>CheckAccount</servlet-name>
    12     <servlet-class>com.ht.servlet.CheckAccount</servlet-class>
    13   </servlet>
    14   <servlet-mapping>
    15     <servlet-name>CheckAccount</servlet-name>
    16     <url-pattern>/login</url-pattern>
    17   </servlet-mapping>
    18 </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

  • 相关阅读:
    iOS应用程序间共享数据(转)
    解决右滑返回手势和UIScrollView中的手势冲突(转)
    (转)iOS被开发者遗忘在角落的NSException-其实它很强大
    iOS 身份证最后一位是X,输入17位后自动补全X(转)
    springboot单机秒杀之queue队列
    springboot单机秒杀-aop+锁
    springbot单机秒杀,锁与事务之间的大坑
    spring-cloud学习之4.微服务请求打通
    spring-cloud学习之3.使用feign实现负载均衡
    spring-cloud学习之2.搭建请求网关spring-cloud-getway
  • 原文地址:https://www.cnblogs.com/beilou310/p/10471836.html
Copyright © 2011-2022 走看看