Servlet服务连接器。

Servlet(Server Applet)是Java Servlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序,具有独立于平台和协议的特性,主要功能在于交互式地浏览和生成数据,生成动态Web内容。

在Java Web工程中找到WebRoot,会发现里面有一个index.jsp网页。

(可以自己创建一个页面)注:常用 pageEncoding="UTF-8"

  • jsp 指令<%%> 脚本 表达式<%=%>

实现过程:

Servlet类:

package com.servlet;

import java.util.List;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.Impl.UserImpl;
import com.bao.UserInterface;
import com.pojo.User;

public class UserServlet extends HttpServlet {
	public UserServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response){
	}
	//接口:接收数据和跳转页面
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		System.out.println("dopost");
		//确定编码
		request.setCharacterEncoding("utf-8");
		//接值,参数必须和login中(用户名和密码)input标签中的name值一样
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println("用户名:"+username+",密码:"+password);
		User u = new User();
		u.setUsername(username);
		u.setPassword(password);
		
		//调用接口-多态 指向实现类
		UserInterface uif = new UserImpl();
		boolean bool = uif.loginSelect(u);
		
		
		//跳转页面 
		//转发 转向 : 服务器一次请求    最终浏览器地址停留在请求名上(刷新一次就向数据库添加一次数据)
		//重定向 : 服务器两次请求   最终浏览器地址停留在jsp页面上    容易丢值

		if(bool){

			List<User> list = uif.selectUserAll();
			//利用session 作用域向页面传值HttpSession
			request.getSession().setAttribute("userlist", list);
			//重定向
			response.sendRedirect(request.getContextPath()+"/userlist.jsp");
		}else{
			//转发
			request.getRequestDispatcher("/loginfail.jsp").forward(request, response);
		}

	}

	public void init() throws ServletException {
		// Put your code here
	}

}

实现类:

public boolean loginSelect(User u) {
		
		try {
			Connection conn = DBUtil.getConnetion();
			String sql = "select * from users where username=? and password=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, u.getUsername());
			ps.setString(2, u.getPassword());
			ResultSet rs = ps.executeQuery();
			if(rs.next()){
				return true;
			}else{
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

jsp页面:login.jsp(登录页面)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>login</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
		
  </head>
  
  <body>
    <div align="center">
     	 <!-- url-pattern中的路径 -->
    	<form action="servlet/UserServlet" method="post">
    		用户名:<input type = "text" name = "username"/><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    		密码:<input type = "password" name = "password"/>
    		<input type = "submit" name = "登录"/>
    	</form>
    </div>
  </body>
</html>

userlist.jsp:(点击登录以后跳转到这个页面,这个页面上显示出所有数据)

注意要写:<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix = "c" %>这一句

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'userlist.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
<body>
    <div align = "center">
    	<table border = "1" >
    		<tr>
    			<td>Id</td>
    			<td>用户名</td>
    			<td>密码</td>
    			<td>年龄</td>
    		</tr>
    		<!-- EL表达式  前台页面接值  :作用域 session(一次会话)  只要不关闭浏览器,信息就保存在session里
    		 request response page   (jsp内置对象)-->
    		<c:forEach items="${userlist}" var="list">
    		<tr>
    			<td>${list.id}</td>
    			<td>${list.username}</td>
    			<td>${list.password}</td>
    			<td>${list.age}</td>
    		</tr>
    		</c:forEach>
    	</table>
    </div>
  </body>
</html>

web.xml:(在WebRoot->WEB-INF中)主要是来查找url-pattern写进login的action

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <servlet>
    <servlet-name>UserServlet</servlet-name>
    <servlet-class>com.servlet.UserServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>/servlet/UserServlet</url-pattern>
  </servlet-mapping>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

流程:

  • 前台用户填写信息
  • 后台接收登录信息 servlet
  • 利用接取到的数据进行数据库查询 (用户点登陆->通过action路径到web.xml->找到servlet-mapping标签,在里面找到servlet-name
  • 在servlet中找到和刚才那个servlet-name一样的->根据class路径找到Servlet类,进行数据接收)

一系列完整页面:

1.web.xml

(主要是可以找到其中各种Servlet类的地址,应用于form action中)

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <servlet>
    <servlet-name>UserServlet</servlet-name>
    <servlet-class>com.servlet.UserServlet</servlet-class>
  </servlet>
  <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>UserAddServlet</servlet-name>
    <servlet-class>com.servlet.UserAddServlet</servlet-class>
  </servlet>
  <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>UserUpdateServlet</servlet-name>
    <servlet-class>com.servlet.UserUpdateServlet</servlet-class>
  </servlet>
  <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>UserUpdate2Servlet</servlet-name>
    <servlet-class>com.servlet.UserUpdate2Servlet</servlet-class>
  </servlet>
  <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>UserDeleteServlet</servlet-name>
    <servlet-class>com.servlet.UserDeleteServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>/servlet/UserServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>UserAddServlet</servlet-name>
    <url-pattern>/servlet/UserAddServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>UserUpdateServlet</servlet-name>
    <url-pattern>/servlet/UserUpdateServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>UserUpdate2Servlet</servlet-name>
    <url-pattern>/servlet/UserUpdate2Servlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>UserDeleteServlet</servlet-name>
    <url-pattern>/servlet/UserDeleteServlet</url-pattern>
  </servlet-mapping>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
2.主要页面
【login.jsp】
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>login</title>
 
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	
  </head>
  
  <body>
    <div align="center">
     	 <!-- url-pattern中的路径 -->
    	<form action="servlet/UserServlet" method="post">
    		用户名:<input type = "text" name = "username"/><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    		密码:<input type = "password" name = "password"/>
    		<input type = "submit" name = "登录"/>
    		
    	</form>
    </div>
  </body>
</html>
【userlist.jsp】

(这个页面主要是用来显示数据信息,然后可以进行编辑和删除)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'userlist.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
<body>
    <div align = "center">
    	<table border = "1" >
    		<tr>
    			<td>Id</td>
    			<td>用户名</td>
    			<td>密码</td>
    			<td>年龄</td>
    			<td>编辑</td>
    			<td>删除</td>
    		</tr>
    		<!-- EL表达式  前台页面接值  :作用域 session(一次会话)  只要不关闭浏览器,信息就保存在session里
    		 request response page   (jsp内置对象)-->
    		<c:forEach items="${userlist}" var="list">
    		<tr>
    			<td>${list.id}</td>
    			<td>${list.username}</td>
    			<td>${list.password}</td>
    			<td>${list.age}</td>
    			<!-- get方法提交 -->
    			<td><a href="servlet/UserUpdateServlet?id=${list.id}">编辑</a></td>
    			<td><a href="servlet/UserDeleteServlet?id=${list.id}">删除</a></td>
    		</tr>
    		</c:forEach>
    	</table>
    	<a href="useradd.jsp">增加</a>
    </div>
  </body>
</html>
【update.jsp】

(这个页面是修改页面,需要把数据都显示出来,然后修改后进行提交。)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'update.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    <div align="center">
     	 <!-- url-pattern中的路径 -->
    	<form action="servlet/UserUpdate2Servlet" method="post">
    	<input type="hidden" name = "id" value="${user.id}"/>
    		用户名:<input type = "text" name = "username" value="${user.username}"/><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    		密码:<input type = "text" name = "password" value="${user.password}"/><br>
    		年龄:<input type = "text" name="age" value="${user.age}"/>
    		<input type = "submit" name = "提交"/>
    		
    	</form>
    </div>
  </body>
</html>
【useradd.jsp】

(这个是增加一条数据的页面)

(其实和login几乎一模一样,除了对应的Servlet位置不同)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'useradd.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    <div align="center">
     	 <!-- url-pattern中的路径 -->
    	<form action="servlet/UserAddServlet" method="post">
    		用户名:<input type = "text" name = "username"/><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    		密码:<input type = "password" name = "password"/><br>
    		年龄:<input type = "text" name="age"/>
    		<input type = "submit" name = "提交"/>
    		
    	</form>
    </div>
  </body>
</html>
3.Servlet类

仅贴出主要部分代码,有关于User类和UserInterface和UserImpl在之前的JDBC中有写,这里不再给出代码。

【UserServlet】
public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	
	System.out.println("dopost");
	//确定编码
	request.setCharacterEncoding("utf-8");
	//接值,参数必须和login中(用户名和密码)input标签中的name值一样
	String username = request.getParameter("username");
	String password = request.getParameter("password");
	System.out.println("用户名:"+username+",密码:"+password);
	User u = new User();
	u.setUsername(username);
	u.setPassword(password);
	
	//调用接口-多态 指向实现类
	UserInterface uif = new UserImpl();
	boolean bool = uif.loginSelect(u);

	if(bool){

		List<User> list = uif.selectUserAll();
		//利用session 作用域向页面传值HttpSession
		request.getSession().setAttribute("userlist", list);
		//重定向
		response.sendRedirect(request.getContextPath()+"/userlist.jsp");
	}else{
		//转发
		request.getRequestDispatcher("/loginfail.jsp").forward(request, response);
	}

}
【UserAddServlet】
public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//字符编码
		request.setCharacterEncoding("utf-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		int age = Integer.parseInt(request.getParameter("age"));
		
		User user = new User();
		user.setAge(age);
		user.setPassword(password);
		user.setUsername(username);
		
		UserInterface uif = new UserImpl();
		uif.addUser(user);
		
		List<User> list = uif.selectUserAll();
		//利用session 作用域向页面传值HttpSession
		request.getSession().setAttribute("userlist", list);
		//重定向
		response.sendRedirect(request.getContextPath()+"/userlist.jsp");
		
	}
【UserUpdateServlet】

注:这里是用的doGet方法,至于doGet和doPost有什么不同:(直接参考:https://www.cnblogs.com/alsf/p/9133951.html)

1.当form框里面的method为get时,执行doGet方法
当form框里面的method为post时,执行doPost方法

2.数据传送方式:

get方式:表单数据存放在URL地址后面。所有get方式提交时HTTP中没有消息体。
post方式:表单数据存放在HTTP协议的消息体中以实体的方式传送到服务器。

3.get是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到

post是通过HTTP post机制,将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址。用户看不到这个过程

4.GET方式:数据量长度有限制,一般不超过2kb。因为是参数传递,且在地址栏中,故数据量有限制。

POST方式:适合大规模的数据传送。因为是以实体的方式传送的。

5.GET方式:安全性差。因为是直接将数据显示在地址栏中,浏览器有缓冲,可记录用户信息。所以安全性低。
POST方式:安全性高。因为post方式提交数据时是采用的HTTP post机制,是将表单中的字段与值放置在HTTP HEADER内一起传送到ACTION所指的URL中,用户是看不见的。

6.在做数据查询时,建议用Get方式;而在做数据添加、修改或删除时,建议用Post方式。

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		int id = Integer.parseInt(request.getParameter("id"));
		UserInterface uif = new UserImpl();
		User user = uif.selectUserById(id);
		request.getSession().setAttribute("user", user);
		response.sendRedirect(request.getContextPath()+"/update.jsp");
	}
【UserUpdate2Servlet】

为什么有两个update呢?第一个是userlist超链接“编辑”所使用到的Servlet,第二个是表单提交以后所使用的到的Servlet。

两个超链接“编辑”和“删除”对应的Servlet是doGet方法,其余为doPost。

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		int id = Integer.parseInt(request.getParameter("id"));
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		int age = Integer.parseInt(request.getParameter("age"));
		
		User user = new User();
		user.setAge(age);
		user.setId(id);
		user.setUsername(username);
		user.setPassword(password);
		
		UserInterface uif = new UserImpl();
		uif.updateUser(user);
		
		List<User> list = uif.selectUserAll();
		//利用session 作用域向页面传值HttpSession
		request.getSession().setAttribute("userlist", list);
		//重定向
		response.sendRedirect(request.getContextPath()+"/userlist.jsp");
	}
【UserDeleteServlet】
public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("doGet");
		request.setCharacterEncoding("utf-8");
		int id = Integer.parseInt(request.getParameter("id"));
		UserInterface uif = new UserImpl();
		
		uif.deleteUser(id);
		
		List<User> list = uif.selectUserAll();
		//利用session 作用域向页面传值HttpSession
		request.getSession().setAttribute("userlist", list);
		//重定向
		response.sendRedirect(request.getContextPath()+"/userlist.jsp");
	}

本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!

java笔记-异常 上一篇
JDBC基本操作-2 下一篇