技术标签: java javaweb tomcat servlet maven 后端
Java web
web开发
在java中,动态web资源开发的技术统称为javaWeb(就是用Java语言开发的
web应用程序:可以提供浏览器访问的程序;
web应用程序编写完毕后,若想提供给外界访问:需要一个服务器来统一管理;
页面会动态展示: “Web的页面展示的效果因人而异";
缺点
优点:
ASP:
<h1>
<h1>
<h1>
</h1>
<h1>
<%
System.out,println("hello")
%>
</h1>
</h1>
</h1>
php:
JSP/Servlet:
B/S: 浏览和服务器
C/S:客户端和服务器
服务器是一种被动的操作,用来处理用户的一些请求和给用户一些响应信息;
llS
微软的;ASP…,Windows中自带的
Tomcat
Tomcat是Apache软件基金会(Apache Software Foundation)的Jakarta项目中的一个核心项目,最新的Servlet和JSP规范总是能在Tomcat中得到体现,因为Tomcat技术先进、性能稳定,而且免费,因而深受Java爱好者的喜爱并得到了部分软件开发商的认可,成为目前比较流行的Web应用服务器。
Tomcat服务器是一个免费的开放源代码的Web应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试ISP程序的首选。对于一个Java初学web的人来说,它是最佳的选择
Tomcat 实际上运行JSP页面和Servlet。Tomcat最新版本为9.0。
tomcat官网:
文件夹作用
启动,关闭Tomcat
访问测试:http://localhost:8080/
可能遇到的问题:
1.Java环境变量没有配置(Tomcat用java写的
2.闪退问题:需要配置兼容性
3.乱码问题:配置文件中设置
可以配置启动的端口号
<connector port="8081" protoco1="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"/>
可以配置主机的名称
<Host name= "www.qinjiang.com"appBase="webapps"
unpackwARS="true" autoDeploy="true">
高难度面试题:
请你谈谈网站是如何进行访问的!
127.0.0.1 www.qinjiang.com
2. 没有:去DNS服务器找,找到的话就返回,找不到就返回找不到;
不会就先模仿
网站应该有的结构
--webapps : Tomcat服务器的web目录
-ROOT
-kuangstudy :网站的目录名
-web-INF
-c1asses : java程序
-lib: web应用所依赖的jar包
-web.xm1 :网站配置文件
-index.htm1 默认的首页
-static
-css
-sty1e.css
-js
-img
-...
HTTP(超文本传输协议)是一个简单的请求-响应协议,它通常运行在TCP之上。
HTTPS:安全的
http1.0
http2.0
Request URL:https : //www. baidu.com/请求地址
Request Method :GET get方法/post方法
status code : 200 oK 状态码: 200
Remote(远程) Address: 14.215.177.39:443
Accept:text/htm1
Accept-Encoding:gzip,deflate,br
Accept-Language:zh-CN,zh;q=0.9 语言
cache-contro1:max-age=o
connection:keep-alive
Accept:text/htm1 告诉浏览器,它所支持的数据类型
Accept-Encoding:gzip,deflate,br 支持哪种编码格式GBK UTF-8 GB2312 ISO8859-1
Accept-Language:zh-CN,zh;q=0.9 它的语言环境
cache-contro1:max-age=0 缓存控制
connection:keep-alive 告诉浏览器,请求完成是断开还是保持连接
HOST:主机...
cache-contro1 :private 缓存控制
connection:keep-Alive 连接
content-Encoding:gzip 编码
Content-Type:text/htm1 类型
Accept: 告诉浏览器,它所支持的数据类型
Accept-Encoding: 支持哪种编码格式GBK UTF-8GB2312 Is08859-1
Accept-Language: 告诉浏览器,它的语言环境
cache-contro1: 缓存控制
connection: 告诉浏览器,请求完成是断开还是保持连接
HOST:主机..../ .
Refresh:告诉客户端,多久刷新一次;
Location:让网页重新定位;
200:请求响应成功200
3xx:请求重定向
4xx:找不到资源404
5xx:服务器代码错误500 502:网关错误
我为什么要学习这个技术?
我们目前用来就是方便导入jar包的!
Maven的核心思想:约定大于配置
Maven会规定好你该如何去编写我们的Java代码,必须要按照这个规范来;
官网;https://maven.apache.org
在我们的系统环境变量中
配置如下配置:
<mirror>
<id>nexus-aliyun</id>
<mirrorof>*,!jeecg,!jeecg-snapshots</mirrorof>
<name>Nexus aliyun</name>
<ur1>http://maven.aliyun.com/nexuls/content/groups/public</ur1>
</mirror>
在本地的仓库,远程仓库;
建立一个本地仓库:localRepository
<localRepository>D:\apache-maven-3.8.6\Maven-repo</localRepository>
等待项目初始化完毕
观察maven仓库中多了什么东西?
IDEA中的Maven设置
IDEA项目创建成功后,看一眼Maven的配置
6.到这里,Maven在IDEA中的配置就ok了
解决警告问题
必须要的配置:为什么会有这个问题:我们访问一个网站,需要指定一个文件夹名字;
pom.xml是Maven的核心配置文件
maven由于他的约定大于配置,我们之后可以能遇到我们写的配置文件,无法被导出或者生效的问题,解决
Serlvet接口Sun公司有两个默认的实现类: HttpServlet,GenericServlet
构建一个普通的Maven项目,删掉里面的src项目,以后我们的学习就在这个项目里建立Moudel。这个空的工程就是Maven主工程。
关于Maven父子工程的理解:
父项目中会有一个
<modules>
<module>servlet-01</module>
</modules>
子项目会有
<parent>
<artifactId>javaweb-02-servlet</artifactId>
<groupId>com.shy.the</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
父项目中的java子项目可以直接使用
son extends father
public class HelloServlet extends HttpServlet {
//由于get或者post只是请求实现的不同方式,可以互相调用业务逻辑都一样
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.print("helloServlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
编写Servlet的映射
为什么需要映射:我们写的是JAVA程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要再web服务中注册我们写的Servlet,还需给他一个浏览器能够访问的路径;
<!-- 注册Servlet-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>servlet.HelloServlet</servlet-class>
</servlet>
<!-- Servlet的请求路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
配置Tomcat
遇到的问题:Tomcat中没有artifact
注意配置项目发布于的路径
启动测试
Servlet是由Web服务器调用,Web服务器在收到I浏览器请求之后,会:
浏览器通过web容器请求servlet调用service方法,之后再响应再通过web容器传送到浏览器
一个Servlet可以指定一个映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
一个Servlet可以指定多个映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello2</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello3</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello4</url-pattern>
</servlet-mapping>
一个Servlet可以指定通用映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
默认请求路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
不进入index页面
指定一些后缀或者前缀等等.
<! --可以自定义后缀实现请求映射
注意点,*前面不能加项目映射的路径he11o/sajdlkajda.qinjiang-->
<servlet-mapping>
<servlet-name>he11o</servlet-name>
<ur1-pattern>*.qinjiang</ur1-pattern></serv1et-mapping>
优先级问题
指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求;
<!--404-->
<servlet>
<servlet-name>error</servlet-name>
<serv1et-class>com. kuang.servlet.Errorservlet</servlet-class></servlet>
<servlet-mapping>
<serv1et-name>error</serv1et-name>
<ur1-pattern>/*</ur1-pattern>
</servlet-mapping>
web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用;
我在这个Servlet中保存的数据,可以在另外一个servlet中拿到
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// this.getServletConfig(); 初始化参数
// this.getServletContext(); Servlet配置
// this.getInitParameter(); Servlet上下文
ServletContext context = this.getServletContext();
String username = "shy";
context.setAttribute("username",username);//将一个数据保存在了ServletContext中,名字为username,值username
System.out.println("hello");
}
}
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// this.getServletConfig(); 初始化参数
// this.getServletContext(); Servlet配置
// this.getInitParameter(); Servlet上下文
ServletContext context = this.getServletContext();
String username = "shy";
context.setAttribute("username",username);//将一个数据保存在了ServletContext中,名字为username,值username
System.out.println("hello");
}
}
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getc</servlet-name>
<servlet-class>servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getc</servlet-name>
<url-pattern>/getc</url-pattern>
</servlet-mapping>
测试访问结果
<!-- 获取一些web应用初始化参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}
转发的路径不会发生变化
在这里插入图片描述
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
System.out.println("进入了ServletDemo04");
RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");//转发的请求路径
requestDispatcher.forward(req,resp);//调用forward实现请求转发
}
Properties
发现:都被打包到了同一个路径下: classes,我们俗称这个路径为classpath:
思路:需要一个文件流;l
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(is);
String username = properties.getProperty("username");
String password = properties.getProperty("password");
resp.getWriter().print(username+":"+password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
访问测试即可ok
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse;
负责向浏览器发送数据的方法
ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;
负责向浏览器发送响应头的方法
void setCharacterEncoding(String var1);
void setContentLength(int var1);
void setContentLengthLong(long var1);
void setContentType(String var1);
void setDateHeader(String var1, long var2);
void addDateHeader(String var1, long var2);
void setHeader(String var1, String var2);
void addHeader(String var1, String var2);
void setIntHeader(String var1, int var2);
void addIntHeader(String var1, int var2);
响应状态码
int SC_CONTINUE = 100;
int SC_SWITCHING_PROTOCOLS = 101;
int SC_OK = 200;
int SC_CREATED = 201;
int SC_ACCEPTED = 202;
int SC_NON_AUTHORITATIVE_INFORMATION = 203;
int SC_NO_CONTENT = 204;
int SC_RESET_CONTENT = 205;
int SC_PARTIAL_CONTENT = 206;
int SC_MULTIPLE_CHOICES = 300;
int SC_MOVED_PERMANENTLY = 301;
int SC_MOVED_TEMPORARILY = 302;
int SC_FOUND = 302;
int SC_SEE_OTHER = 303;
int SC_NOT_MODIFIED = 304;
int SC_USE_PROXY = 305;
int SC_TEMPORARY_REDIRECT = 307;
int SC_BAD_REQUEST = 400;
int SC_UNAUTHORIZED = 401;
int SC_PAYMENT_REQUIRED = 402;
int SC_FORBIDDEN = 403;
int SC_NOT_FOUND = 404;
int SC_METHOD_NOT_ALLOWED = 405;
int SC_NOT_ACCEPTABLE = 406;
int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
int SC_REQUEST_TIMEOUT = 408;
int SC_CONFLICT = 409;
int SC_GONE = 410;
int SC_LENGTH_REQUIRED = 411;
int SC_PRECONDITION_FAILED = 412;
int SC_REQUEST_ENTITY_TOO_LARGE = 413;
int SC_REQUEST_URI_TOO_LONG = 414;
int SC_UNSUPPORTED_MEDIA_TYPE = 415;
int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
int SC_EXPECTATION_FAILED = 417;
int SC_INTERNAL_SERVER_ERROR = 500;
int SC_NOT_IMPLEMENTED = 501;
int SC_BAD_GATEWAY = 502;
int SC_SERVICE_UNAVAILABLE = 503;
int SC_GATEWAY_TIMEOUT = 504;
int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
public class FileServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 要获取下载文件的路径
String realPath = "D:\\javawebcode\\javaweb-02-servlet\\response\\target\\classes\\程璐.png";
System.out.println("下载的文件的路径"+realPath);
//2. 下载的文件名是啥
String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
//3. 设置想办法让浏览器能够以支持的下载我们的需要的东西,中文文件名用URLEncoder.encode编码,否则有可能乱码
resp.setHeader("Content-Disposition","attachmnent;filename="+URLEncoder.encode(filename,"UTF-8"));
//4. 获取下载文件的输入流
FileInputStream is = new FileInputStream(realPath);
//5. 创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
//6. 获取Output Stream对象啊
ServletOutputStream os = resp.getOutputStream();
//7. 将File Output Stream流写入到buffer缓冲区,使用Output Stream将缓冲区中的数据输出到客户端
while ((len=is.read(buffer))>0){
os.write(buffer,0,len);
}
is.close();
os.close();
}
}
public class ImageServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如如何让浏览器三秒刷新一次
resp.setHeader("refresh","3");
//在内存中创建一个图片
BufferedImage bufferedImage = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
//得到图片
Graphics2D g = (Graphics2D)bufferedImage.getGraphics();//笔
//设置图片的背景颜色
g.setColor(Color.white);
g.fillRect(0,0,80,20);
//给图片写数据
g.setColor(Color.blue);
g.setFont(new Font(null,Font.BOLD,20));
g.drawString(makeNum(),0,20);
//告诉浏览器,这个请求用图片的方式打开
resp.setContentType(("image/jpeg"));
//网站存在缓存,不让浏览器缓存
resp.setDateHeader("expires",1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
ImageIO.write(bufferedImage,"jpg",resp.getOutputStream());
}
private String makeNum(){
Random random = new Random();
String s = random.nextInt(99999) + "";
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i <5-s.length(); i++) {
stringBuffer.append("0");
}
String s1 = stringBuffer.toString() + s;
return s1;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
B一个web资源收到客户端A请求后,B他会通知A客户端去访问另外一个web资源C,这个过程叫重定向
常见场景:
测试:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/* resp.setHeader("Location","/response_war/image");
resp.setStatus(302);
*/
resp.sendRedirect(("/response_war/image"));//重定向
}
面试题:请你聊聊重定向和转发的区别
相同的
不同点
HttpServletRequest代表客户端的请求,用户通过Http协议防蚊服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息。
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbys = req.getParameterValues("hobbys");
System.out.println("==========================");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbys));
System.out.println("==========================");
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话
有状态会话:一个同学来过教室,下次再来教室,我们会知道这个同学,曾经来过,称之为有状态会话;
一个网站,怎么证明你来过?客户端
服务端
服务端给客户端一个信件,客户端下次访问服务端带上信件就可以了; cookie
服务器登记你来过了,下次你来的时候我来匹配你; seesion
cookie
session
常见网站
从请求中拿到Cookie信息
服务器响应给客户端Cookie
cookie[] cookies = req.getcookies(;//获得cookiecookie.getName(;//获得cookie中的key
cookie.getvalue(;//获得cookie中的v1aue
new cookie("lastLoginTime",system.currentTimeMi17is()+"");//新建一个cookiecookie.setMaxAge(24*60*60);//设置cookie的有效期
resp.addcookie(cookie);//响应给客户端一个cookie
cookie:一般会保存在本地的用户目录下appdata;
一个网站cookie是否存在上限!聊聊细节问题
删除Cookie;
编码解码
URLEncoder.encode("秦疆", "utf-8")
URLDecoder.decode(cookie.getvalueo , "UTF-8")
什么是Session:
Session和cookie的区别
使用场景
使用Session
package servlet;
import pojo.Preson;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
resp.setCharacterEncoding("utf-16");
req.setCharacterEncoding("utf-16");
resp.setContentType("text/html;charset=utf-8");
//得到Session
HttpSession session = req.getSession();
//给Session中存东西
session.setAttribute("name",new Preson("the shy",20));
//获取Session的Id
String id = session.getId();
//判断Session是不是新创建
if(session.isNew()){
resp.getWriter().write("session创建成功,ID"+id);
}else {
resp.getWriter().write("session已经在服务器中存在了,ID"+id);
}
// Session创建的时候做了什么事情;
// cookie cookie = new cookie( "JSESSIONID" ,sessionId);
// resp.addcookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
//得到Session
HttpSession session = req.getSession();
Preson preson = (Preson) session.getAttribute("name");
System.out.println(preson.toString());
HttpSession session = req.getSession();
session.removeAttribute("name");
//手动注销Session
session.invalidate();
会话自动过期:web.xml配置
<!--设置Session默认的失效时间-->
<session-config>
<!--15分钟后Session自动失效,以分钟为单位-->
<session-timeout>15</session-timeout>
</session-config>
Java Server Pages : Java服务器端页面,也和Servlet一样,用于动态Web技术!
最大的特点:
思路:JSP到底怎么执行的
代码层面没有任何问题
服务器内部工作
tomcat有一个work目录
idea中使用tomcat的会在IDEA的tmcat中产生一个work目录
页面变成了java程序
浏览器向服务器发送请求不管访问什么资源,其实都是在访问Servlet
JSP最终也会被转换成为以一个JAVA类
JSP本质上就是一个Servlet
//初始化
pub1ic void _jspInit() {
}
//销毁
pub1ic void - _jspDestroy() {
}
//JSPService
pub1ic void - _jspService(. HttpServletRequest request, HttpServletResponse response)
1.判断请求
2.内置一些对象
final javax.servlet.jsp.PageContext pageContext; //页面上下文
javax.servlet.http.HttpSession session = nu11; //session
fina1 javax.servlet.Serv1etContext application; //applicati onContext
fina1 javax.serv1et.Serv1etConfig config; //config
javax.servlet.jsp.JspWriter out = nu11; //out
fina1 java.lang.object page = this; //page:当前
HttpServletRequest request //请求
HttpServ1etResponse response //响应
3.输出页面前增加代码
response . setContentType(" text/htm1");//设置响应的页面类型
pageContext = - j spxFactory. getPageContext(this,request, response,nu11,true,8192,true);
_jspx_page_context =pageContext;
app1ication = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession() ;
out = pageContext. getout();
_jspx_ out =out;
4.以上得这些个对象我们可以在JSP页面中直接使用
在JSP页面中;
只要是JAVA代码就会原封不动的输出;
如果是HTML代码,就会被转换为:
out. write("<htm1>\r\n");
这样的格式,输出到前端!
任何语言都有自己的语法,JAVA中有。JSP 作为java技术的-种应用,它拥有一-些自己扩 充的语法(了解,知道
即可! ),Java所有语法都支持!
<%--JSP表达式
作用:用来将程序的输出,输出到客户端
<%= 变量或者表达式%>
--%>
<%= new java. uti1. Date()%>
<%--jsp脚本片段--%>
<%
int sum = 0;
for(inti=1;i<==100;i++){
sum+=i;
}
out. println("<h1>Sum="+sum+" </h1>" );
%>
<%
intx=10;
out. print1n(x);
%>
<p>这是一个JSP文档</p>
<%
inty=2;
out. print1n(y);
%>
<hr>
<%--在代码嵌入HTML元素--%>
<%
for(inti=0;i<5;i++){
%>
<h1>He11o,Wor1d <%=i%> </hl>
<%
}
%>
<%!
static {
System. out. print1n("Loading Servlet!");
}
private int g1obalVar = 0;
public void kuang(){
System. out. print1n("进入了万法Kuang: ");
}
%>
JSP声明:会被编译到SP生成Java的类中!其他的,就会被生成到jspService方法中!
在JSP,嵌入ava代码即可!
<%%>
<%=%>
<%!%>
<%--注释--%>
JSP的注释,不会在客户端显示,HTML会
<%@page args.. .. %><%@include file=""%>
<%--@include会将两个页面合二为一--%>
<%@include file="common/header.jsp"%>
<h1>网页主体</h1>
<%@include fi1e="common /footer.jsp"%>
<hr>
<%--jSP标签
jsp:include:拼接页面,本质还是三个
--%>
jsp:include page=" /common/header.jsp"/>
<h1>网页主体</h1>
<jsp:include page=" /common /footer.jsp"/>
PageContext 存东西
Request 存东西
Response
Session 存东西
Application 【SerlvetContext】存东西
config【SerlvetConfig )
out
page 不用了解
exception
pagecontext.setAttribute("name1", "秦疆1号");//保存的数据只在一个页面中有效
request.setAttribute("name2" , "秦疆2号");//保存的数据只在一次请求中有效,请求转发会携带这个数据
session.setAttribute( "name3" , "秦疆3号");//保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器
application.setAttribute("name4" ,"秦疆4号");//保存的数据只在服务器中有效,从打开服务器到关闭服务器
request:客户端向服务器发送请求,产生的数据,用户看完就没用了,比如:新闻,用户看完没用的!
session:客户端向服务器发送请求,产生的数据,用户用完一会还有用,比如:购物车;
application:客户端向服务器发送请求,产生的数据,一个用户用完了,其他用户还可能使用,比如:聊天数据;
<!-- JSTL表达式的依赖-->
<dependency>
<groupId>javax.servlet.jsp.jstl</ groupId>
<artifactId>jst1-api</artifactId>
<version>1.2</version>
</dependency>
<!-- standard标签库-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
EL表达式:${}
JSP标签
<%--jsp:include--%>
<%--
http://1ocalhost:8080/jsptag.jsp?name=kuangshen&age=12
--%>
<jsp:forward page="/jsptag2.jsp">
<jsp:param name="name" value="kuangshen"></jsp:param>
<jsp:param name="age" value="12"></jsp:param>
</jsp:forward>
JSTL表达式
JSTL标签库的使用就是为了弥补HTML标签的不足;它自定义许多标签,可以供我们使用,标签的功能和Java代码一样!
核心标签
格式化标签
SQL标签
XML标签
JSTL标签库使用步骤
<head>
<title>Title</title>
</head>
<body>
<h4>if测试</ h4>
<hr>
<form action="coreif.jsp" method="get">
<%--
EL表达式获取表单中的数据${param.参数名舒}
--%>
<input type="text" name="username" value="${param.username}">
<input type="submit" value="登录">
</form>
<%--判断如果提交的用户名是管理员,则登录成功--%>
<c:if test="${param.username=='admin'}" var="isAdmin">
<c:out value="管理员欢迎您!"/ >
</c:if>
<%--自闭合标签--%>
<c:out value="${isAdmin}" />
</body>
<%
ArrayList<String> people = new ArrayList<>();
people.add(e, "张三");
people.add(1,"李四");
people.add(2,"王五");
people.add( 3,"赵六");
people.add(4,"田六");
request.setAttribute(name:"list" ,people);
%>
<%--
var ,每一次遍历出来的变量
items,要遍历的对象
begin,哪里开始
end,到哪里
step,步长
--%>
<c:forEach var="people" items="${list}">
<c:out value="${people}"/><br>
</c:forEach>
<c:forEach var="people" items="${list}" begin="1" end="3" step="1" >
<c:out value="${people}"/> <br>
</c:forEach>
实体类(pojo,entity
JavaBean有特定的写法:
一般用来和数据库的字段做映射ORM;
ORM︰对象关系映射
什么是MVC:model,view ,Controller,模型,视图,控制器
用户直接访问控制层,控制层就可以直接操作数据库
servlet--CRUD-->数据库
弊端:程序十分臃肿,不利于维护
servlet的代码中:处理请求、响应、视图跳转、处理DBc、处理业务代码、处理逻辑代码
架构:没有什么是加一层解决不了的!
程序猿调用
|
JDBC
|
Mysq1 oracle sqlserver ....
Model
view
Controller(Servlet)
登录--->接收用户的登录请求--->处理用户的请求(获取用户登录的参数,username,password) ---->交
给业务层处理登录业务(判断用户名密码是否正确:事务)--->Dao层查询用户名和密码是否正确-->数据库
Filter:过滤器,用来过滤网站的数据;
1.导包导入的包要在javax.servlet目录下的
2.编写过滤器
public class CharacterEncodingFilter implements Filter {
//初始化Web服务器启动,就已经初始化了,随时灯带过滤对象出现
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncodingFilter已经初始化");
}
//Chain:链
/*
1.过滤中的所有代码,在过滤特定请求的时候都会执行
2.必须要让过滤器继续同行
chain.doFilter(request, response);
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=UTF-8");
System.out.println("CharacterEncodingFilter执行前");
filterChain.doFilter(servletRequest,servletResponse);//让我继续走,如果不写,程序到这里就被拦截停止了
System.out.println("CharacterEncodingFilter执行后");
}
@Override
//销毁Web服务器关闭才会销毁
public void destroy() {
System.out.println("CharacterEncodingFilter已经销毁");
}
}
<filter>
<filter-name>CE</filter-name>
<filter-class>shy.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CE</filter-name>
<!--只要是/servlet的任何请求,会经过这个过滤器-->
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
实现一个监听器的接口(有N种)
编写一个监听器
实现监听器接口
//同合计网站在线人数:统计session
public class OnlineCountListener implements HttpSessionListener {
@Override//创建Session监听,看你的一举一动
//一旦创建Session就会触发一次这个事件
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");
if(onlineCount==null){
onlineCount=new Integer(1);
}else {
int count = onlineCount.intValue();
onlineCount=new Integer(count+1);
}
servletContext.setAttribute("OnlineCount",onlineCount);
}
@Override//销毁Session监听,看你的一举一动
//一旦销毁Session就会触发一次这个事件
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");
if(onlineCount==null){
onlineCount=new Integer(1);
}else {
int count = onlineCount.intValue();
onlineCount=new Integer(count-1);
}
servletContext.setAttribute("OnlineCount",onlineCount);
}
/*
session销毁:
1.手动销毁getsession( ).invalidate( );
2.自动销毁
*/
}
<!--注册监听器-->
<listener>
<listener-class>shy.listener.OnlineCountListener</listener-class>
</listener>
监听器:GUI编程中经常使用
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame( title: "中秋节快乐");//新建一个窗体Panel panel = new Panel( layout: null); //面板
frame.setLayout(nu11); //设置窗体的布局
frame.setBounds( 30,300,500,height:500) ;
frame.setBackground(new Color(0,0,255));//设置背景颜色
panel.setBounds(50,0,300,300);
panel.setBackground(new color(0,255,0));//设置背景颜色
frame.add(panel);
frame.setvisible(true);
//监听事件,监听关闭事件
frame . addwindowListener((WindowAdapter) windowClosing(e) → {
super.windowClosing(e); });
}
}
用户登录之后才能进入主页!用户注销后不能进入主页
<url-pattern>/sys/*</url-pattern>
xml文件路径配置中最前面的/相当于到web文件夹
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("sysFilter启动了");
HttpServletRequest request= (HttpServletRequest) servletRequest;
HttpServletResponse response= (HttpServletResponse) servletResponse;
if(request.getSession().getAttribute("USER_SESSION")==null){
response.sendRedirect("/s/error.jsp");
}
filterChain.doFilter(request,response);
}
什么JDBC:JAVA连接数据库
需要jar包的支持:
实验环境搭建
CREATE TABLE users(
id INT PRIMARY KEY,
`name` VARCHAR(40),
`password` VARCHAR(40),
email VARCHAR(60),
birthday DATE
);
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(1,'张三','123456','[email protected]','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(2,'李四','123456','[email protected]','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(3,'王五','123456','[email protected]','2000-01-01');
SELECT * FROM users
导入数据库依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
JDBC固定步骤
public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
String url="jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSl=true";
String username="root";
String password="123456";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.向数据库发送SQL的对象Statement:CRUD
Statement statement = connection.createStatement();
//4.编写SQL
String sql ="select * from users";
//受影响的行数,|增删改都是用executeUpdate即可
//int i = statement.executeUpdate(sqL);
//5.执行查询SQL,返回一个ResultSet
ResultSet execute = statement.executeQuery(sql);
while(execute.next()){
System.out.println("id"+execute.getObject("id"));
System.out.println("name"+execute.getObject("name"));
System.out.println("password"+execute.getObject("password"));
System.out.println("email"+execute.getObject("email"));
System.out.println("birthday"+execute.getObject("birthday"));
}
//6.关闭连接,释放资源
execute.close();
statement.close();
connection.close();
}
}
预编译(防SQL注入
public class TestJdbc2 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
String url="jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSl=true";
String username="root";
String password="123456";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.编写SQL
String sql ="insert into user(id,name,password,email,birthday)values(?,?,?,?,?);";
//4.预编译
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,1);
preparedStatement.setString(2,"ts");
preparedStatement.setString(3,"123456");
preparedStatement.setString(4,"[email protected]");
preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));
//5.执行Sql
int i = preparedStatement.executeUpdate();
if(i>0){
System.out.println("插入成功");
}
//6.关闭连接,释放资源
preparedStatement.close();
connection.close();
}
}
事务
要么成功,要么失败
ACID原则,保证数据成功
Junit单元测试
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
简单使用
@Test注解只有在方法上有效,只要加了这个注解的方法,就可以直接运行
public class TestJdbc3 {
@Test
public void test(){
System.out.println("hello");
}
}
文章浏览阅读240次。精通PKI网络安全认证技术与编程实现从实战出发,介绍了PKI应用开发过程和细节。《精通PKI网络安全认证技术与编程实现》共32章,分6篇,主要内容包括PKI基础知识、OpenSSL开发、CrytoAPI开发、JavaSecurity开发、电子商务网站应用、PKI技术应用等,涉及C语言、Java语言、JSP、ASP/ASP.NET、PHP等开发语言。为了方便读者深入了解PKI,《精通PKI网络安全认..._api安全技术与实战pdf
文章浏览阅读644次。函数名: modf头文件:函数原型: double modf(double value, double *iptr);功 能: 求双精度数的小数部分参 数: double value 为要操作的双精度数 ,double *iptr 为要传回整数部分的变量指针返回值: 返回value的小数部分程序例: 分别求出双精度number的小数部分和整数部分,并将结果输出#include#includ..._c语言求一个双精度数的整数部分和小数部分
文章浏览阅读288次。最近在学习DDos相关知识,参考一些只是,做了摘要,供自己参考。 参考:http://blog.csdn.net/xlf13872135090/article/details/8059538SYN Flood 攻击原理 利用TCP协议缺陷,发送了大量伪造的TCP连接请求,使得被攻击方资源耗尽,无法及时回应或处理正常的服务请求。一个正常的TCP连接需要三次握手,首先客户端发送一个包含SYN标志的数_http存在synflood吗
文章浏览阅读775次。我们之前学习的都是针对一个表的操作。如果要进行多个表之间的操作,就要用到外键把他们关联起来。外键的作用:能够让多个表进行关联,使表与表之间有联系,实现共性抽取。如果数据项比较多的情况下,把所有数据都存放在一个表中,如果表太大,影响操作效率。解决办法就是把一个表拆分成多个表,并且用外键去关联。例子:如果要设计一个员工表1)员工表:编号、姓名、年龄、性别、所在分公司、所在部门2)部门表:编号、部门名称、部门经理、主要任务3)公司表:编号、分公司名,地址、电话、法人把公司和部门的数据抽取出来,形成_sql查询外键id的数据
文章浏览阅读803次,点赞14次,收藏14次。章节一讲述了OpenGL在渲染的时候需要一个Context来记录了OpenGL渲染需要的所有信息和状态,可以把上下文理解成一个大的结构体,它里面记录了当前绘制使用的颜色、是否有光照计算以及开启的光源等。不同的操作系统,都有各自的上下文创建方法,最简单的上下文可以通过创建。章节二讲述了一个一个轻量级的图形界面框架,GLFW 的是提供了处理手柄、键盘、鼠标输入章节二还创建了一个空项目章节三讲述了GLAD库是用来管理OpenGL的函数指针的,所以在调用任何OpenGL的函数之前我们需要,从而让我们。_opengl窗口颜色
文章浏览阅读644次。一、Spring部分1、Spring的运行流程·第一步:加载配置文件ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");,ApplicationContext接口,它由BeanFactory接口派生而来,因而提供了BeanFactory所有的功能。配置文件中的bean的信息是被加载在HashMap中的,一个..._ssm那个文件是运行
文章浏览阅读1.3k次。目标:使用OpenCV cv::inRange 函数进行基本的 阈值操作, 基于像素值在HSV色度空间的范围进行对象检测理论:前一篇文章中我们学习了如何使用cv::threshold 阈值函数进行阈值操作 本文我们将学习使用 cv::inRange 来进行处理 原理是一样的但是现在我们增加了一个我们所需要的 【像素值的范围】HSV色度空间 HSV colorspaceHSV ..._inrange和cv2.threshold一起使用
文章浏览阅读154次。 瑜伽培训课程层出不穷,但市面上都没有教授瑜伽老师们如何“教”的系统培训。瑜伽行业表面看似繁荣,但大多数老师缺失教学的“灵魂”。 为此,心合瑜伽学院王梓涵院长结合多年来积累的经验以及瑜伽老师的痛点,与心合教学团队不断打磨,开创瑜伽培训先河,首创贴合瑜伽老师的『瑜伽教学法』,教学法正是指导瑜伽老师们如何上课的法门! 不少老师们,有时会有这样的问题: “我把正确的口令讲出来了,但是会员好像不听我的口令,并没有按照口令去做,需要我不停地辅助和做示范才能完成...” 一个优秀的老师,总可以_会员病了无法来上瑜伽课怎么说
文章浏览阅读2.2w次,点赞12次,收藏113次。随机森林概述随机森林是集成学习方法bagging类中的翘楚。与集成学习boosting类的GBDT分庭抗礼。bagging类集成学习采用的方法是:用部分数据 or 部分特征 or 多个算法 训练一些模型;然后再组合这些模型,对于分类问题采用投票多数表决,回归问题采用求平均。各个模型训练之间互不影响,天生就适合并行化处理。在如今大数据时代背景下很有诱惑力。 主要效果:重点关注降低方差,..._随机森林及其调参
文章浏览阅读1.5k次,点赞2次,收藏2次。解决Exception: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z和Error: JAVA_HOME is incorrectly set.Please update D:\Software\hadoop260\conf\hadoop-env.cmd‘-Xmx512m’ 不是内部或外部命令,也不是可运行的程序或批处理文件。这个错误目前我知道的有以下几种解决办法:一、查看hadoop安装是_org.apache.hadoop.io.nativeio.nativeio$windows.access0(ljava/lang/string;i)z
文章浏览阅读2.6k次。我的是linux系统,那么要怎么样才能查看防火墙有没有开启呢?下面由学习啦小编给你做出详细的linux查看防火墙是否开启方法介绍!希望对你有帮助!linux查看防火墙是否开启方法一:service iptables status可以查看到iptables服务的当前状态。但是即使服务运行了,防火墙也不一定起作用,你还得看防火墙规则的设置 iptables -L在此说一下关于启动和关闭防火墙的命令:1..._linux防火墙服务找不到
文章浏览阅读109次。public class useDatrgrivView { string conn = null; string sqlComm = null; DataSet das = null; DataGridView GridView = null; //初始化,绑定 publ..._datrgridview 显示不了数据