栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JavaWeb

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaWeb

JavaWeb Maven

main-新建文件夹java和resourcesrc-新建文件夹test-新建java和resource

pom.xml




  4.0.0

  org.example
  untitled3
  1.0-SNAPSHOT

  war

  untitled3 Maven Webapp
  
  http://www.example.com

  

    UTF-8

    1.7
    1.7
  

  

    
      junit
      junit
      4.11
      test
    
  

  
    untitled3
    
      
        
          maven-clean-plugin
          3.1.0
        
        
        
          maven-resources-plugin
          3.0.2
        
        
          maven-compiler-plugin
          3.8.0
        
        
          maven-surefire-plugin
          2.22.1
        
        
          maven-war-plugin
          3.2.2
        
        
          maven-install-plugin
          2.5.2
        
        
          maven-deploy-plugin
          2.8.2
        
      
    
  

Servlet

步骤

编写一个普通类实现Serlvet接口,这里我们继承HttpSerlvet导入servlet包


     javax.servlet
     javax.servlet-api
     4.0.1
     compile
   
- ```java
public class HelloServlet extends HttpServlet {
    //由于get和post只是请求实现的不同的方式,可以相互调用,业务逻辑都一样
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //ServletOutputStream outputStream = resp.getOutputStream();
        PrintWriter writer = resp.getWriter();//响应流
        writer.print("Hello,Serlvet");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

编写Serlvet的映射




  Archetype Created Web Application

  
    hello
    com.liu.servlet.HelloServlet
  

  
    hello
    /hello
  

配置TomCat servlet原理


  hello
  /hello*.properties
        ***.properties
        **
        resp.sendRedirect("/response_war/im");
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

  re
  com.liu.response.re


  re
  /re

面试题:请你聊聊重定向和转发的区别?
相同点
●页面都会实现跳转
不同点
●请求转发的时候,url不会产生变化307
●重定向时候,url地址栏会发生变化302

1.导入jsp包


  javax.servlet.jsp
  javax.servlet.jsp-api
  2.3.3
  provided

2.编写登录页



<%--这里提交的路径,需要找到项目的路径--%>
<%--${pageContext.request.contextPath}代表当前的项目--%>
<%--⬇⬇⬇⬇⬇⬇⬇支持EL--%>
<%@ page isELIgnored="false"%>
用户名:
密码:
提交

3.编写要跳转的success页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    成功进入





4.注册


  login
  com.liu.response.denglu


  login
  /login

5.代码实现

public class denglu extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理请求
        String username = req.getParameter("username");
        String pwd = req.getParameter("password");
        System.out.println(username+":"+pwd);
        //重定向注意路径,404
        resp.sendRedirect("/response_war/success.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
HttpServletRequest 获取前端传递的参数,请求转发

1.index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false"%>


    登录
    登录
    
        
name
password
girls boys submit

2.success.jsp

3.代码

public class request extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //中文乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        String name = req.getParameter("username");//获取单个
        String pwd = req.getParameter("password");
        String[] hobby = req.getParameterValues("hobbies");//获取多个

        System.out.println(name);
        System.out.println(pwd);
        System.out.println(hobby);
        System.out.println("===================================");
        System.out.println(req.getContextPath());
        //通过请求转发
        req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

4.注册




  login
  com.liu.request.request

  
    login
    /login
  

cookie
public class cookieDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //服务器 ,告诉你来的时间,把这个时间封装成为一个信件,我就知道你来了
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        //cookie,服务器端从客户端获取
        cookie[] cookies = req.getcookies();//这里返回数组,说明cookies可能存在多个
        //判断cookie是否存在
        if(cookies!=null){
            out.write("你上一次访问的时间是:");
            for (int i = 0; i  
//1.从请求中拿到cookie信息
//2.服务器响应给客户端cookie
cookie[] cookies = req.getcookies();//获得cookies
cookie.getName();//获取cookie的key
cookie.getValue();//获取cookie的vlaue
new cookie("lastlogintime", System.currentTimeMillis()+"");//新建一个cookie
cookie.setMaxAge(24*60*60);//设置cookie的有效期
resp.addcookie(cookie);//响应给客户端一个cookie
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中存东西
        session.setAttribute("name","刘");

        //获取session的ID
        String id = session.getId();

        //判断Session是不是新创建的
        if(session.isNew()){
            resp.getWriter().write("session创建成功,ID:"+id);
        }else {
            resp.getWriter().write("session已经在服务器中存在了,ID:"+id);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

补充session

JSP

导入:servlet,jsp,jstl-api,standard

    
      javax.servlet
      javax.servlet-api
      4.0.1
    

    
      javax.servlet.jsp
      javax.servlet.jsp-api
      2.3.3
    

    
      javax.servlet.jsp.jstl
      javax.servlet.jsp.jstl-api
      1.2.2
    

    
      taglibs
      standard
      1.1.2
    
Jsp表达式
<%--JSP表达式
作用:用来将程序的输出,输出到客户端
<%= 变量或表达式%>
--%>
<%= new java.util.Date()%>
Jsp脚本片段
<%--Jsp脚本片段--%>
<%
    int num = 0;
    out.print("num"+num+"");
%>
<%--在代码中嵌入html元素--%>
<%
    for (int i = 0; i < 5; i++) {
%>
hello
<%}%>
<%!%>声明变量的。
JSP指令
<%@page args...%>
<%@include file=""%>

<%--@include会将两个页面合2为一--%>
<%@include file="common/header.jsp"%>
网页主体
<%@include file="common/footer.jsp"%>

<%--jSP标签 jsp:include:拼接页面,本质还是三个 --%> 网页主体
JSP内置对象及作用域
<%@ page isELIgnored="false" %>
<%--内置对象--%>
<%
    pageContext.setAttribute("name1","liu1");//保存的数据只在一个页面中有效
    request.setAttribute("name2","liu2");//保存的数据只在一次请求中有效,请求转发会携带这个数据
    session.setAttribute("name3","liu3");//保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器
    application.setAttribute("name4","liu4");//保存的数据只在服务器中有效,从打开服务器到关闭服务器
%>
<%--脚本片段中的代码,会被原封不动生成带.JSP.java
要求:在这里的代码必须保证Java语法的正确性
--%>
<%
    //从pageContext取出,通过寻找方式
    //从底层到高层(作用域)  page-->request-->session-->application
    String name1 = (String) pageContext.findAttribute("name1");
    String name2 = (String) pageContext.findAttribute("name2");
    String name3= (String) pageContext.findAttribute("name3");
    String name4 = (String) pageContext.findAttribute("name4");
    String name5 = (String) pageContext.findAttribute("name5");//不存在
%>
<%--使用EL表达式输出${}--%>

取出的值为:

${name1} ${name2} ${name3} ${name4} <%=name5%>
<%
pageContext.forward("/index.jsp");
request.getRequestDispatcher("/index.jsp").forward(request,response); 
%>
JSP标签、JSTL标签、EL表达式 EL表达式: ${ }

获取数据执行运算获取web开发的常用对象

    
      javax.servlet.jsp.jstl
      javax.servlet.jsp.jstl-api
      1.2.2
    

    
      taglibs
      standard
      1.1.2
    
JSP标签
<%--a.jsp--%>
1
<%--jsp:include--%>
<%--
http://localhost:8080/a.jsp?name=liu&age=12
--%>

    
    

<%--a2.jsp
 取出   
 --%>
<%=request.getParameter("name")%>
<%=request.getParameter("age")%>
JSTL表达式

引入对应的taglib使用其中的方法

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false" %>


    Title


<%-- EL表达式获取表中的数据 ${param.参数名} --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false" %>


    Title


<%-- EL表达式获取表中的数据 ${param.参数名} --%>
<%--判断如果提交的用户名是管理员,则登录成功--%> <%--自闭和标签--%>


    
        优秀
    
    
        良好
    

<%
    ArrayList people = new ArrayList<>();
    people.add(0,"张三");
    people.add(1,"李四");
    people.add(2,"王五");
    people.add(3,"赵六");
    people.add(4,"田六");
    request.setAttribute("list",people);
%>
<%--
var,每一次遍历出来的变量
items,要遍历的对象
step,步长
--%>

     

JavaBean
//1.get和set
//2.无参构造器
//3.toString
//实体类一般与数据结构一一对应
public class People {
    private int id;
    private String name;
    private int age;
    private String address;

    public People() {
    }

    public People(int id, String name, int age, String address) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    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;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "People{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", age=" + age +
                ", address='" + address + ''' +
                '}';
    }
}
<%@ page import="com.liu.nn.People" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


<%
//    People people = new People();
//    people.setAddress();
//    people.setId();
//    people.setAge();
//    people.setName();
%>
<%--作用域scope="page"是当前页面--%>





<%--<%=people.getAddress()%>--%>
姓名:
id:
年龄:
地址:


MVC三层架构

Model

业务处理:业务逻辑(Service)数据持久层: CRUD (Dao)

View

展示数据提供链接发起Servlet请求(a, form, img…)

Controller (Servlet)

接收用户的请求: (req: 请求参数、Sessio信息)…交给业务层处理对应的代码控制视图的跳转 过滤器Filter(开发步骤) 1.导入包

Add framework Supprt…

    
      javax.servlet
      javax.servlet-api
      4.0.1
    

    
      javax.servlet.jsp
      javax.servlet.jsp-api
      2.3.3
    

    
      javax.servlet.jsp.jstl
      javax.servlet.jsp.jstl-api
      1.2.2
    

    
      taglibs
      standard
      1.1.2
    

    
        mysql
        mysql-connector-java
        8.0.19
    
2.编写过滤器

处理中文乱码

public class Utf8 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("你好!");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

实现Filter接口,重写对应的方法即可

package com.liu.filter;

import javax.servlet.*;
import java.io.IOException;

public class CharacterEncodingFilter implements Filter {
    //初始化:web服务器启动,就已经初始化了,随时等待过滤对象出现!
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CharacterEncodingFilter已经初始化");
    }
    //FilterChain filterChain chain:链

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletResponse.setCharacterEncoding("utf-8");
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");

        System.out.println("CharacterEncodingFilter执行前");
        filterChain.doFilter(servletRequest,servletResponse);//让我们的请求继续走,如果不写,程序到这里就被拦截停止!
        System.out.println("CharacterEncodingFilter执行后");
    }
    //销毁:web服务器关闭的时候,过滤会销毁
    @Override
    public void destroy() {
        System.out.println("CharacterEncodingFilter销毁");
    }
}
3.在web中配置filter


    
        ShowServlet
        com.liu.filter.Utf8
    
    
        ShowServlet
        /servlet/show
    
    
        ShowServlet
        /show
    


    
        Character
        com.liu.filter.CharacterEncodingFilter
    
    
        Character

        /servlet
    


    
超市订单管理系统
${error }

  login.jsp

    package com.liu.dao.user;
    
    import com.liu.pojo.User;
    
    import java.sql.Connection;
    
    public interface UserDao {
        public User getLoginUser(Connection connection,String userCode);
    }
    
    转载请注明:文章转载自 www.mshxw.com
    本文地址:https://www.mshxw.com/it/785859.html
    我们一直用心在做
    关于我们 文章归档 网站地图 联系我们

    版权所有 (c)2021-2022 MSHXW.COM

    ICP备案号:晋ICP备2021003244-6号