使用maven+ssm搭建簡單的登入驗證,有關maven 相關配置檢視另一篇文章 eclipse中使用Maven搭建簡單javaweb
這次開發順序采用資料庫->背景->前端
本人使用的mysql資料庫 建立一個名為ssmdemo資料庫
建表sql語句
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`password` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `users` VALUES ('1', 'admin', 'admin');
項目結構如下
pom.xml
<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.dawan.maven</groupId>
<artifactId>mavendemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!--1.資料庫相關依賴-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.1</version>
</dependency>
<!--2.dao架構:MyBatis依賴-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<!--mybatis自身實作的spring整合依賴-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
<!-- json轉換架構 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--4:spring依賴-->
<!--1)spring核心依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!--2)spring dao層依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!--3)springweb相關依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
</dependencies>
<!-- 插件配置-->
<build>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.2.v20170220</version>
</plugin>
</plugins>
</build>
</project>
User.java 實體類
package com.dawan.ssmdemo.entity;
public class User{
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserDao.java 資料層
package com.dawan.ssmdemo.dao;
import org.apache.ibatis.annotations.Param;
import com.dawan.ssmdemo.entity.User;
public interface UserDao {
/**
* 通過使用者名查詢使用者
* @param username
* @return
*/
User userByName(@Param("username") String username);
}
UserService.java 業務層接口
package com.dawan.ssmdemo.service;
import com.dawan.ssmdemo.entity.User;
public interface UserService {
/**
* 通過使用者名查詢使用者
* @param username
* @return User
*/
User userByName(String username);
}
UserServiceImpl.java 實作類
package com.dawan.ssmdemo.serviceimpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dawan.ssmdemo.dao.UserDao;
import com.dawan.ssmdemo.entity.User;
import com.dawan.ssmdemo.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public User userByName(String username) {
User user = userDao.userByName(username);
return user;
}
}
UserController.java
package com.dwan.ssmdemo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.dawan.ssmdemo.entity.User;
import com.dawan.ssmdemo.service.UserService;
@Component
@RequestMapping(value="/user")
public class UserController {
@Autowired
private UserService userService;
/**
*
* @param model
* @return
* @throws JsonProcessingException
* 查詢所有文章
*/
@RequestMapping(value="/login")
public String articleList(@RequestParam(value="username", required=true) String username,
@RequestParam(value="password", required=true) String password){
System.out.println("username"+username);
System.out.println("password"+password);
User user = userService.userByName(username);
if (user==null) {
return "loginerr";
}else if(user.getUsername().equals(password)) {
System.out.println(user.getPassword());
return "loginok";
}
return "loginerr";
}
}
@RequestParam 擷取前端傳入參數 value綁定前端參數的名字 required設定參數是否能為空
jdbc.properties 資料庫連接配接配置檔案
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/ssmdemo?useUnicode=true&characterEncoding=utf-8
users=root
password=root
useUnicode=true&characterEncoding=utf-8參數解決中文亂碼問題 ssmdemo為資料庫名 users 和password為mysql使用者名和密碼
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>
<!--配置全局屬性-->
<settings>
<!--使用jdbc的getGeneratekeys擷取自增主鍵值-->
<setting name="useGeneratedKeys" value="true"/>
</settings>
</configuration>
這裡隻簡單配置還有更多屬性另行查詢
UserDao.xml
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dawan.ssmdemo.dao.UserDao">
<!--目的:為dao接口方法提供sql語句配置
即針對dao接口中的方法編寫我們的sql語句-->
<!-- 通過id查詢文章 -->
<select id="userByName" resultType="com.dawan.ssmdemo.entity.User" parameterType="String">
SELECT id,username,password
FROM users
WHERE username=#{username}
</select>
</mapper>
因為這裡使用的mybatis接口程式設計 各個sql語句id的值與對應的Dao層接口的方法名要一一對應
resultType 指定傳回類型
parameterType指定參數類型
where 使用#{username} mybatis 解析#{username}為占位符,sql語句會預編譯能防止sql注入
spring-dao.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">
<!-- 配置整合mybatis過程 -->
<!-- 引入配置檔案
ignore-unresolvable就是過濾掉特殊占位符 -->
<context:property-placeholder location="classpath*:configs/*.properties"
ignore-unresolvable="true"/>
<!--2.資料庫連接配接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--配置連接配接池屬性-->
<property name="driverClass" value="${driver}" />
<!-- 基本屬性 url、user、password -->
<property name="jdbcUrl" value="${url}" />
<property name="user" value="${users}" />
<property name="password" value="${password}" />
<!--c3p0私有屬性-->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!--關閉連接配接後不自動commit-->
<property name="autoCommitOnClose" value="false"/>
<!--擷取連接配接逾時時間-->
<property name="checkoutTimeout" value="2000"/>
<!--當擷取連接配接失敗重試次數-->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!--約定大于配置-->
<!--3.配置SqlSessionFactory對象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--往下才是mybatis和spring真正整合的配置-->
<!--注入資料庫連接配接池-->
<property name="dataSource" ref="dataSource"/>
<!--配置mybatis全局配置檔案:mybatis-config.xml-->
<property name="configLocation" value="classpath:configs/mybatis-config.xml"/>
<!--掃描entity包,使用别名,多個用;隔開-->
<property name="typeAliasesPackage" value="com.dawan.ssmdemo.entity"/>
<!--掃描sql配置檔案:mapper需要的xml檔案-->
<property name="mapperLocations" value="classpath:configs/mapper/*.xml"/>
</bean>
<!--4:配置掃描Dao接口包,動态實作DAO接口,注入到spring容器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入SqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 給出需要掃描的Dao接口-->
<property name="basePackage" value="com.dawan.ssmdemo.dao"/>
</bean>
</beans>
spring-service.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"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config />
<!--掃描相關service 實作類 -->
<context:component-scan base-package="com.dawan.ssmdemo.serviceimpl"/>
<!--配置事務管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入資料庫連接配接池-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置基于注解的聲明式事務
預設使用注解來管理事務行為-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
spring-web.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置spring mvc-->
<!--1,開啟springmvc注解模式
a.自動注冊DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter
b.預設提供一系列的功能:資料綁定,數字和日期的[email protected],@DateTimeFormat
c:xml,json的預設讀寫支援-->
<mvc:annotation-driven/>
<!--2:掃描web相關的controller-->
<context:component-scan base-package="com.dwan.ssmdemo.controller"/>
<!--3.靜态資源預設servlet配置-->
<!--
1).加入對靜态資源處理:js,gif,png
2).允許使用 "/" 做整體映射
-->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!--4:配置JSP 顯示ViewResolver-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsps/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置ViewResolver 可以用多個ViewResolver.
使用order屬性排序, InternalResourceViewResolver放到最後 -->
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1"/>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json"/>
<entry key="xml" value="application/xml"/>
<entry key="htm" value="application/html"/>
</map>
</property>
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean
class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
</bean>
</list>
</property>
</bean>
</beans>
下面簡單寫前端和web.xml對ssm的配置
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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<!-- 編碼過濾 -->
<filter>
<display-name>encodingFilter</display-name>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring MVC核心 -->
<display-name>Spring MVC</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:configs/spring/spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
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>Insert title here</title>
</head>
<body>
<form action="/user/login" method="post">
使用者名<input type="text" name="username"/>
密碼<input type="password" name="password"/>
<input type="submit"/>
</form>
</body>
</html>
loginerr.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>
loginerr
</body>
</html>
loginok.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>
loginok
</body>
</html>
就此使用maven搭建ssm 實作簡單的登入驗證就好了
有不足之處請留言