SpringMVC demo 小例子,實現簡單的登錄和注冊


1.創建一個動態的web工程

2.導入springMvc所需要的jar包(這里可以去網上找,資源有很多)

前兩部就不詳細描述了,后面才是正經代碼~

首先有一個web.xml文件,這個屬於大配置文件,由於只要寫login,里面簡單配置一下基本環境就可以

 

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
     <servlet-name>springmvc</servlet-name>
     <url-pattern>/</url-pattern>
  </servlet-mapping>

加入的這個叫Dispatcher Servlet,可以根據servlet-name找到對應的小配置文件,也就是配置spring MVC的文件

在web.xml文件同級目錄下新建springmvc-servlet.xml文件,下面是springmvc-servlet.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:p="http://www.springframework.org/schema/p"
    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-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!--默認的注解映射的支持 -->
    <mvc:annotation-driven/>
    <!--啟用自動掃描 -->
    <context:component-scan base-package="controller"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

注意說明的是,啟動自動掃描,spring會在指定的包下(例如我這里是controller包),自動掃描標注@Controller的類

prefix指的是返回的值給自動加一個前綴,同理suffix指的就是后綴

 

 

看到這里也是夠辛苦了,上面是給出的完整目錄,下面開始寫邏輯代碼,先從loginController開始

@Controller
public class LoginController {
    @RequestMapping(value="/",method=RequestMethod.GET)
    public String sayHello(){
        //model.addAttribute("msg", "Hello,World!");
        return "login";
    }

解釋上面代碼,@Controller,標注這個類是Controller類,spring會自動進行掃描,@Request Mapping中的value指的是url中的地址后綴,設置成/的目的當然是為了方便啊,

比如啟動工程時,url只需要輸入什么localhost:8080/項目名,它就會自動跳轉到login頁面;method指的是來的url是post請求還是get請求

return的是login字符串,大家還記得上面說的prefix了吧,它就會把你的url自動拼接上,完整路徑就是下面這個

/WEB-INF/jsp/login.jsp

 接下來看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>login</title>
</head>
<body>
    <form action="login" method="post">
        用戶名:<input type="text" name="username"/><br/>&nbsp;&nbsp;碼:<input type="password" name="password"/>
        <input type="submit" value="登陸"/>
        <a href="regist">注冊</a>
    </form>
</body>
</html>

這里的action返回的是login,Controller會自動捕獲到這個請求,於是在login Controller中要有一個方法來捕獲這個請求

@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 = LoginCheck.check(username, password);
        if(user_name != null && user_name != ""){
            model.addAttribute("msg", user_name);
            return "success";
        }else{
            return "login2";
        }
    }

登陸嘛,當然要有驗證,於是就有了LoginCheck,不多說,上代碼

package logic;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import dao.Dao;

public class LoginCheck {
    
    public static String check(String username,String password){
        try {
            Connection conn = Dao.getConnection();
            PreparedStatement p = conn.prepareStatement("select * from user_t where user_name=? and password=?");
            p.setString(1, username);
            p.setString(2, password);
            ResultSet rs = p.executeQuery();
            if(rs.next()){
                String user_name = rs.getString("user_name");
                Dao.close(rs, p, conn);
                return user_name;
            }
            Dao.close(rs, p, conn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}

向數據庫查詢就要有DAO啦,Dao網上都有,我的就是在網上隨便找一個改改就用了~

package dao;

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 url = "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong";
        try
        {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","數據庫密碼");//大家分享代碼的時候也不要暴露自己的數據庫密碼,這樣是非常不安全的
        }
        catch(ClassNotFoundException e)
        {
            e.printStackTrace();
            System.out.println("數據庫驅動加載出錯");
        }
        catch(SQLException e)
        {
            e.printStackTrace();
            System.out.println("數據庫出錯");
        }
        return conn;
    }
     //關閉相關通道
    public static void close(ResultSet rs,PreparedStatement p,Connection conn)
    {
        try
        {
            if(!rs.isClosed()){
                rs.close();
            }
            if(!p.isClosed()){
                p.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("數據關閉出錯");
        }
    }
}

好了,如果查詢的結果匹配上數據庫中查詢到的值了,那么就可以跳轉到success頁面了,success.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>登陸成功</title>
</head>
<body>
    登陸成功!
    歡迎~${msg};
</body>
</html>

login大功告成,接下來的注冊頁面和這個道理相似,我不多廢話了,把代碼附上供大家參考

首先是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>注冊頁面</title>
</head>
<body>
    <form action="registSuccess" method="Post">
        用戶名:<input type="text" name="username"/>&nbsp;&nbsp;碼<input type="text" name="password"/>&nbsp;&nbsp;齡<input type="number" name="age"/>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>

接下來是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 logic.RegistCheck;

@Controller
public class RegistController {
    @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 "regist2";
        }
    }
}

接下來是RegistCheck

 

package logic;

import java.sql.Connection;
import java.sql.PreparedStatement;

import dao.Dao;

public class RegistCheck {
    
    public static boolean registCheck(String username,String password,String age){
        String user_name = LoginCheck.check(username, password);
        if(user_name == null || user_name == ""){
            try {
                Connection conn = Dao.getConnection();
                PreparedStatement p = conn.prepareStatement("insert user_t(user_name,password,age) VALUES (?,?,?);");
                p.setString(1, username);
                p.setString(2, password);
                p.setString(3, age);
                p.executeUpdate();
                System.out.println("注冊成功");
                Dao.close(p, conn);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}

還有一個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>注冊成功</title>
</head>
<body>
    注冊成功!
</body>
</html>

好了,現在為止login和注冊頁面都寫好了,新人剛到公司的時候非常容易碰到這樣的小練習,哈哈哈說多了,喜歡就點贊哈

歡迎轉載,轉載請注明出處~

Java從學習到放棄,MySQL從刪庫到跑路,哈哈哈

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM