java web学习总结

servlet学习

1.1 基本配置

1.导入依赖

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>

2.创建一个servlet去继承HttpServlet,重写service方法,在该方法中写我们的一些操作

public class SchoolServlet extends HttpServlet {
	@Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1.首先编码设置
		req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        // 2. 响应结果 
        resp.getWriter().println("被访问了。");
	}
}

3.在web.xml中配置servlet

    <servlet>
        <servlet-name>add</servlet-name>
        <!---->
        <servlet-class>action.Servlet</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>add</servlet-name> 
    <!-- 测试地址是否符合要求,静态资源是否被拦截 **** tomcat 优先 找web.xml中的servlet的路径 , 如果找不到就找静态资源, 如 果还找不到,就404. 
    **** tomcat 优先精确匹配, 如果没有符合要求的,就模糊匹配。 **** 尽量避免特殊的后缀名: 比如.jsp , .css , .js ...... 
    ① / , 模糊匹配, 除了jsp之外,都会被匹配到。 
    ② /* , 模糊匹配,所有的地址都会被匹配到 
    ③ /*.xx , java.lang.IllegalArgumentException: servlet映射中的<url pattern>[/*.do]无效 
    ④ *.xx , 按后缀名进行匹配。 
    ⑤ /url , 精确地址 
    ⑥ /url.do , 精确地址 
    ⑦ url , 错误
     ⑧ url.do , 错误 -->
    <url-pattern>*.do</url-pattern>

1.2 一些用法

1.首先创建一个jsp页面

<%--
  Created by IntelliJ IDEA.
  User: 20473
  Date: 2022/9/13
  Time: 9:30
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>登录</title>
    </head>
    <body style="text-align: center">
        <form action="../login">
            <label>用户名:</label>
            <input type="text" name="uName">
            <br>
            <label style="margin-left: 1em">密码:</label>
            <input type="password" name="uPassword">
            <div style="margin: 5px 50px">
                <input type="submit" value="提交">
                <input type="reset" value="重置">
            </div>
        </form>
    </body>
</html>

<form action="../login"> 注意action写的是表单提交相对应servlet的地址

2.@WebServlet()配置servlet

添加Tomacat后使用,否则用不了

添加依赖

@WebServlet("/login") //通过该注解省去web.xml中的配置
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
}

3.得到页面传递过来的参数

req.getParameter()

4.session使用

 		HttpSession session = req.getSession();
 		//保存信息到session中
        session.setAttribute("user",uName);
        //设置有效期,单位秒,默认30分钟
        session.setMaxInactiveInterval(60);
        //session失效
        session.invalidate();  

5.cookie的使用

//创建cookie对象
 Cookie cookie = new Cookie("name",user);
 //设置cookie的存在时间,单位秒
 cookie.setMaxAge(2*60);
 //设置cookie的value值
 cookie.setValue();
 //添加cookie到浏览器中
 resp.addCookie(cookie);
 //得到浏览器中的cookie
 Cookie[] cookies = req.getCookies();

6.转发

转发是共享request, response对象 ,因此可以把需要转发的数据保存在request对象中。

        //设置属性
        req.setAttribute("books",books);
        //转发到jsp中
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("book/show.jsp");
        requestDispatcher.forward(req,resp);

jsp页面得到servlet传递过来的对象(脚本方式)

<%中间可以写java代码%>,<%=book.getId()%>得到属性值

例如书籍信息展示:

            <table>
            <tr>
                <th>书本编号</th>
                <th>类型编号</th>
                <th>书名</th>
                <th>作者</th>
                <th>价格</th>
                <th>出版日期</th>
                <th>库存</th>
                <th>操作</th>
            </tr>
            <%
                Object books = request.getAttribute("books");
                if (books != null) {
                    ArrayList<Book> list = (ArrayList<Book>) books;
                    for (Book book : list) {
            %>
            <tr>
                <td><%=book.getId()%></td>
                <td><%=book.getTyId()%></td>
                <td><%=book.getName()%></td>
                <td><%=book.getAuthor()%></td>
                <td><%=book.getPrice()%></td>
                <td><%=book.getDate()%></td>
                <td><%=book.getNum()%></td>
                <td>
                    <a href="query.do?book_id=<%=book.getId()%>">修改</a>
                    <a href="delete.do?book_id=<%=book.getId()%>">删除</a>
                </td>
            </tr>
            <%
                    }
                }
            %>
        </table>

7.重定向

System.out.println(req.getContextPath());//"/web01" System.out.println(req.getRequestURL());//http://localhost:8080/web01/b.do System.out.println(req.getServletPath());// "/b.do

resp.sendRedirect(req.getContextPath() + "/show.do");

8.el表达式
同理,先是servlet转发request, response对象,然后再jsp页面上进行使用

 //设置属性
        req.setAttribute("books",books);
        //转发到jsp中
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("book/show.jsp");
        requestDispatcher.forward(req,resp);

用法${}

<label style="margin-left: 2em;">书名:</label>
<input type="text" name="book_name" value="${book.name}">

EL表达式不仅能获取Servlet中存储的数据,也能简化JSP中的代码量,使程序简单易维护,另外,当域对象里面的值不存在时,使用EL表达式获取域对象里面的值返回空字符串;而使用Java脚本方式获取,返回值是null,会报空指针异常。

el表达式具体详情可以参考JavaWeb——EL表达式

过滤器

过滤器是sun提供一个组件, 需要依赖于tomcat容器运行。
过滤器的执行过程: 访问请求的时候,先根据过滤器的配置,符号过滤器路径的请求,则先进入到过滤器中执行,执行结束之后,再根据情况,看是否需要进入到servlet中。
例如未登录不让访问

public class Filter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String requestURI = request.getRequestURI();
		//登录界面不过滤
        if (requestURI.contains("login")){
            chain.doFilter(request,response);
            return;
        }
        HttpSession session = request.getSession();
        if (session.getAttribute("user") != null){
            //调用下一个过滤器的doFilter方法,如果没有就执行servlet
            chain.doFilter(request,response);
        }else {
            response.getWriter().println("请先登录");
        }
    }
}

web.xml配置过滤器的拦截

<filter>
	<filter-name>hh</filter-name> 
	<filter-class>action.LoginFilter</filter-class>
 </filter> 
 <filter-mapping>
  	<filter-name>hh</filter-name> 
  <!-- /* 所有的都拦截 , jsp也拦截--> 
  <!-- / 不拦截jsp--> 
  <!-- /add ,表示只拦截/add请求 --> 
  	<url-pattern>/*</url-pattern>
  </filter-mapping>

监听器

监听器在后台工作,可以设置需要监听的内容
例如对请求次数的统计

public class Listener implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {

    }
    //每次请求一次统计数据
    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        ServletContext servletContext = servletRequestEvent.getServletContext();
        Object count = servletContext.getAttribute("count");
        if (count == null){
        	//第一次请求,创建count
            servletContext.setAttribute("count",1);
        }else {
            int num = (int) count + 1;
            servletContext.setAttribute("count",num);
        }
    }
}

同理在web.xml中配置

    <listener>
        <listener-class>action.Listener</listener-class>
    </listener>

ajax使用

$.ajax({ 
	url: "hobby", // 请求的url 
	data: args, // 请求参数 
	type: "get", // 请求的方式 
	dataType: "json",// 期待的响应结果的格式 
	success:function (res) {//成功之后,// res ==> {"success":true} 
 		if(res.success){ 
 			alert("成功") 
 		}else{
 			alert("失败了") 
 		} 
 	} 
 })

jsp内置对象

request : 请求
session : 会话
out : 输出语句
response : 响应结果
page : 类似于this
pageContext : 有效范围只在当前的jsp页面上
application: ServletContext
config : servlet的数据
exception: 异常
作用域

pageContext :只在当前页面有效
request : 请求期间有效
session: 会话期间有效
application : 程序运行期间有效

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值