第二篇 -- 写一个登录界面
第一篇讲了如何写一个HelloWorld程序,今天了解一下如何写一个登录界面。
一、准备MySQL数据
方法1. 通过命令行创建
第1步:查看数据库
第二步:新建一个user的数据库(用来存放用户信息)
第三步:创建一个user表格(存放ID,用户名和密码)
第三步:给表中添加数据
方法2. 通过MySQL Workbench添加
第一步:先认识MySQL Workbench界面
可以看到数据库有user,就是刚刚用命令行创建的一个数据库
第二步:创建数据库
点击apply,可以看到多了一个userui的数据库
第三步:创建数据表
第四步:看下之前cmd版创建的user表格式是怎样的
第五步:配置数据表
点击Apply,可以看到user已经创建好了。
第六步:瞧一瞧user表里的数据,并添加数据
好了,MySQL Workbench添加数据库的方法也了解了,数据库现在已经Ready了。
二、实现登录页面程序
第一步:按照上篇介绍新建一个HelloWorld项目并能运行成功。
(乱码问题上节讲过,这里不重要)
第二步:将页面访问主页定位到登录页面并编写登录页面
在HomeController.java中指定登录页面为login
在views文件夹新建一个jsp文件
login.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ page session="false"%> <%@ page language="java" contentType="text/html; charset=UTF-8" import="java.util.*" pageEncoding="UTF-8"%> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Login</title> </head> <body> <form role="form" action="index" method="post"> <fieldset> <div class="form-group"> <label for="name">Name: </label> <input class="form-control" placeholder="Name" name="name" type="name" style="font-size: 16px;text-align:left;" maxlength="30"> </div> <div class="form-group"> <label for="password">Password: </label> <input class="form-control" placeholder="Password" name="password" type="password" style="font-size: 16px;text-align:left;" maxlength="30"> </div> <div align="center" class="form-group"> <button type="submit" class="btn btn-lg btn-success btn-default btn-block" name="Login">Login</button> </div> <p style="font-size: 14px; line-height: 150%; font-family: consolas;"> <font color="red">${Error}</font> </p> </fieldset> </form> </body> </html>
然后运行一遍代码,可以看到结果
第三步:获取用户输入的数据
在HomeController.java中添加
然后运行程序,输入账号密码,点击Login按钮,看是否触发这个函数,打印出account
可以看到成功打印出你输的账户信息,那么接下来就是连接到数据库去查找有没有这个用户了。
第四步:连接已经准备好的数据库。
1. 右键LoginPage项目,【New】-->【Package】,Name就填com.free.entity。
2. 在com.free.entity下新建一个User.java,右键com.free.entity,【New】--> 【Class】,Name就填User。当然java的名称自己可以取的。这个文件对应前面数据库中的数据(id, name, password)
User.java
package com.free.entity; public class User { private Integer id; private String name; private String password; public Integer getuser_id() { return id; } public void setuser_id(Integer User_id) { id = User_id; } public String getuser_name() { return name; } public void setuser_name(String User_name) { name = User_name; } public String getpassword() { return password; } public void setpassword(String Password) { password = Password; } public User(Integer User_id, String User_name, String Password) { super(); id = User_id; name = User_name; password = Password; } }
3. 新建一个com.free.dao包,在其下新建一个UserDao.java,用来写操作数据库的方法接口
UserDao.java
package com.free.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.free.entity.User; public interface UserDao { User login(@Param("name") String name,@Param("password") String password); //这个地方的name和Usermapper里面login中select语句#{name}对应 }
4. 新建一个com.free.mapper,实现UserDao里面的方法,这里用到了mybatis。在com.free.mapper下新建一个Usermapper.xml文件,【New】--> 【Other】--> 【Web】--> 【XML File】,取名为Usermapper。
Usermapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.free.dao.UserDao"> <resultMap id="user" type="com.free.entity.User"> <id column="id" property="id" jdbcType="INTEGER" /> <result column="name" property="name" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> </resultMap> <select id="login" resultMap="user"> SELECT * FROM user WHERE name=#{name} AND password=#{password}; </select> </mapper>
5. 配置mybatis和mysql
在src/main/resources下建立一个mybatis的文件夹,右键src/main/resources,【New】--> 【Folder】,Name就填mybatis。
在mybatis文件夹下新建mybatis的配置文件,右键mybatis,【New】-->【Other】--> 【MyBatis】--> 【MyBatis XML Mapper】,取名为mybatis-config。
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> </configuration>
在src/main/resources下面新建一个properties文件夹,在此文件夹下建立一个jdbc.properties文件,【New】--> 【File】,取名为jdbc.properties。
jdbc.properties
jdbc_driverClassName=com.mysql.jdbc.Driver jdbc_url=jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=utf8 jdbc_username=root jdbc_password=password
修改pom.xml, src\main\webapp\WEB-INF\web.xml, src\main\webapp\WEB-INF\spring\root-context.xml, src\main\webapp\WEB-INF\spring\appServlet\servlet-context.xml
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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.free</groupId> <artifactId>loginpage</artifactId> <name>loginpage</name> <packaging>war</packaging> <version>1.0.0-BUILD-SNAPSHOT</version> <properties> <java-version>1.6</java-version> <org.springframework-version>4.2.6.RELEASE</org.springframework-version> <org.aspectj-version>1.8.9</org.aspectj-version> <org.slf4j-version>1.7.5</org.slf4j-version> </properties> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> <exclusions> <!-- Exclude Commons Logging in favor of SLF4j --> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${org.springframework-version}</version> </dependency> <!-- AspectJ --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${org.aspectj-version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${org.aspectj-version}</version> </dependency> <!-- Logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${org.slf4j-version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.15</version> <exclusions> <exclusion> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> </exclusion> <exclusion> <groupId>javax.jms</groupId> <artifactId>jms</artifactId> </exclusion> <exclusion> <groupId>com.sun.jdmk</groupId> <artifactId>jmxtools</artifactId> </exclusion> <exclusion> <groupId>com.sun.jmx</groupId> <artifactId>jmxri</artifactId> </exclusion> </exclusions> <scope>runtime</scope> </dependency> <!-- @Inject --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- Test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.7</version> <scope>test</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.4</version> <exclusions> <exclusion> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> </exclusion> <exclusion> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.7.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.7.4</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.2.6.RELEASE</version> </dependency> <!-- mybatis 包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.0</version> </dependency> <!--mybatis spring 插件 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!-- mysql连接 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.13</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.0</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-pdfa</artifactId> <version>5.5.0</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.10-FINAL</version> </dependency> <!-- POI --> <!-- xls view --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.14</version> </dependency> <!-- xlsx view --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.14</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-eclipse-plugin</artifactId> <version>2.9</version> <configuration> <additionalProjectnatures> <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature> </additionalProjectnatures> <additionalBuildcommands> <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand> </additionalBuildcommands> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> <compilerArgument>-Xlint:all</compilerArgument> <showWarnings>true</showWarnings> <showDeprecation>true</showDeprecation> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <configuration> <mainClass>org.test.int1.Main</mainClass> </configuration> </plugin> </plugins> </build> </project>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- The definition of the Root Spring Container shared by all Servlets and Filters --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <!-- Creates the Spring Container shared by all Servlets and Filters --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Processes application requests --> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet> <display-name>UploadServlet</display-name> <servlet-name>UploadServlet</servlet-name> <servlet-class>com.free.loginpage.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/loginpage/UploadServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.ttf</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.woff</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.woff2</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.gif</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.jpg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> </web-app>
root-context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- Root Context: defines shared resources visible to all other web components --> <!-- 引入jdbc配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:properties/*.properties</value> </list> </property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.free.dao" /> </bean> <!-- 配置数据源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>${jdbc_driverClassName}</value> </property> <property name="url"> <value>${jdbc_url}</value> </property> <property name="username"> <value>${jdbc_username}</value> </property> <property name="password"> <value>${jdbc_password}</value> </property> </bean> <!-- 配置Mybatis文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations" value="classpath*:com/free/mapper/**/*.xml"/> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" /> </bean> </beans>
sevlet-context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> <!-- Enables the Spring MVC @Controller programming model --> <annotation-driven /> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> <resources mapping="/resources/**" location="/resources/" /> <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <!-- File Upload --> <beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <beans:property name="maxUploadSize"> <beans:value>10485760</beans:value> </beans:property> <beans:property name="defaultEncoding"> <beans:value>UTF-8</beans:value> </beans:property> </beans:bean> <!-- 自动扫描controller --> <context:component-scan base-package="com.free.loginpage" /> <!-- 自动扫描的service --> <context:component-scan base-package="com.free.service" /> </beans:beans>
注意,因为我用的mysql的版本是mysql-8.0.12-winx64,所以在pom.xml中配置的mysql-connection-java版本是8.0.13,这里需要跟自己的mysql版本对应
6. 新建一个com.free.service包,在com.free.service包下建一个UserService.java,作为一个用户登陆接口。右键com.free.service,【New】--> 【Class】,Name就填UserService。当然java的名称自己可以取的。
UserService.java
package com.free.service; import java.util.List; import org.apache.ibatis.annotations.Param; import com.free.entity.User; public interface UserService { User login(String name,String password); }
7. 在com.free.service包下建一个UserServiceImpl.java,实现UserService的函数。
UserServiceImpl.java
package com.free.service; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.free.dao.UserDao; import com.free.entity.User; @Service public class UserServiceImpl implements UserService { @Resource public UserDao userDao; @Override public User login(String name,String password) { return userDao.login(name,password); } }
8. 修改HomeController.java中的登录函数。
HomeController.java
package com.free.loginpage; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.bind.annotation.SessionAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; import javax.annotation.Resource; import com.free.entity.User; import com.free.service.UserService; /** * Handles requests for the application home page. */ @Controller @SessionAttributes("User") public class HomeController { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); @Resource public UserService userService; /** * Simply selects the home view to render by returning its name. */ @RequestMapping(value = "/") public String ShowLogin() { return "login"; } @RequestMapping(value = "/login") public String logout(HttpServletRequest request){ Enumeration<String> em = request.getSession().getAttributeNames(); while(em.hasMoreElements()) { request.getSession().removeAttribute(em.nextElement().toString()); } request.getSession().invalidate(); return "login"; } // 点击login时触发 @RequestMapping(value = "/index", params="Login", method = RequestMethod.POST) public ModelAndView Login(HttpServletRequest request,Locale locale, Model model,ModelAndView view, RedirectAttributes redirectAttributes) { String name = request.getParameter("name"); String password = request.getParameter("password"); logger.info(name); User user = userService.login(name, password); if(user != null) { model.addAttribute("User", user); view.setViewName("redirect:/index"); } else { redirectAttributes.addFlashAttribute("Error", " * Wrong name or password."); view.setViewName("redirect:/login"); } return view; } @RequestMapping(value = "/index") public ModelAndView ShowIndex(@ModelAttribute("User") User user, Locale locale, Model model,ModelAndView view) { //get current time view.setViewName("index"); return view; } }
9. 最后,直接将原先写HelloWorld对应的Home.jsp重命名为index,然后运行程序。
包结构
效果图: