Spring项目结构
package com.layne.my.shop.common.context; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.DisposableBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class SpringContext implements ApplicationContextAware, DisposableBean { private static final Logger logger = LoggerFactory.getLogger(SpringContext.class); private static ApplicationContext applicationContext; /** * 获取存储在静态变量中的 ApplicationContext * @return */ public static ApplicationContext getApplicationContext() { assertContextInjected(); return applicationContext; } /** * 使用ApplicationContext,根据BeanId获取实例 * @param beanId * @param <T> * @return */ public static <T> T getBeanExample(String beanId){ assertContextInjected(); return (T) applicationContext.getBean(beanId); } /** * 使用ApplicationContext,根据BeanId获取实例 * @param clazz * @param <T> * @return */ public static <T> T getBeanExample(Class<T> clazz){ assertContextInjected(); return applicationContext.getBean(clazz); } @Override public void destroy() throws Exception { logger.debug("清空ApplicationContext"); applicationContext=null; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContext.applicationContext=applicationContext; } /* public Object getBean(String beanId){ ApplicationContext context=new ClassPathXmlApplicationContext("spring-context.xml"); return context.getBean(beanId); }*/ /** * 断言容器【ApplicationContext】已经注入 * public static void validState(boolean expression, String message, Object... values) { * if (!expression) { * throw new IllegalStateException(String.format(message, values)); * } * } * * 1.applicationContext!=null----->applicationContext为空---->applicationContext!=null【false】------>!expression【true】 * 2.applicationContext==null----->applicationContext为空---->applicationContext!=null【true】------>!expression【false】 */ private static void assertContextInjected(){ Validate.validState(applicationContext!=null,"你还没有在spring-context.xml中配置SpringContext对象"); } }
POM.XML
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.layne</groupId> <artifactId>my-shop</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <slf4j.version>1.7.25</slf4j.version> <log4j.version>1.2.17</log4j.version> <spring.version>4.3.17.RELEASE</spring.version> <servlet-api.version>4.0.1</servlet-api.version> <commons-lang3>3.5</commons-lang3> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet-api.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jul-to-slf4j</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang3}</version> </dependency> </dependencies> </project>
WEB.XML
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-context*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>LoginController</servlet-name> <servlet-class>com.layne.my.shop.web.controller.LoginController</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginController</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> </web-app>
INDEX.JSP
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <!--Head Begin--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>我的商城 | 登录</title> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <!-- Bootstrap 3.3.7 --> <link rel="stylesheet" href="assets/bower_components/bootstrap/dist/css/bootstrap.min.css"/> <!-- Font Awesome --> <link rel="stylesheet" href="assets/bower_components/font-awesome/css/font-awesome.min.css"/> <!-- Ionicons --> <link rel="stylesheet" href="assets/bower_components/Ionicons/css/ionicons.min.css"/> <!-- Theme style --> <link rel="stylesheet" href="assets/css/AdminLTE.min.css"/> <!-- iCheck --> <link rel="stylesheet" href="assets/plugins/iCheck/square/blue.css"/> </head> <!--Head end--> <body class="hold-transition login-page"> <div class="login-box"> <div class="login-logo"> <a href="#">我的商城</a> </div> <!-- /.login-logo --> <div class="login-box-body"> <p class="login-box-msg">欢迎管理员登录</p> <form action="/login" method="post"> <%--<c:if test="${message != null}"> <div class="alert alert-danger alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ${message} </div> </c:if>--%> <div class="alert alert-danger alert-dismissible" ${message==null?"style='display: none'":""}> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ${message} </div> <div class="form-group has-feedback"> <input type="email" class="form-control" name="email" placeholder="邮箱"> <span class="glyphicon glyphicon-envelope form-control-feedback"></span> </div> <div class="form-group has-feedback"> <input type="password" class="form-control" name="password" placeholder="密码"> <span class="glyphicon glyphicon-lock form-control-feedback"></span> </div> <div class="row"> <div class="col-xs-8"> <div class="checkbox icheck"> <label> <input type="checkbox"> 记住我 </label> </div> </div> <!-- /.col --> <div class="col-xs-4"> <button type="submit" class="btn btn-primary btn-block btn-flat">登录</button> </div> <!-- /.col --> </div> </form> <a href="#">忘记密码</a><br> </div> </div> <!-- /.login-box--> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"/> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"/> <![endif]--> <!-- jQuery 3 --> <script src="assets/bower_components/jquery/dist/jquery.min.js"></script> <!-- Bootstrap 3.3.7 --> <script src="assets/bower_components/bootstrap/dist/js/bootstrap.min.js"></script> <!-- iCheck --> <script src="assets/plugins/iCheck/icheck.min.js"></script> <script> $(function () { $('input').iCheck({ checkboxClass: 'icheckbox_square-blue', radioClass: 'iradio_square-blue', increaseArea: '20%' /* optional */ }); }); </script> </body> </html>
log4j.properties
log4j.rootLogger=INFO, console, file log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%d %p [%c] - %m%n log4j.appender.file=org.apache.log4j.DailyRollingFileAppender log4j.appender.file.File=logs/log.log log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.A3.MaxFileSize=1024KB log4j.appender.A3.MaxBackupIndex=10 log4j.appender.file.layout.ConversionPattern=%d %p [%c] - %m%n
CookieUtils
package com.layne.my.shop.common.context.utils; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; public final class CookieUtils { /** * 得到Cookie的值, 不编码 * * @param request * @param cookieName * @return */ public static String getCookieValue(HttpServletRequest request, String cookieName) { return getCookieValue(request, cookieName, false); } /** * 得到Cookie的值, * * @param request * @param cookieName * @return */ public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) { Cookie[] cookieList = request.getCookies(); if (cookieList == null || cookieName == null) { return null; } String retValue = null; try { for (int i = 0; i < cookieList.length; i++) { if (cookieList[i].getName().equals(cookieName)) { if (isDecoder) { retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8"); } else { retValue = cookieList[i].getValue(); } break; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return retValue; } /** * 得到Cookie的值, * * @param request * @param cookieName * @return */ public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) { Cookie[] cookieList = request.getCookies(); if (cookieList == null || cookieName == null) { return null; } String retValue = null; try { for (int i = 0; i < cookieList.length; i++) { if (cookieList[i].getName().equals(cookieName)) { retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString); break; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return retValue; } /** * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码 */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue) { setCookie(request, response, cookieName, cookieValue, -1); } /** * 设置Cookie的值 在指定时间内生效,但不编码 */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage) { setCookie(request, response, cookieName, cookieValue, cookieMaxage, false); } /** * 设置Cookie的值 不设置生效时间,但编码 */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, boolean isEncode) { setCookie(request, response, cookieName, cookieValue, -1, isEncode); } /** * 设置Cookie的值 在指定时间内生效, 编码参数 */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) { doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode); } /** * 设置Cookie的值 在指定时间内生效, 编码参数(指定编码) */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString) { doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString); } /** * 删除Cookie带cookie域名 */ public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) { doSetCookie(request, response, cookieName, "", -1, false); } /** * 设置Cookie的值,并使其在指定时间内生效 * * @param cookieMaxage cookie生效的最大秒数 */ private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) { try { if (cookieValue == null) { cookieValue = ""; } else if (isEncode) { cookieValue = URLEncoder.encode(cookieValue, "utf-8"); } Cookie cookie = new Cookie(cookieName, cookieValue); if (cookieMaxage > 0) cookie.setMaxAge(cookieMaxage); if (null != request) {// 设置域名的cookie String domainName = getDomainName(request); // System.out.println(domainName); if (!"localhost".equals(domainName)) { cookie.setDomain(domainName); } } cookie.setPath("/"); response.addCookie(cookie); } catch (Exception e) { e.printStackTrace(); } } /** * 设置Cookie的值,并使其在指定时间内生效 * * @param cookieMaxage cookie生效的最大秒数 */ private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString) { try { if (cookieValue == null) { cookieValue = ""; } else { cookieValue = URLEncoder.encode(cookieValue, encodeString); } Cookie cookie = new Cookie(cookieName, cookieValue); if (cookieMaxage > 0) cookie.setMaxAge(cookieMaxage); if (null != request) {// 设置域名的cookie String domainName = getDomainName(request); // System.out.println(domainName); if (!"localhost".equals(domainName)) { cookie.setDomain(domainName); } } cookie.setPath("/"); response.addCookie(cookie); } catch (Exception e) { e.printStackTrace(); } } /** * 得到cookie的域名 */ private static final String getDomainName(HttpServletRequest request) { String domainName = null; String serverName = request.getRequestURL().toString(); if (serverName == null || serverName.equals("")) { domainName = ""; } else { serverName = serverName.toLowerCase(); serverName = serverName.substring(7); final int end = serverName.indexOf("/"); serverName = serverName.substring(0, end); final String[] domains = serverName.split("\\."); int len = domains.length; if (len > 3) { // www.xxx.com.cn domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1]; } else if (len <= 3 && len > 1) { // xxx.com or xxx.cn domainName = "." + domains[len - 2] + "." + domains[len - 1]; } else { domainName = serverName; } } if (domainName != null && domainName.indexOf(":") > 0) { String[] ary = domainName.split("\\:"); domainName = ary[0]; } return domainName; } }
LoginController
package com.layne.my.shop.web.controller; import com.layne.my.shop.common.context.SpringContext; import com.layne.my.shop.common.context.utils.CookieUtils; import com.layne.my.shop.dao.UserDao; import com.layne.my.shop.entity.User; import com.layne.my.shop.service.UserService; import org.apache.commons.lang3.StringUtils; import org.springframework.context.ApplicationContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class LoginController extends HttpServlet { private UserService userService=SpringContext.getBeanExample("userService"); private static final String COOKIE_NAME_USER_INFO="userInfo"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String userInfo = CookieUtils.getCookieValue(req, COOKIE_NAME_USER_INFO); if(!StringUtils.isBlank(userInfo)){ String[] userInfoArray=userInfo.split(":"); String email=userInfoArray[0]; String password=userInfoArray[1]; req.setAttribute("email",email); req.setAttribute("password",password); req.setAttribute("isRemember",true); } req.getRequestDispatcher("/login.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /* SpringContext springContext=new SpringContext(); UserService userService = (UserService) springContext.getBean("userService");*/ boolean isRemember=req.getParameter("isRemember")==null?false:true; String email = req.getParameter("email"); String password = req.getParameter("password"); User admin=userService.login(email,password); if(admin!=null){ if(isRemember){ //CookieUtils.setCookie(req,resp,"userInfo",email+":"+password,); CookieUtils.setCookie(req,resp,COOKIE_NAME_USER_INFO,String.format("%s:%s",email,password),7*24*60*60); }else{ CookieUtils.deleteCookie(req,resp,COOKIE_NAME_USER_INFO); } resp.sendRedirect("/main.jsp"); }else{ req.setAttribute("message","登录名或密码错误"); req.getRequestDispatcher("/index.jsp").forward(req,resp); } } }