C/S(client server)架构
B/S(client server)架构 browser server
Java Web是指所有通过 Java 语言编写,可以通过浏览器访问的程序的总称。
JavaWeb是基于请求和响应来开发的。
请求(request)是指客户端给服务器发送数据。
响应(response)是指服务器给客户端回传数据。
web 资源按实现的技术和呈现的效果的不同,分为静态资源和动态资源两种。
静态资源:html、css、js、txt、jpg 图片、mp4 视频 ,
动态资源:jsp 页面、Servlet 程序
tomcat:由 Apache 组织提供的一种 Web 服务器,提供对 JSP 和 Servlet 的支持。它是一种轻量级的 Java Web 容器(服务器),也是当前应用最广的 Java Web 服务器(免费)。
Jboss:是一个遵从 JavaEE 规范的、开放源代码的、纯 Java 的 EJB 服务器,它支持所有的 JavaEE 规范(免费)。
GlassFish:由 Oracle 公司开发的一款 Java Web 服务器,是一款强健的商业服务器,达到产品级质量(应用很少)。
Resin:是 CAUCHO 公司的产品,是一个非常流行的服务器,对 Servlet 和 JSP 提供了良好的支持,性能也比较优良,resin 自身采用Java 语言开发(收费,应用比较多)。
WebLogic:是 Oracle 公司的产品,是目前应用最广泛的 Web 服务器,支持 JavaEE 规范,而且不断的完善以适应新的开发要求,适合大型项目(收费,用的不多,适合大公司)。
登录官网地址:https://www.apache.org
点击“Tomcat”
选择对应版本点击
选择要下载的类型
下载完成后直接解压即可。
bin 存放 Tomcat 服务器的可执行程序
conf 存放 Tocmat 服务器的配置文件
lib 存放 Tomcat 服务器的 jar 包
logs 存放 Tomcat 服务器运行时输出的日记信息
temp 存放 Tomcat 运行时产生的临时数据
webapps 存放部署的 Web 工程。
work Tomcat 工作时的目录,用来存放 Tomcat 运行时 JSP 翻译为 Servlet 的源码,和 Session 钝化的目录。
找到 Tomcat 目录下的 bin 目录下的 startup.bat 文件,双击。
测试 Tomcat 服务器启动成功:打开浏览器,在浏览器地址栏中输入以下地址测试:
1、http://localhost:8080
2、http://127.0.0.1:8080
3、http://真实 ip:8080
当出现如下界面,说明 Tomcat 服务器启动成功。
常见的启动失败的情况:双击 startup.bat 文件,会出现一个小黑窗口一闪而过。原因基本上都是因为没有配置好 JAVA_HOME 环境变量。
配置JAVA_HOME环境变量
一:JAVA_HOME 必须全大写。
二:JAVA_HOME 中间必须是下划线,不是减号-
三:JAVA_HOME 配置的路径只需要配置到 JDK 的安装目录即可。不需要带上 bin 目录。
1、打开命令行
2、cd 到 Tomcat 的 bin 目录下
3、敲入启动命令:
startup.bat
catalina run
方式一:点击 tomcat 服务器窗口的 “x” 关闭按钮
方式二:把 Tomcat 服务器窗口置为当前窗口,然后按快捷键 Ctrl+C
方式三:双击 Tomcat 的 bin 目录下的 shutdown.bat
MySQL 默认的端口号是:3306
Tomcat 默认的端口号是:8080
找到 Tomcat 目录下的 conf 目录,找到 server.xml 配置文件。
平时上百度:http://www.baidu.com:80
HTTP 协议默认的端口号是:80
把 web 工程的目录拷贝到 Tomcat 的 webapps 目录下即可。
访问 Tomcat 下的 web 工程:只需要在浏览器中输入访问地址,格式如下:
http://ip:port/工程名/目录下/文件名
找到 Tomcat 下的 conf 目录\Catalina\localhost\ 下,创建如下的配置文件:
abc.xml 配置文件内容如下:
Context 表示一个工程上下文
path 表示工程的访问路径:/abc
docBase 表示你的工程目录在哪里
访问这个工程的路径如下:http://ip:port/abc/ 就表示访问 E:\book 目录.
手拖 html 页面到浏览器和在浏览器中输入http://ip:端口号/工程名/的区别
手托 html 页面的原理:
输入访问地址访问的原因:
在浏览器地址栏中输入访问地址如下:
http://ip:port/
没有工程名的时候,默认访问的是 ROOT 工程。
当我们在浏览器地址栏中输入的访问地址如下:
http://ip:port/工程名/
没有资源名,默认访问 index.html 页面
操作的菜单如下:File->Settings->Build, Execution, Deployment->Application Servers
创建模块时,会自动加载已经配置的Tomcat。
File->New->Module
选择“Java Enterprise”
点击“Next”
点击“Finish”
建议修改 web 工程对应的 Tomcat 运行实例名称
确认 Tomcat 实例中有要部署运行的 web 工程模块
还可以修改 Tomcat 实例启动后默认的访问地址:
public interface HttpServletRequest
extends ServletRequest
请求对象。
javax.servlet
Interface ServletRequest
All Known Subinterfaces:
HttpServletRequest
int getRemotePort()
String getContextPath()
String getRemoteAddr() 在ServletRequest接口中。
StringBuffer getRequestURL()
String getRequestURI()
Enumeration getHeaderNames()
String getHeader(String name)
Cookie[] getCookies()
HttpSession getSession()
String getMethod()
String getParameter(String name) 在ServletRequest接口中。
String[] getParameterValues(String name) 在ServletRequest接口中。
乱码解决:
void setCharacterEncoding(String env) throws UnsupportedEncodingException 在ServletRequest接口中。
void setAttribute(String name, Object o) 在ServletRequest接口中。
Object getAttribute(String name) 在ServletRequest接口中。
void removeAttribute(String name) 在ServletRequest接口中。 移除指定属性。
package com.oracle.one.servlet.simple;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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("/simple/three")
public class TestServletDispatcher00002 extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
httpServletRequest.setCharacterEncoding("utf-8");
httpServletRequest.setAttribute("name", "宋江");
httpServletRequest.setAttribute("gender", "男");
/*
* 转发不会改变浏览器地址栏中的显示内容。
* 转发属于项目内的跳转。
* */
String uri = "/simple/fourth";
RequestDispatcher requestDispatcher = httpServletRequest.getRequestDispatcher(uri);
requestDispatcher.forward(httpServletRequest, httpServletResponse);
//简化写法
//httpServletRequest.getRequestDispatcher(uri).forward(httpServletRequest, httpServletResponse);
}
@Override
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
doPost(httpServletRequest, httpServletResponse);
}
}
package com.oracle.one.servlet.simple;
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;
@WebServlet("/simple/fourth")
public class TestServletDispatcher00003 extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
httpServletRequest.setCharacterEncoding("utf-8");
System.out.println("转发到了这里。");
String name = (String)httpServletRequest.getAttribute("name");
String gender = (String)httpServletRequest.getAttribute("gender");
System.out.println("姓名:" + name);
System.out.println("性别:" + gender);
}
@Override
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
doGet(httpServletRequest, httpServletResponse);
}
}
javax.servlet.http
Interface HttpServletResponse
All Superinterfaces:
ServletResponse
响应对象
PrintWriter getWriter() throws IOException 在ServletResponse接口中
ServletOutputStream getOutputStream() throws IOException 在ServletResponse接口中
package com.oracle.one.servlet.simple.http_servlet.response;
import java.io.IOException;
//import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "TestHttpServletResponse00000", urlPatterns = { "/http_servelt_response/one" })
public class TestServlet00000 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
httpServletRequest.setCharacterEncoding("utf-8");
httpServletResponse.setContentType("text/html;charset=utf-8");
/*PrintWriter printWriter = httpServletResponse.getWriter();
printWriter.write("这是HttpServletResponse响应对象输出的文本内容。");
//printWriter.write("这是HttpServletResponse响应对象输出的文本内容。
");
printWriter.flush();
printWriter.close();*/
ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
servletOutputStream.write("哈哈哈".getBytes());
servletOutputStream.flush();
servletOutputStream.close();
}
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
doGet(httpServletRequest, httpServletResponse);
}
}
void sendRedirect(String location) throws IOException
package com.oracle.one.servlet.simple.http_servlet.response;
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;
@WebServlet(name = "TestServlet00001", urlPatterns = { "/simple/servlet_response/two" })
public class TestServlet00001 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
//重定向
httpServletResponse.sendRedirect("/00000_request/http_servelt_response/one");
}
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
doGet(httpServletRequest, httpServletResponse);
}
}
package com.oracle.one.servlet.simple.request_dispatcher_send_redirect;
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;
@WebServlet("/servlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
httpServletRequest.setCharacterEncoding("utf-8");
httpServletResponse.setContentType("text/html;charset=utf-8");
httpServletRequest.setAttribute("name", "宋江");
httpServletRequest.setAttribute("gender", "男");
httpServletRequest.getRequestDispatcher("/servlet1").forward(httpServletRequest, httpServletResponse);
//httpServletResponse.sendRedirect("/00000_request/servlet1");
}
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
doGet(httpServletRequest, httpServletResponse);
}
}
package com.oracle.one.servlet.simple.request_dispatcher_send_redirect;
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;
@WebServlet("/servlet1")
public class TestServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
httpServletRequest.setCharacterEncoding("utf-8");
httpServletResponse.setContentType("text/html;charset=utf-8");
String name = (String)httpServletRequest.getAttribute("name");
String gender = (String)httpServletRequest.getAttribute("gender");
System.out.println(name + "\t" + gender);
}
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
doGet(httpServletRequest, httpServletResponse);
}
}
javax.servlet
Interface ServletConfig
All Known Implementing Classes:
GenericServlet, HttpServlet
public interface ServletConfig
配置信息
String getInitParameter(String name)
package com.oracle.one.servlet.servlet_config;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet00000 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
String name = servletConfig.getInitParameter("name");
String gender = servletConfig.getInitParameter("gender");
System.out.println(name + "\t" + gender);
}
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
System.out.println("来了");
ServletConfig servletConfig = getServletConfig();
String name = servletConfig.getInitParameter("name");
String gender = servletConfig.getInitParameter("gender");
System.out.println("doGet()方法中:" + name + "\t" + gender);
}
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
doGet(httpServletRequest, httpServletResponse);
}
}
<servlet>
<servlet-name>MyHttpServletservlet-name>
<servlet-class>com.oracle.one.servlet.servlet_config.TestServlet00000servlet-class>
<init-param>
<param-name>nameparam-name>
<param-value>宋江param-value>
init-param>
<init-param>
<param-name>genderparam-name>
<param-value>男param-value>
init-param>
servlet>
<servlet-mapping>
<servlet-name>MyHttpServletservlet-name>
<url-pattern>/servlet_config/test_servlet00000url-pattern>
servlet-mapping>
javax.servlet
Interface ServletContext
public interface ServletContext
共享上下文对象
String getInitParameter(String name)
void setAttribute(String name, Object object)
Object getAttribute(String name)
package com.oracle.one.servlet.servlet_context;
import java.io.IOException;
import javax.servlet.ServletContext;
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("/servlet_context/my_servlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void init() throws ServletException {
System.out.println("初始化");
}
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
ServletContext servletContext = getServletContext();
String ip = servletContext.getInitParameter("ip");
String port = servletContext.getInitParameter("port");
System.out.println("ip:" + ip + "\tport:" + port);
servletContext.setAttribute("name", "宋江");
Object name = servletContext.getAttribute("name");
System.out.println(name);
}
}
package com.oracle.one.servlet.servlet_context;
import java.io.IOException;
import javax.servlet.ServletContext;
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("/servlet_context/my_servlet1")
public class MyServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
ServletContext servletContext = getServletContext();
Object name = servletContext.getAttribute("name");
System.out.println(name);
}
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
doGet(httpServletRequest, httpServletResponse);
}
}
<context-param>
<param-name>ipparam-name>
<param-value>127.0.0.1param-value>
context-param>
<context-param>
<param-name>portparam-name>
<param-value>1234param-value>
context-param>
javax.servlet.http
Class Cookie
java.lang.Object
javax.servlet.http.Cookie
All Implemented Interfaces:
Serializable, Cloneable
public Cookie(String name, String value)
public void setMaxAge(int expiry)
public void setDomain(String domain)
public void setPath(String uri)
package com.oracle.one.servlet.cookie;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/cookie/my_servlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
httpServletRequest.setCharacterEncoding("utf-8");
httpServletResponse.setContentType("text/html;charset=utf-8");
//第一次用户发起请求,将此相关数据存放至Cookie,并将Cookie响应到浏览器中。
String name = "宋江";
Cookie cookie = new Cookie("username", name); //设置cookie名称与内容。
cookie.setDomain("localhost"); //设置域名
cookie.setPath("/00000_request/cookie/my_servlet1"); //设置路径
cookie.setMaxAge(60*60*24); //设置有效期:单位秒
httpServletResponse.addCookie(cookie);
PrintWriter printWriter = httpServletResponse.getWriter();
printWriter.write("请求第一个Servlet成功,带回来了一个Cookie。
点我查看
");
System.out.println("解析到的Cookie:" + cookie.getName() + ":" + cookie.getValue());
printWriter.flush();
printWriter.close();
}
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
doGet(httpServletRequest, httpServletResponse);
}
}
package com.oracle.one.servlet.cookie;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/cookie/my_servlet1")
public class MyServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
httpServletRequest.setCharacterEncoding("utf-8");
httpServletResponse.setContentType("text/html;charset=utf-8");
Cookie[] cookies = httpServletRequest.getCookies();
PrintWriter printWriter = httpServletResponse.getWriter();
if(cookies != null) {
for(Cookie cookie : cookies) {
printWriter.write("解析到的Cookie:" + cookie.getName() + ":" + cookie.getValue());
printWriter.flush();
}
}else {
printWriter.write("没有任何Cookie。");
}
printWriter.close();
}
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
doGet(httpServletRequest, httpServletResponse);
}
}
package com.oracle.one.servlet.session;
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;
import javax.servlet.http.HttpSession;
@WebServlet("/session/my_servlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
httpServletRequest.setCharacterEncoding("utf-8");
httpServletResponse.setContentType("text/html;charset=utf-8");
HttpSession httpSession = httpServletRequest.getSession(); //获取客户端和服务端之间的连接会话,如果没有则新建一个会话。
//HttpSession httpSession1 = httpServletRequest.getSession(false); //获取客户端和服务端之间的连接会话,如果没有则根据参数决定:true:新建会话,false:不新建会话,返回null
System.out.println("客户端与服务端连接了一个会话:" + httpSession);
//httpSession.setMaxInactiveInterval(60*5); //最大活跃周期,参数为秒。
//借助会话对象,缓存数据。
httpSession.setAttribute("id", "001");
httpSession.setAttribute("age", 20);
//清除HttpSession中指定的数据。
//httpSession.removeAttribute("id");
//清除HttpSession
//httpSession.invalidate();
PrintWriter printWriter = httpServletResponse.getWriter();
printWriter.write("HttpSession会话创建成功!
");
printWriter.flush();
printWriter.close();
}
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
doGet(httpServletRequest, httpServletResponse);
}
}
package com.oracle.one.servlet.session;
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;
import javax.servlet.http.HttpSession;
@WebServlet("/session/my_servlet1")
public class MyServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
httpServletRequest.setCharacterEncoding("utf-8");
httpServletResponse.setContentType("text/html;charset=utf-8");
HttpSession httpSession = httpServletRequest.getSession();
String id = (String)httpSession.getAttribute("id");
Integer age = (Integer)httpSession.getAttribute("age");
System.out.println(id);
System.out.println(age.toString());
PrintWriter printWriter = httpServletResponse.getWriter();
if(id != null & age != null ) {
printWriter.write("学生学号:"
+ id + "
学生年龄:" + age + "");
printWriter.flush();
}else {
printWriter.write("没有拿到HttpSession数据。
");
printWriter.flush();
}
printWriter.close();
}
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
doGet(httpServletRequest, httpServletResponse);
}
}
void invalidate()
void setAttribute(String name, Object value)
Object getAttribute(String name)
void removeAttribute(String name)
void setMaxInactiveInterval(int interval)
也可以在web.xml文件中设置。
<session-config>
<session-timeout>5session-timeout>
session-config>
首页
DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录页面title>
head>
<body>
<form action="http://localhost:8080/00000_request/session/login_case/login_servlet" method="post">
<p>
账号:<input type="text" name="username"/>
p>
<p>
密码:<input type="text" name="password"/>
p>
<p>
<input type="submit" value="提交"/>
p>
form>
body>
html>
首页Servlet
package com.oracle.one.servlet.session.login_case;
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;
import javax.servlet.http.HttpSession;
@WebServlet("/session/login_case/index_servlet")
public class IndexServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
httpServletRequest.setCharacterEncoding("utf-8");
httpServletResponse.setContentType("text/html;charset=utf-8");
//获取Session中的缓存身份。
HttpSession httpSession = httpServletRequest.getSession();
String username = (String)httpSession.getAttribute("username");
PrintWriter printWriter = httpServletResponse.getWriter();
//如果不为空,表示之前登录成功过,提示欢迎。
if(username != null) {
printWriter.write("欢迎:"
+ username + ",来到后台系统。退出");
printWriter.flush();
}else {
//如果为空,则表示未登录成功,给予提示,并提供链接跳回登录页面。
printWriter.write("请先登录!点击跳回登录页面
");
printWriter.flush();
}
printWriter.close();
}
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
doGet(httpServletRequest, httpServletResponse);
}
}
登录Servlet
package com.oracle.one.servlet.session.login_case;
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;
import javax.servlet.http.HttpSession;
@WebServlet("/session/login_case/login_servlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
httpServletRequest.setCharacterEncoding("utf-8");
httpServletResponse.setContentType("text/html;charset=utf-8");
//获取账号、密码
String username = httpServletRequest.getParameter("username");
String password = httpServletRequest.getParameter("password");
String username1 = "admin";
String password1 = "123456";
//检查账号、密码是否正确。
if(username.equals(username1) && password.equals(password1)) {
//账号、密码正确;借助Session存储登录用户的身份,打开系统后台首页。
HttpSession httpSession = httpServletRequest.getSession();
httpSession.setAttribute("username", username);
String url = httpServletRequest.getContextPath();
System.out.println("获取的Java Project名称:" + url);
//重定向
httpServletResponse.sendRedirect(url + "/session/login_case/index_servlet");
}else {
//错误:响应错误提示信息,并跳转至登录页面。
PrintWriter printWriter = httpServletResponse.getWriter();
printWriter.write("登录失败,请重新登录!点击跳回登录页面
");
printWriter.flush();
printWriter.close();
}
}
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
doGet(httpServletRequest, httpServletResponse);
}
}
退出Servlet
package com.oracle.one.servlet.session.login_case;
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;
@WebServlet("/session/login_case/logout_servlet")
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
//设置HttpSession会话的登录身份失效
HttpSession httpSession = httpServletRequest.getSession();
httpSession.invalidate();
//重定向至登录页面。
httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/page/00000_servlet/00002_session_login_case/login.html");
}
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
doGet(httpServletRequest, httpServletResponse);
}
}
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML">
<html>
<head>
<title>JSP pagetitle>
head>
<body>
<a href="http://localhost:8080/00000_request/page/00000_servlet/00001/b.jsp?id=5">点击a> <br>
<a href="/00000_request/page/00000_servlet/00001/b.jsp?id=6">点击a> <br>
body>
html>
<%@ page language="java" pageEncoding="UTF-8"%>
DOCTYPE HTML>
<html>
<head>
<title>JSP pagetitle>
head>
<body>
id=${param.id}
body>
html>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title heretitle>
head>
<body>
<%-- JSP脚本注释 --%>
<%
for(int i=0; i<5; i++){
System.out.println("i=" + i);
out.write("<h2>测试标题。h2>" + i);
}
%>
<%
for(int i=0; i<5; i++){
out.write("<h3>测试JSP访问。h3>" + i);
%>
<%
}
%>
<hr>
<h1>测试JSP访问。h1>
<%!
public String name = "宋江";
public void test00000(){
System.out.print("name:" + name);
}
%>
<%
test00000();
%>
<hr>
<%-- 以下的输出脚本相当于service方法内的out.write();输出。 --%>
<%= name %>
<%= 200 %>
<%= "卢俊义" %>
body>
html>
<%@ page language="java"
contentType="text/html; charset=utf-8"
pageEncoding="utf-8"
import="java.util.*, java.io.*" %>
<%@ include file="00000_jsp.jsp" %>
DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title heretitle>
head>
<body>
<%
List<String> list = new ArrayList<>();
list.add("宋江");
list.add("卢俊义");
list.add("吴用");
list.forEach(e -> System.out.println(e));
File file = new File("1.txt");
%>
<jsp:include page="00000_jsp.jsp"/>
body>
html>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"
isErrorPage="true"%>
DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title heretitle>
head>
<body>
<%
System.out.println(request); //请求对象
System.out.println(response); //响应对象
System.out.println(page); //当前页面对象
System.out.println(pageContext); //当前JSP页面上、下文对象。
System.out.println(application); //ServletContext上、下文全局共享数据
System.out.println(session); //会话对象
System.out.println(config); //当前Servlet程序的配置对象。
System.out.println(out); //当前页面的输出流。
System.out.println(exception); //只有当前JSP成为了异常处理代码块,才能识别到该异常对象。
%>
<%
pageContext.setAttribute("name", "林冲");
String name = (String)pageContext.getAttribute("name");
System.out.println("name=" + name);
//pageContext可以控制其他对象,实现自定义属性值存储:可以操作request中的属性。
pageContext.setAttribute("name1", "宋江", PageContext.REQUEST_SCOPE); //等同于request.setAttribute("name1", "宋江");
pageContext.setAttribute("name2", "宋江", PageContext.SESSION_SCOPE); //等同于session.setAttribute("name1", "宋江");
pageContext.setAttribute("name3", "宋江", PageContext.APPLICATION_SCOPE); //等同于servletContext.setAttribute("name1", "宋江");
pageContext.setAttribute("name4", "宋江", PageContext.PAGE_SCOPE); //等同于pageContext.setAttribute("name1", "宋江"); 当前页面中
%>
body>
html>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"
import="java.util.*, com.oracle.one.jsp.entity.Dog"
%>
DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>EL表达式title>
head>
<body>
<%
pageContext.setAttribute("id", "001");
request.setAttribute("name", "宋江");
session.setAttribute("age", 23);
application.setAttribute("gender", "男");
%>
${pageScope.id} <br>
${requestScope.name} <br>
${sessionScope.age} <br>
${applicationScope.gender} <br>
${id}
<hr>
<%
int number = 1;
int[] array = new int[]{1, 2, 3, 4, 5};
List<String> names = new ArrayList<>();
names.add("宋江");
names.add("卢俊义");
names.add("吴用");
names.add("公孙胜");
Map<String, String> map = new HashMap<>();
map.put("name", "潘金莲");
map.put("name1", "潘巧云");
map.put("name2", "阎婆惜");
Dog dog = new Dog("旺财", 2);
pageContext.setAttribute("number", number);
pageContext.setAttribute("array", array);
pageContext.setAttribute("names", names);
pageContext.setAttribute("map", map);
pageContext.setAttribute("dog", dog);
%>
${number} <br>
${array} <br>
${names} <br>
${map} <br>
${dog} <br>
<hr>
${names[0]} - ${names[1]} <br>
${map["name"]} - ${map['name1']} <br>
${dog.name} - ${dog.age}
<hr>
${pageContext.request.contextPath}
body>
html>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
DOCTYPE html>
<html>
<head>
<meta charset="uft-8">
<title>EL运算符title>
head>
<body>
<%
pageContext.setAttribute("money", 9);
pageContext.setAttribute("name", "宋江");
%>
${money+2} <br>
${money-2} <br>
${money*2} <br>
${money/2} <br>
${money>10} <br>
${money>=10} <br>
${money<10} <br>
${money<=10} <br>
${money==10} <br>
${money eq 100} <br>
${money>=10?"大于":"小于"} <br>
${money>=10 and money<=5} <br>
${money>=10 or money<=5} <br>
${empty money} <br>
${empty emoney1} <br>
${not (money>10)}
body>
html>
<%@ page language="java" contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<title>JSTL内置函数fntitle>
head>
<body>
<%
pageContext.setAttribute("name", "宋江");
pageContext.setAttribute("name1", " hi,卢俊义。");
%>
${name} <br>
${fn:length(name)} <br>
${fn:indexOf(name, "江")} <br>
${fn:startsWith(name, "宋")} <br>
${fn:substring(name1, 0, 2)} <br>
${fn:toLowerCase(name1)} <br>
${fn:toUpperCase(name1)} <br>
${fn:trim(name1)}
body>
html>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"
import="com.oracle.one.jsp.entity.Dog, java.util.*"
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>c_outtitle>
head>
<body>
<%
Dog dog = new Dog("宋江", 50);
request.setAttribute("dog", dog);
List<String> list = new ArrayList<>();
list.add("卢俊义");
list.add("吴用");
list.add("公孙胜");
request.setAttribute("list", list);
Map<String, String> map = new HashMap<>();
map.put("name", "潘金莲");
map.put("name1", "潘巧云");
map.put("name2", "阎婆惜");
request.setAttribute("map", map);
int[] array = new int[]{1, 2, 3};
request.setAttribute("array", array);
%>
${dog.name}
=
${dog.age}
<br>
<c:out value="${dog.name}"/>
=
<c:out value="${dog.age * 3}"/>
<hr>
<c:out value="${list[0]}"/>
<c:out value="${list[1]}"/>
<c:out value="${list[2]}"/>
<c:out value="${list[3]}"/>
<hr>
<c:out value="${map['name']}"/>
<c:out value="${map['name1']}"/>
<c:out value="${map['name2']}"/>
<c:out value="${map['name3']}"/>
<hr>
<c:out value="${array[0]}"/>
<c:out value="${array[1]}"/>
<c:out value="${array[2]}"/>
<c:out value="${array[3]}"/>
body>
html>
package com.oracle.one.jsp.entity;
public class Dog {
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"
import="java.util.*"
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
DOCTYPE HTML>
<html>
<head>
<title>c:settitle>
head>
<body>
<c:set var="one" value="中国,北京" scope="request"/>
<c:out value="${one}"/>
body>
html>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"
import="com.oracle.one.jsp.entity.Dog"
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
DOCTYPE HTML">
utf-8">
c:if
<%
request.setAttribute("a","helloa");
request.setAttribute("age","23");
Dog dog = new Dog("宋江", 50);
request.setAttribute("dog", dog);
%>
${a== 'hello'}">
ok
${a!= 'hello'}">
no ok
${age==56} ">
ok 56
${age <56}">
no ok 56
${age >10 and age<34}">
age>10 and age<34 <br>
c:if>
<hr>
<c:if test="${dog.age>3}">
年龄大于3
c:if>
body>
html>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"
import="com.oracle.one.jsp.entity.Dog"
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
DOCTYPE HTML">
utf-8">
c:choose
<%
Dog dog = new Dog("宋江", 50);
request.setAttribute("dog", dog);
%>
${dog.age <18}">
red">未成年
${dog.age >18 and dog.age<50}">
<font color="green">青年font>
c:when>
<c:otherwise>
<font color="blue">中年font>
c:otherwise>
c:choose>
body>
html>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"
import="java.util.*, com.oracle.one.jsp.entity.Dog"
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML">
<html>
<head>
<meta charset="utf-8">
<title>c:foreachtitle>
head>
<body>
<%
List<Dog> dogs = new ArrayList<>();
Dog dog = new Dog("宋江", 50);
Dog dog1 = new Dog("卢俊义", 51);
Dog dog2 = new Dog("吴用", 52);
dogs.add(dog);
dogs.add(dog1);
dogs.add(dog2);
request.setAttribute("dogs", dogs);
@SuppressWarnings("unchecked")
List<Dog> dogsObject = (ArrayList<Dog>)request.getAttribute("dogs");
for(Dog dogSimple : dogsObject) {
out.println(dogSimple.getName() + " " + dogSimple.getAge());
}
%>
<br>
<c:forEach items="${dogs}" var="dog" >
<c:out value="${dog.name}"/>
<c:out value="${dog.age}"/>
c:forEach>
<hr>
<c:forEach var="i" begin="1" end="10">
<c:out value="${i}"/> ->
c:forEach>
<hr>
<c:forEach var="i" begin="3" end="10" step="2">
<c:out value="${i}"/> -->
c:forEach>
body>
html>
<%@page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"
import="java.util.*, com.oracle.one.jsp.entity.Dog"
%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>c:forEachtitle>
head>
<body>
<%
Map<String, Dog> map = new HashMap<>();
Dog dog = new Dog("宋江", 50);
Dog dog1 = new Dog("卢俊义", 51);
Dog dog2 = new Dog("吴用", 52);
map.put("dog", dog);
map.put("dog1", dog1);
map.put("dog2", dog2);
request.setAttribute("map", map);
Set<Dog> set = new HashSet<>();
set.add(dog);
set.add(dog1);
set.add(dog2);
request.setAttribute("set", set);
%>
<c:forEach items="${map}" var="mapDog">
key=${mapDog.key }
value.name=${mapDog.value.name }
value.age=${mapDog.value.age } <br>
c:forEach>
<hr>
<c:forEach items="${set}" var="setDog">
value=${setDog.name}
age = ${setDog.age } <br>
c:forEach>
<hr>
<c:if test="${empty map}">
没有
c:if>
<c:if test="${!empty set}">
有
c:if>
body>
html>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"
import="java.util.*"
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<title>c:removetitle>
head>
<body>
<%
request.setAttribute("one", "你好");
%>
<c:out value="${one}"/> <br>
<c:remove var="one"/>
<c:out value="${a}" default="没有了"/>
body>
html>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<title>c:redirecttitle>
head>
<body>
<c:redirect url="http://www.baidu.com"/>
body>
html>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML">
<html>
<head>
<meta charset="utf-8"/>
<title>c:forTokestitle>
head>
<body>
<%
request.setAttribute("abc", "12; 56; 你好;ddd; uuu"); /* 12 56; 你好; ddd uuu */
%>
<c:forTokens items="${abc}" delims=";" var="temp" begin="0" end="2" step="2">
${temp} <br>
c:forTokens>
body>
html>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>c:catchtitle>
head>
<body>
<c:catch var="myException">
<% int i=8/0; %>
c:catch>
<c:out value="${myException}"/> <br>
<c:out value="${myException.message}"/>
body>
html>
package com.greensea.manage.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Test;
public class TestJdbc {
@Test
public void testJdbc() {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_jack?characterEncoding=utf-8", "root", "root");
preparedStatement = connection.prepareStatement("select * from t_user where id=? and username=?");
preparedStatement.setString(1, "67"); //参数编号从1开始
preparedStatement.setString(2, "宋江");
resultSet = preparedStatement.executeQuery();
while(resultSet.next()) {
System.out.println(resultSet.getString("id"));
System.out.println(resultSet.getString("username"));
System.out.println(resultSet.getString("password"));
System.out.println(resultSet.getString("age"));
System.out.println(resultSet.getString("sex"));
System.out.println(resultSet.getString("email"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(resultSet!=null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(preparedStatement!=null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}