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

實現簡單的登陸和註冊

步驟:html

工程目錄:java

 

1.建立一個動態的web工程mysql

2.導入springMvc所須要的jar包(包含mysql驅動包)web

3.配置web.xml步驟:面試

配置惟一的 Servletspring

3.1 增長 servlet和 servlet-mapping 標籤sql

3.2 配置 servlet 標籤,name 隨便起,class 是 DispatcherServlet數據庫

3.3 配置 servlet-mapping,name 和上邊保持一致,url-pattern 是 /apache

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新手,請多指教!哈哈~

相關文章
相關標籤/搜索