从ModelAndView查看与ViewResolver中的视图

时间:2016-12-18 12:16:47

标签: java spring spring-mvc web

在Spring MVC中,当请求命令时,DispatcherServlet指定HandlerMapping,指示哪个控制器应该处理请求。 Controller处理请求并返回具有指定View的模型。

ViewResolver开始工作时,我不知道会发生什么。如果View已指定Controller,为什么会有ViewResolver图层?它实际上做了什么?不应该View之前指定Controller或与Controller并列吗?或者ViewResolver可能会触发using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace Infinite_Trainer_v2 { class database_connector { private MySqlConnection connection; private string server; private string database; private string uid; private string password; // Constructor public database_connector() { Initialize(); } //Initialize values private void Initialize() { server = "ip:3306"; database = "dbName"; uid = "username"; password = "password"; string connectionString; connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";"; connection = new MySqlConnection(connectionString); } //open connection to database private bool OpenConnection() { try { connection.Open(); return true; } catch (MySqlException ex) { switch (ex.Number) { case 0: MessageBox.Show("Cannot connect to server. Contact administrator."); break; case 1045: MessageBox.Show("Invalid username/password, please try again"); break; } return false; } } //Close connection private bool CloseConnection() { try { connection.Close(); return true; } catch (MySqlException ex) { MessageBox.Show(ex.Message); return false; } } // Select statement public bool userCheck(string username, string password) { string query = "SELECT username, password FROM Users WHERE username = '" + username + "' AND password = '" + password + "'"; bool hasRecords = false; if (this.OpenConnection() == true) { MySqlCommand cmd = new MySqlCommand(query, connection); MySqlDataReader dataReader = cmd.ExecuteReader(); if (dataReader.HasRows) { while (dataReader.Read()) { hasRecords = true; } } dataReader.Close(); this.CloseConnection(); } return hasRecords; } } } 图层?

1 个答案:

答案 0 :(得分:4)

ViewResolver将视图名称映射到实际视图。例如:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
</bean>

在返回字符串时告诉spring方法,在返回值和视图加载时添加前缀和后缀,假设你有

@RequestMapping("/")
public String home() {
    return "home";
}

ViewResolver将带回家并将其更改为home.jsp并查看/ WEB-INF / views /以加载/WEB-INF/views/home.jsp