- 关于servlet3.0 介绍不多说,直接进入开发主题
先写个登陆页面,代码如下
- index.jsp 页面
-
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String msg = request.getParameter("msg"); %> <!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="login" method="post" style="text-align: center;"> <h1>用户登陆</h1> 用户名:<input type="text" name="username"> <br/> 密 码:<input type="password" name="password"> <br/> <input type="submit" value="登陆"><br/> <span id="msg"><%=msg %></span> </form> <script type="text/javascript"> var msg = <%=msg%>; if(msg==null){ document.getElementById("msg").style.display = "none"; } </script> </body> </html>
原来需要在web.xml中配置,如下,在servlet3.0中通过注解功能,不再需要web.xml配置
-
<servlet> <servlet-name>login</servlet-name> <servlet-class>com.action.Login</servlet-class> </servlet> <servlet-mapping> <servlet-name>login</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping>
servlet 代码如下
-
package com.action; 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; /** * @author zhuweishi * @version 1.1.0 */ /* * @SuppressWarnings 表示不提示警告信息 * @WebServlet * name 相当于web.xml中servlet的servlet-name * urlPatterns servlet-maring 中的url-pattern * loadOnStartup 加载顺序 * inintParams 初始值 */ @SuppressWarnings("serial") @WebServlet(name="Test",urlPatterns={"/login","/test/login"},loadOnStartup=1,
-
initParams={@WebInitParam(name="usname",value="张三")}) public class Login extends HttpServlet{ @Override public void init(ServletConfig config) throws ServletException { //ServletConfig config = this.getServletConfig(); String usname = config.getInitParameter("usname"); System.out.println(usname+"-----"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); String password = req.getParameter("password"); System.out.println(username+"==="+password); resp.setCharacterEncoding("UTF-8"); if("sysadmin".equals(username)){ if("000000".equals(password)){ // 设置作用域 req.setAttribute("username", username); //转发 req.getRequestDispatcher("/login.jsp").forward(req,resp); }else{ String msg = java.net.URLEncoder.encode("密码错误!", "utf-8"); resp.sendRedirect(req.getContextPath()+"/index.jsp?msg="+msg); } }else{ // 解决中文乱码 String msg = java.net.URLEncoder.encode("用户名错误!", "utf-8"); resp.sendRedirect(req.getContextPath()+"/index.jsp?msg="+msg); } } }
写一个 中文乱码的Filter
package com.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; /* * 原来 web.xml 配置 * <filter> * <filter-name>UTFFilter</filter-name> * <filter-class>com.action.UTFFilter</filter-class> * <init-param> * <param-name>enconding</param-name> * <param-value>UTF-8</param-value> * </init-param> * </filter> * <filter-mapping> * <filter-name>UTFFilter</filter-name> * <url-pattern>/*</url-pattern> * </filter-mapping> * ------------------------------------------------- * filterName 对应web.xml 中filter-name * value 对应web.xml 中 url-pattern * servletNames 是指定那个servlet的name */ @WebFilter(filterName="UTFFilter",value="/*",servletNames={"Test"}) public class UTFFilter implements Filter{ @Override public void destroy() { System.out.println("======销毁======"); } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // 设置编码方式 req.setCharacterEncoding("UTF-8"); chain.doFilter(req, res); } @Override public void init(FilterConfig config) throws ServletException { System.out.println("======初始化====="); } }
登陆成后的页面
login.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>Insert title here</title> </head> <body> 欢迎 ${username} </body> </html>
强制登陆
package com.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 chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)req; HttpSession session = request.getSession(); // 获取登陆用户名 String username = (String)session.getAttribute("username"); // 获取请求的uri String uri = request.getRequestURI(); System.out.println("username:"+username+"=========="); if(username != null){ chain.doFilter(request, res); }else if(uri.contains("/login")){ chain.doFilter(request, res); }else{ System.out.println("===else===="); request.getRequestDispatcher("/index.jsp").forward(req, res); } } @Override public void init(FilterConfig arg0) throws ServletException { } }
这里需要把上面servlet中的Login 修改下 session作用域
// 设置作用域 req.getSession().setAttribute("username", username); // 加上这句 //req.setAttribute("username", username); 注释掉
上传文件
- 上传文件的servlet
-
package com.action; 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("/upload") @MultipartConfig public class Upload extends HttpServlet{ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取文件部件 part Part part = req.getPart("upfile"); String name = part.getHeader("content-disposition"); System.out.println(name); System.out.println("partName:"+part.getName()); // 上传路径 String root = req.getServletContext().getRealPath("/upload"); System.out.println("root:"+root); // 后缀名 String str = name.substring(name.lastIndexOf("."),name.length()-1); System.out.println("str:"+str); // 重命名 String filename = root + "\\"+UUID.randomUUID().toString()+str; part.write(filename); } }
修改login.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>Insert title here</title> </head> <body> 欢迎 ${username} <br/> <form action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="upfile"><br/> <input type="submit" value="上传"> </form> </body> </html>
此时上传就可以了
写的不是很详细,只是粗略的进行了下测试
如果不足,多多指导。
时间: 2024-10-30 01:39:28