美文网首页java
Servlet3.0注解技术

Servlet3.0注解技术

作者: dravenxiaokai | 来源:发表于2017-10-14 21:59 被阅读0次

    PS: 自从专注前端以来,已经好久没有碰 java了,现在重新复习来感受一下 java,不管来得及来不及,学无止境,能够拿来做项目才是硬道理

    因为我是非常喜欢注解这个东西的,这是个好东西,在学习 angular2+ 的时候,里面就新增了注解 annotation 的方法,现在 servlet3.0 出来以后多了注解,这是我非常喜欢的,也是我为什么写这篇文章的缘由之一吧

    Servlet 各版本对应的环境

    Servlet Spec JSP Spec EL Spec WebSocket Spec JASPIC Spec Apache Tomcat version Actual release revision Supported Java Versions
    4.0 TBD (2.4?) TBD (3.1?) TBD (1.2?) 1.1 9.0.X 9.0.0.M15 (alpha) 8 and later
    3.1 2.3 3.0 1.1 1.1 8.5.X 8.5.9 7 and later
    3.1 2.3 3.0 1.1 N/A 8.0.X (superseded) 8.0.39 (superseded) 7 and later
    3.0 2.2 2.2 1.1 N/A 7.0.X 7.0.7.3 6 and later (7 and later for WebSocket)
    2.5 2.1 2.1 N/A N/A 6.0.X 6.0.4.8 5 and later

    @WebServlet

    /** LoginServlet.java **/
    package ren.draven.servlet;
    
    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("/login")
    public class LoginServlet extends HttpServlet {
    
        private static final long serialVersionUID = 1L;
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    //      super.doPost(req, res); //下面有跳转,这一行得注释掉,不然启动 tomcat 会报错
            System.out.println("----------doPost----------");
    
            String userName = req.getParameter("userName");
            String userPwd = req.getParameter("userPwd");
    
            System.out.println(userName);
            System.out.println(userPwd);
    
            if ("admin".equals(userName) && "admin123".equals(userPwd)) {
                req.setAttribute("userName", userName);
                req.getRequestDispatcher("/index.jsp").forward(req, res);
            } else {
                req.getRequestDispatcher("/fail.jsp").forward(req, res);
            }
        }
    
    }
    
    
    <!-- login.jsp -->
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>login</title>
    </head>
    <body>
        <form action="login" method="post">
            <h1>用户登录</h1>
            账号:<input type="text" name="userName"><br>
            密码:<input type="password" name="userPwd"><br>
            <input type="submit" value="登录">
        </form>
    </body>
    </html>
    
    <!-- index.jsp -->
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
        <h1>恭喜您,${userName} 登录成功</h1>
    </body>
    </html>
    
    <!-- fail.jsp -->
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
        <h1>账号或密码错误,登录失败</h1>
    </body>
    </html>
    

    如果新建 web 项目的时候,生成了 web.xml 配置文件,如果想要取消注解的功能的话,可以在 web-app 标签中添加属性 metadata-complete="true"

    以前的 Servlet 在 web.xml 中的配置

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
        id="WebApp_ID" version="3.1">
        
        <display-name>testdemo</display-name>
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
        </welcome-file-list>
    
        <servlet>
            <servlet-name>TestServlet</servlet-name>
            <servlet-class>ren.draven.servlet.TestServlet</servlet-class>
            <init-param>
                <param-name>nickname</param-name>
                <param-value>小凯</param-value>
            </init-param>
        </servlet>
        <servlet-mapping>
            <servlet-name>TestServlet</servlet-name>
            <url-pattern>/test</url-pattern>
        </servlet-mapping> 
        <servlet-mapping>
            <servlet-name>TestServlet</servlet-name>
            <url-pattern>/testServlet</url-pattern>
        </servlet-mapping> 
    </web-app>
    

    @WebInitParam

    对比 servlet3.0 中的注解方式,省略 web.xml 文件的配置

    /* TestServlet.java */
    package ren.draven.servlet;
    
    import java.io.IOException;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebInitParam;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /*
     * <servlet>
            <servlet-name>TestServlet</servlet-name>
            <servlet-class>ren.draven.servlet.TestServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>TestServlet</servlet-name>
            <url-pattern>/test</url-pattern>
        </servlet-mapping>
        
        name === <servlet-name>
        urlPatterns === <url-pattern>
        urlPatterns 和 value 等同,只能二选一
        
        loadOnStartup === <load-on-startup></load-on-startup>
        
        @WebInitParam(name="",value="") === 
            <init-param>
                <param-name>nickname</param-name>
                <param-value>小凯</param-value>
            </init-param>
     */
    
    @WebServlet(name = "TestServlet", urlPatterns = { "/test", "/testServlet" }, loadOnStartup = 1,initParams= {@WebInitParam(name="nickname",value="小凯")})
    public class TestServlet extends HttpServlet {
    
        @Override
        public void init() throws ServletException {
            ServletConfig config = this.getServletConfig();
            String name = config.getInitParameter("nickname");
            System.out.println("-------init-----: " + name);
        }
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("------doGet--------");
        }
    
    }
    

    @WebFilter

    /* UTFFilter */
    package ren.draven.filter;
    
    import java.io.IOException;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.annotation.WebFilter;
    
    /**
     * <filter>
        <filter-name>UTFFilter</filter-name>
        <filter-class>ren.draven.filter.UTFFilter</filter-class>
      </filter>
      <filter-mapping>
        <filter-name>UTFFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
      
     * @author dravenxiaokai
     *
     *  filterName <==> <filter-name>
     *  urlPatterns="/*" <==> <url-pattern>/*</url-pattern>
     *  urlPatterns <==> value
     */
    
    @WebFilter(filterName="UTFFilter",value= {"/*"},servletNames = {"LoginServlet"})
    public class UTFFilter implements Filter{
    
        @Override
        public void destroy() {
            System.out.println("------销毁---------");
        }
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
                throws IOException, ServletException {
            // 设置字符编码集
            req.setCharacterEncoding("utf-8");
            filterChain.doFilter(req, res);
        }
    
        @Override
        public void init(FilterConfig arg0) throws ServletException {
            System.out.println("------初始化--------");
            
        }
    
    }
    

    登录验证

    /** LoginServlet.java **/
    package ren.draven.servlet;
    
    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("/login")
    public class LoginServlet extends HttpServlet {
    
        private static final long serialVersionUID = 1L;
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
            // super.doPost(req, res); //下面有跳转,这一行得注释掉,不然启动 tomcat 会报错
            System.out.println("----------doPost----------");
    
            String userName = req.getParameter("userName");
            String userPwd = req.getParameter("userPwd");
    
            System.out.println(userName);
            System.out.println(userPwd);
    
            if ("admin".equals(userName) && "admin123".equals(userPwd)) {
                // 登录成功,把账号保存到 session 中
                HttpSession session = req.getSession();
                session.setAttribute("user", userName);
    
                req.getRequestDispatcher("/index.jsp").forward(req, res);
            } else {
                req.getRequestDispatcher("/fail.jsp").forward(req, res);
            }
        }
    
    }
    
    /* LoginFilter.java */
    package ren.draven.filter;
    
    import java.io.IOException;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    
    @WebFilter("/*")
    public class LoginFilter implements Filter {
    
        @Override
        public void destroy() {
        }
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
                throws IOException, ServletException {
            // 获取 HttpServletRequest
            HttpServletRequest req2 = (HttpServletRequest) req;
            // 获取 session
            HttpSession session = req2.getSession();
    
            String user = (String) session.getAttribute("user");
            // 获取请求的地址
            String uri = req2.getRequestURI();
            System.out.println(uri);
    
            if (user != null) {
                filterChain.doFilter(req2, res);
            } else if (uri.contains("/login")) {
                filterChain.doFilter(req2, res);
            } else {
                req2.getRequestDispatcher("/login.jsp").forward(req, res);
            }
        }
    
        @Override
        public void init(FilterConfig arg0) throws ServletException {
        }
    }
    

    常规的 Listener

    /* MyListener.java */
    package ren.draven.listener;
    
    import javax.servlet.http.HttpSessionEvent;
    import javax.servlet.http.HttpSessionListener;
    
    public class MyListener implements HttpSessionListener {
    
        @Override
        public void sessionCreated(HttpSessionEvent arg0) {
            System.out.println("------sessionCreated-------");
        }
    
        @Override
        public void sessionDestroyed(HttpSessionEvent arg0) {
            System.out.println("-----sessionDestroyed------");
        }
    }
    
    /* web.xml */
      <listener>
        <listener-class>ren.draven.listener.MyListener</listener-class>
      </listener>
    

    @WebListener

    /* MySessionListener.java */
    package ren.draven.listener;
    
    import javax.servlet.annotation.WebListener;
    import javax.servlet.http.HttpSessionAttributeListener;
    import javax.servlet.http.HttpSessionBindingEvent;
    
    @WebListener
    public class MySessionListener implements HttpSessionAttributeListener {
    
        @Override
        public void attributeAdded(HttpSessionBindingEvent event) {
            System.out.println("key: " + event.getName() + " value: " + event.getValue());
            System.out.println("-----attributeAdded-------");
        }
    
        @Override
        public void attributeRemoved(HttpSessionBindingEvent event) {
            System.out.println("key: " + event.getName() + " value: " + event.getValue());
            System.out.println("------attributeRemoved-------");
        }
    
        @Override
        public void attributeReplaced(HttpSessionBindingEvent event) {
            System.out.println("key: " + event.getName() + " value: " + event.getValue());
            System.out.println("-------attributeReplaced------");
        }
    }
    
    /* index.jsp */
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>index.jsp</title>
    </head>
    <body>
        <%
            // 销毁
            session.invalidate();
        %>
    </body>
    </html>
    
    /* add.jsp */
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>add.jsp</title>
    </head>
    <body>
        <%
            session.setAttribute("username", "小凯");
        %>
    </body>
    </html>
    
    /* remove.jsp */
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>remove.jsp</title>
    </head>
    <body>
        <%
            session.setAttribute("username", "小凯");
            session.removeAttribute("username");
        %>
    </body>
    </html>
    
    /* replace.jsp */
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>replace.jsp</title>
    </head>
    <body>
        <%
            session.setAttribute("username", "小凯");
            //session.removeAttribute("username");
            session.setAttribute("username", "draven");
        %>
    </body>
    </html>
    

    Servlet3.0 中的上传

    /* file.jsp */
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>上传文件</title>
    </head>
    <body>
        <form action="uploadFile" method="post" enctype="multipart/form-data">
            <input type="file" name="upfile">
            <input type="submit" value="上传">
        </form>
    </body>
    </html>
    
    /* UploadFileServlet.java */
    package ren.draven.servlet;
    
    import java.io.IOException;
    import java.util.UUID;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;
    
    @WebServlet("/uploadFile")
    @MultipartConfig
    public class UploadFileServlet extends HttpServlet {
    
        private static final long serialVersionUID = 1L;
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
            // 获取文件部件 part
            Part part = req.getPart("upfile");
    
            // 获取请求的信息
            String name = part.getHeader("content-disposition");
            System.out.println(name);
    
            String root = req.getServletContext().getRealPath("/upload");
            System.out.println(root);
    
            // 文件类型后缀
            String str = name.substring(name.lastIndexOf("."), name.length() - 1);
            System.out.println(str);
            // 新的路径文件名
            String uploadPath = "d:/upload";
            // String filename = root + "\\" + UUID.randomUUID().toString() + str;
            String filename = uploadPath + "/" + UUID.randomUUID().toString() + str;
            System.out.println(filename);
    
             part.write(filename);
        }
    }
    
    /* 控制台结果输出 */
    form-data; name="upfile"; filename="D:\Downloads\潘凯的个人简历.pdf"
    D:\workspace-j2ee\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\servlet3upload\upload
    .pdf
    d:/upload/d4773501-225a-484e-b953-42231b9409d0.pdf
    

    项目源代码:


    想要查看更多文章,敬请关注 dravenxiaokai 的简书

    哇,写的太赞了,别拦着我打赏 o( ̄︶ ̄)o

    微信打赏 支付宝打赏

    相关文章

      网友评论

        本文标题:Servlet3.0注解技术

        本文链接:https://www.haomeiwen.com/subject/txdxuxtx.html