文章目录
1. web基本概念
静态和动态web
web 服务器(TomCat:8080)
TomCat服务器
安装TOMCAT
官网安装包
直接解压,打开bin文件,启动startup.bat文件,然后可以利用localhost:8080来进行访问。
阿利面试题:网站是如何进行访问的
利用tomcat发布一个网站:
注意首先打开Tomcat服务器!!!
HTTP(超文本传输协议)
http请求&&响应:
2. Maven(方便导入jar包–dependency依赖)
maven配置文件的阿里云镜像下载&本地的仓库(加速)以及配置环境变量(自己电脑)+java配置maven
1.安装配置Maven
<localRepository> E:\java\apache-maven-3.8.4-bin\apache-maven-3.8.4\maven-repo</localRepository>
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*,!jeecg,!jeecg-snapshots</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
2.idea配置maven
初始化配置创建一个maven项目(主要用于加载处idea的maven骨干jar包–即下载中央仓库文件到你的本地仓库),注意:先关闭所有的idea项目,然后进行设置maven3.6.2版本,而不是idea默认的maven3,。这一步完之后,再随便建一个项目,将中央仓库的jar包下载进入本地建的仓库,注意将配置文件改为阿里云的镜像下载那个,不然下载的很慢!!!!!
之后我们可以将这个初始化的这个项目删除,进行正常的maven项目创建,这时你的idea的maven就可加载出maven的骨干jar包了!!!
创建一个普通的maven项目(很快):直接点击next,不用打钩选择下面的骨干内容
3.idea 里Tomcat配置(使用maven里的一个webapp已有项目为例子)
(注意需要先对Tomcat进行环境变量的配置,否则idea找不到对应版本的Tomcat)
注意:这个Application context:可以自定义http地址的前面一段地址,啥都不加(http://localhost:8080),或者用系统产生的自定义的路径(http://localhost:8080/springmvc_04_controller_war_exploded/)
启动Tomcat,然后这个项目就会运行
显然helloworld来自项目里面的jsp文件
4.maven侧边栏的学习(maven结构学习)
pom.xml文件是maven的核心配置文件(代码结构分析)
<?xml version="1.0" encoding="UTF-8"?>
<!--maven版本和头文件-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- 这里是配置的GAV-->
<groupId>org.example</groupId>
<artifactId>Javaweb-01-maven</artifactId>
<version>1.0-SNAPSHOT</version>
<!--项目的打包方式:
jar:java应用
war:javaweb打包方式-->
<packaging>war</packaging>
<name>Javaweb-01-maven Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<!--配置-->
<properties>
<!--西安航母的默认配置编码-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!--配置java的版本-->
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<!--项目依赖,可以自动导入jar包-->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<!--项目构建用的东西-->
<build>
................
</build>
</project>
5.dependency自定导入相关联或者所依赖的jar包(太强了)=
本项目的依赖情况:
maven也会出现资源导出出现问题,利用下面的方法解决:
<!-- 在build中配置resources , 来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
3. Servlet(动态web)
Helloservlet简单webapp动态项目
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<!--注册servlet-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.kuang.servlet.HelloServlet</servlet-class>
</servlet>
<!--servlet的请求映射路径(可以给hello请求多条路径)-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
创建一个java编写的Servlet class
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入doget方法");
// ServletOutputStream outputStream = resp.getOutputStream();
PrintWriter writer = resp.getWriter();
writer.print("hello,servlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
运行结果1:来自父类的jsp
运行结果2:来自servlet的子类运行结果
servlet原理
映射路径的优先级,下面是一个通配符的路径,页面一进去就是404
<!--注册servlet-->
<servlet>
<servlet-name>error</servlet-name>
<servlet-class>com.kuang.servlet.ErrorServlet</servlet-class>
</servlet>
<!--servlet的请求路径-->
<servlet-mapping>
<servlet-name>error</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
public class ErrorServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
PrintWriter writer = resp.getWriter();
writer.print("<h1>404</h1>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
ServletContext(共享数据)
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取servlet上下文
ServletContext context = this.getServletContext();
String username="清姜";
//将一个数据保存在ServletContext中(键值对)
context.setAttribute("username",username);
}
}
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//两个servlet共用了一个ServletContext
//注意访问先访问helloServlet才能拿到username,否则是null
ServletContext context = this.getServletContext();
String username =(String) context.getAttribute("username");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter().print("我是"+username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
请求转发
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入了ServletDemo02");
ServletContext context = this.getServletContext();
//转发的请求路径
RequestDispatcher requestDispatcher = context.getRequestDispatcher("/getp");
//实现请求转发
requestDispatcher.forward(req,resp);
}
相当于sd2请求转发了getp的东西
读取资源文件(properties)
解决maven只打包resources目录下的文件,不打包java路径下的文件
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
将上述build代码放入对应的pom文件并重启idea
读取properties文件的内容
public class ServletDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is= this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/kuang/servlet/aa.properties");
Properties prop = new Properties();
prop.load(is);
String user = prop.getProperty("username");
String pwd = prop.getProperty("password");
//在申请路径下的网络页面打印出来
resp.getWriter().print(user+":"+pwd);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
HttpServletResponse
方法的简单分类
相应的状态码
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;
常见应用(验证码的3秒刷新—jsp、下载文件)
下载文件:(下载文件路径没讲明白)
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取下载文件的路径
String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/1.png");
System.out.println("下载文件的路径:"+realPath);
//下载的文件名
String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
//让浏览器能够支持我们下载东西
resp.setHeader("content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"UTF-8"));
//获取下载文件的输入流
FileInputStream in= new FileInputStream(realPath);
//创建缓冲区
int len=0;
byte[] buffer=new byte[1024];
//获取outputstream对象
ServletOutputStream out = resp.getOutputStream();
//将fileoutputstream写入到缓冲区
while((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
response重定向
public class Redirectservlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("./down");//或者路径填写:/servletResponse_war/down(急需要添加Tomcat里的artifact文件名)
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
本质原理:
面试题:请你聊聊重定向和转发的区别:
例如:sd2转发getp
例如:red重定向down
HttpServletRequest
获取前端传递的参数
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");//后台接收中文乱码问题
// 注意index.jsp写的是post提交
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbies = req.getParameterValues("hobby");
System.out.println(username+":"+password);
System.out.println(Arrays.toString(hobbies));
// 通过请求转发
req.getRequestDispatcher("./success.jsp").forward(req,resp);
resp.setCharacterEncoding("utf-8");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//调用doget方法相当于重写了dopost
doGet(req,resp);
}
}
请求转发
4.Session&Cookie(保存会话的两种技术)
cookie使用
//保存用户上一次访问的时间
public class CookieDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
// cookie(多个标志)由服务器从客户端获取
Cookie[] cookies = req.getCookies();
//判断cookie是否存在
if(cookies!=null){
out.write("您上一次访问的时间是:");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if(cookie.getName().equals("lastLoginTime")){
long lastLoginTime = Long.parseLong(cookie.getValue());
Date date = new Date(lastLoginTime);
out.write(date.toLocaleString());
}
}
}else{
out.write("这时你第一访问本站");
}
//服务器给客户"响应"一个cookie(始终执行更新)
Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");
//设置cookie有效期为一天
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//方法调用
doGet(req, resp);
}
}
手动删除cookie(注意待删除的cookie的名称必须与删除操作中的一样)
//删除cookie
public class CookieDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 创建一个cookie,名字和待删除的cookie一样
Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");
// 将cookie的有效期设置为0,立马过期
cookie.setMaxAge(0);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
解决cookie的键值对乱码问题:
session使用(重点)
session的注册
public class SessionDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 解决乱码问题
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=UTF-8");
// 得到session
HttpSession session = req.getSession();
// 给session中存放东西(可以放object,不同于cookie的string)
session.setAttribute("name",new Person("清姜",35));
// 获取session的id
String sessionId = session.getId();
if(session.isNew()){
resp.getWriter().write("session创建成功!"+"sessionId:"+sessionId);
}else{
resp.getWriter().write("session已经创建过!"+"sessionId:"+sessionId);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
session的手动注销(网页注销)
//注销session
public class SessionDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 解决乱码问题
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=UTF-8");
// 得到session
HttpSession session = req.getSession();
session.removeAttribute("name");
session.invalidate();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
session配置自动注销(web.xml)
<!-- session的自动配注销-->
<session-config>
<!--1分钟后自动失效-->
<session-timeout>1</session-timeout>
</session-config>
session和cookie的区别
5.JSP(开发动态web,简略HTML+JS)
基础语法
加上等号的是要在客户端输出的;不加等号的属于脚本片段。
JSP指令
内置对象(了解作用域的问题)
JSP标签(直接略了,据说现在完全不用)
6.javabean(实体类)
7.MVC三层架构
早些年的开发架构(过时):
MVC三层架构:
8.过滤器(过滤网站的数据!!!重要)
注意不要导错 Filtert的包
public class CharEncodeFilter implements Filter {
//初始化(web服务器一启动,就已经初始化了,随时等待过滤对象)
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("已经初始化...");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-16");
response.setCharacterEncoding("utf-16");
response.setContentType("text/html;charset=UTF-8");
System.out.println("过滤执行前。。。");
//chain的作用:经过过滤的代码,在过滤后继续执行
chain.doFilter(request,response);
System.out.println("过滤执行后");
}
//销毁(web服务器--Tomcat关闭的时候会自动销毁)
@Override
public void destroy() {
System.out.println("已经销毁...");
}
}
web配置文件
<filter>
<filter-name>charEncodeFilter</filter-name>
<filter-class>com.kuang.filter.CharEncodeFilter</filter-class>
</filter>
<!--只要是在/servlet后的任何请求都会过滤-->
<filter-mapping>
<filter-name>charEncodeFilter</filter-name>
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>showst</servlet-name>
<servlet-class>com.kuang.servlet.ShowServlet</servlet-class>
</servlet>
<!--过滤器过滤的-->
<servlet-mapping>
<servlet-name>showst</servlet-name>
<url-pattern>/servlet/show</url-pattern>
</servlet-mapping>
<!--过滤器未过滤的请求-->
<servlet-mapping>
<servlet-name>showst</servlet-name>
<url-pattern>/show</url-pattern>
</servlet-mapping>