實現簡單的登錄和註冊 步驟: 工程目錄: 1.創建一個動態的web工程 2.導入springMvc所需要的jar包(包含mysql驅動包) 3.配置web.xml步驟: 配置唯一的 Servlet 3.1 增加 servlet和 servlet-mapping 標簽 3.2 配置 servlet 標 ...
實現簡單的登錄和註冊
步驟:
工程目錄:
1.創建一個動態的web工程
2.導入springMvc所需要的jar包(包含mysql驅動包)
3.配置web.xml步驟:
配置唯一的 Servlet
3.1 增加 servlet和 servlet-mapping 標簽
3.2 配置 servlet 標簽,name 隨便起,class 是 DispatcherServlet
3.3 配置 servlet-mapping,name 和上邊保持一致,url-pattern 是 /
3.4 在 servlet 標簽中增加 init-param 標簽設置 spring-mvc 配置文件的路徑
3.5 param-name:contextConfigLocation
3.6 param-value:classpath:spring-mvc.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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Springdemo1</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
以上配置web.xml文件的屬性過於繁瑣,有沒有簡單的方法?
在原web.xml文件中輸入“dispatch“按alt+/會出現提示符,向上按會出現一個“# dispatcherservlet”選中,即可自動添加代碼。
註意:把<param-value>location</param-value>修改為<param-value>classpath:spring-mvc.xml</param-value>
<url-pattern>url</url-pattern>修改為<url-pattern>/</url-pattern>即可。
4.在src目錄下建立spring-mvc.xml文件:
4.1複製代碼:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd">
</beans>
4.1 增加對註解的支持<context:component-scan base-package="controller"/>
4.2使用預設的 handleMapping 和啟用 mvc 中的註解 <mvc:annotation-driven/>
4.3 增加頁面解析類 InternalResourceViewResolver
4.3.1 增加 bean 標簽
4.3.2 設置 class = 全名 = 包名 + 路徑
4.3.3 增加 prefix 和 suffix 設置頁面路徑的首碼和尾碼
設置首碼以後將來所有的 jsp 必須放在 view 文件夾下
<property name="prefix" value="/view/"></property>
<property name="suffix" value=".jsp"></property>
代碼如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd">
<!-- 啟用 mvc 中的註解 -->
<mvc:annotation-driven />
<!-- 啟用 自動掃描的包 -->
<context:component-scan base-package="controller" />
<!-- 增加頁面解析類 InternalResourceViewResolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/view/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
註意說明的是,啟動自動掃描,spring會在指定的包下(例如我這裡是controller包),自動掃描標註@Controller的類
prefix指的是返回的值給自動加一個首碼,同理suffix指的就是尾碼
5.編寫邏輯代碼
5.1 建立一個包:controller,包下建立一個LoginControl類
5.2在WebContent下建立一個文件view,在其中新建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>
<form action="login" method="post">
<input type="text" name="username" /><br>
<input type="password" name ="password"/><br>
<input type="submit" value="登錄"/><br>
<a href="regist">註冊</a>
</form>
</body>
</html>
5.3form的action指向login,Controller會自動捕獲到這個請求,於是在所以LoginControl類需要一個login方法來捕獲這個請求
代碼如下:
package controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import check.CheckLogin;
@Controller
public class LoginControl {
@RequestMapping(value = "login", method = RequestMethod.POST)
public String login(Model model,// 前臺頁面傳的值放入model中
HttpServletRequest request) {// 從前臺頁面取得的值
String username = request.getParameter("username");
String password = request.getParameter("password");
String user_name = CheckLogin.check(username, password);
if (user_name != null && user_name != "") {
model.addAttribute("USER", user_name);
return "loginsuccess";
}
return "regist";
}
}
5.4 建立check包和LoginCheck類,以及對應的check方法,有check方法,就要用到資料庫,先建立一個dao類,代碼如下:
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Dao {
public static Connection getConnection(){
Connection conn = null;
String user="root";
String pass="1234";
String url ="jdbc:mysql://localhost:3306/test?useOldAliasMetadataBehavior=true";
try {
Class.forName("com.mysql.jdbc.Driver");
conn= DriverManager.getConnection(url, user, pass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("資料庫驅動有誤");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("資料庫有誤");
}
return conn;
}
public static void closeAll(ResultSet rs,PreparedStatement ps,Connection conn){
try {
if(!rs.isClosed()){
rs.close();
}
if(!ps.isClosed()){
ps.close();
}
if(!conn.isClosed()){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("資料庫關閉有誤");
}
}
public static void close(PreparedStatement p,Connection conn)
{
try
{
if(!p.isClosed()){
p.close();
}
if(!conn.isClosed()){
conn.close();
}
}
catch(SQLException e)
{
e.printStackTrace();
System.out.println("數據關閉出錯");
}
}
}
5.5有了dao類就可以編寫check方法了:
代碼如下:
package check;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import db.Dao;
public class CheckLogin {
public static String check(String username, String password) {
try {
String sql = "select * from table_demo where username=? and password=?";
Connection conn = Dao.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
String user_name = rs.getString("username");
return user_name;
}
Dao.closeAll(rs, ps, conn);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
6.運行項目:
異常;
嚴重: Servlet /Springdemo1 threw load() exception
java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
解決方案;解決辦法是在項目中導入commons-logging-1.2.jar(這是我導入的版本,其他版本沒有測試)。
7.接下來就是寫註冊頁面的
RegistController類:
package controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import check.RegistCheck;
@Controller
public class RegistControl {
@RequestMapping(value = "regist", method = RequestMethod.GET)
public String regist() {
return "regist";
}
@RequestMapping(value = "registSuccess", method = RequestMethod.POST)
public String registSuccess(HttpServletRequest request, Model model) {
String username = request.getParameter("username");
String password = request.getParameter("password");
String age = request.getParameter("age");
if (RegistCheck.registCheck(username, password, age)) {
model.addAttribute("username", username);
return "login";
} else {
return "regist";
}
}
}
8.regist.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="registSuccess" method="Post">
用戶名:<input type="text" name="username"/>
密 碼<input type="text" name="password"/>
年 齡<input type="number" name="age"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
9.registSuccess.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>
註冊成功!
</body>
</html>
10:運行效果:
姓名輸入1:
資料庫中有數據1,可登錄成功!
資料庫沒有1則跳轉到註冊頁面:
點擊註冊,進入註冊頁面。如上圖,添加對應信息後,點擊提交,控制台輸出註冊成功,回到登錄頁面,再實現登錄!
簡單的小程式,面試時候遇到,總結一下,分享給大家!
java新手,請多指教!哈哈~