首页 > 代码库 > servlet简单用法
servlet简单用法
一、创建java web项目
参考
二、创建LoginServlet类
LoginServlet需要继承HttpServlet,并重写四个方法:
- init()
- doGet()
- doPost()
- destroy()
package com.httpshttp.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void init(ServletConfig config) throws ServletException { } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String certName = req.getHeader("client-cert-dn"); String scheme = req.getHeader("X-Forwarded-Proto"); if (scheme == null) scheme = "http"; String username = req.getParameter("username"); String context = req.getContextPath(); PrintWriter out = resp.getWriter(); out.println("<html><head><title>test</title></head><body>"); if (username == null || "".equals(username)) { resp.sendRedirect(context); } if ("https.user".equals(username) && "http".equals(scheme)) { out.println("user " + username + " need authentication, wait 8 seconds for redirecting, or click "); out.println("<a href="http://www.mamicode.com/+"https://demo.belle.net.cn/httpshttp" + ">" + "ssl portal" + "</a>"); out.println("<script language=‘javascript‘>"); out.println("window.setTimeout(\"window.location=\‘https://demo.belle.net.cn/httpshttp\‘\",8000); "); out.println("</script>"); out.println("</body></html>"); out.close(); return; } if (certName != null && !("/CN=" + username).equals(certName)) { out.println("user " + username + " login success"); out.println(" ,but does not match certificate name " + certName); } else { out.println("user " + username + " login success"); } out.println("</body></html>"); out.close(); } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { doGet(req, resp); } public void destroy() { } }
三、配置web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>demo</display-name> <servlet> <servlet-name>login</servlet-name> <servlet-class>com.httpshttp.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>login</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> </web-app>
四、浏览器访问
servlet简单用法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。