面試時可能會讓你上機寫一個基於SpringMVC的小程式

来源:https://www.cnblogs.com/feiyang-dabao/archive/2017/12/29/8146040.html
-Advertisement-
Play Games

實現簡單的登錄和註冊 步驟: 工程目錄: 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"/>
密&nbsp;&nbsp;碼<input type="text" name="password"/>
年&nbsp;&nbsp;齡<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新手,請多指教!哈哈~


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 本文主要介紹四種實例化bean的方式(註入方式) 或者叫依賴對象實例化的四種方式。上面的程式,創建bean 對象,用的是什麼方法 ,用的是構造函數的方式 (Spring 可以在構造函數私有化的情況下把類對象創建出來) 常用的創建方式有以下四種: 1) setter 方法 2) 構造函數 3) 靜態工 ...
  • 這是在看完了C++ Primer這本書之後又回過頭來碼的筆記,在看的時候也發現,看到後面,前面就忘了,有點像狗熊掰玉米。。。所以決定回過頭來再過一遍,這一次只看那些比較重要的知識點,太詳細了也終歸還是記不住。另外,這篇博客是使用 Markdown寫的,第一次用,估計寫出來的格式可能會有點醜。。 1. ...
  • 數據流分為輸入、輸出流,無論是輸入流還是輸出流,都可看作是在源和目標之間架設一根"管道",這些管道都是單向流動的,要麼流入到記憶體(輸入流),要麼從記憶體流出(輸出流)。 應用於java上,輸入流和輸出流分別為InputStream和OutputStream。輸入流用於讀取(read)數據,將數據載入到 ...
  • Web層用Structs2的action Service層用Spring的IoC和aop以及JdbcTemplate或者Transaction事務(創建對象及維護對象間的關係) Dao層用Hibernate的crude操作 看上去是Structs2和Spring(把Structs2的action交給 ...
  • 都線上購物過吧?那麼你應該體驗過,當沒有登錄賬戶時,點開購物車,個人中心,收藏物品等的操作時,都會直接跳轉到登錄賬戶的界面,然後如果登錄一次後就不用再登錄,直到用戶登出。 是的,本次項目就是做一個登錄驗證系統 需求:1.模擬某購物網站,進入菜單選項:一共有以下頁面,根據用戶輸入的序號,做出不同的反饋 ...
  • 2.1 python3.6 工具使用 運行python 自帶的idle後,輸入python命令,如print('hello world'),回車後輸出 hello world 其中mac系統會出現一段warning :the version of tcl/tk in use may be ustab ...
  • 最近項目用到springcloud,研究了下springcloud的熔斷機制Hystrix。 熔斷機制,就是下游服務出現問題後,為保證整個系統正常運行下去,而提供一種降級服務的機制,通過返回緩存數據或者既定數據,避免出現系統整體雪崩效應。在springcloud中,該功能可通過配置的方式加入到項目中 ...
  • 用正則表達式開發一個計算器,計算用戶給定的一串帶有加減乘除的公式。 要求:不能使用eval轉換字元串 分析: 要求簡單,就是計算混合運算,但是不能使用eval直接轉換,主要就是把整個式子中的小括弧優先匹配到進行計算再把計算結果替換到式子中,然後再根據小括弧計算,直到沒有小括弧再按照加減乘除優先順序計算 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...