Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Spring MVC

2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

Spring Web MVC

Spring Web MVC requires the use of IOC functionality.

Web program for developing MVC structure.

I. MVC thought

The program component is divided into three parts: model, view and controller.

II. How does Spring implement MVC

a. The browser issues a HTTP request

b. Request to enter the DispatcherServlet master controller first

c. The main controller calls the HandlerMapping component to find the Controller processing of the mapping according to the request.

d. Executes the Controller processing method and returns the result to the ViewResolver component

The e.ViewResolver component locates the view JSP according to the result returned by Controller and passes the model data to JSP.

f. The response result is generated by JSP and output to the browser

Send a request to DispatcherServlet, then go to HandlerMapping to Controller1, and then return a ViewResolver to the view.

Eg: when you issue a hello.do request on the page, you first go through web.xml and know that the .do request needs to go to DispatcherServlet,DispatcherServlet and applicationContext.xml.

Look for the handlerMapping component, find the hello.do according to the mapping name hello.do and find the helloController component to deal with. Find / WEB-INF/hello.jsp according to the prefix and suffix configurations of ModelAndView and applicationContext.xml in helloController

Eg1: displays the login page

/ tologin.do

-> DispatcherServlet (configuration) / / act as the master controller and send it to him first when you send a request

-> hanlderMapping (configuration) / / define the corresponding relationship between Servlet request and Controller, and resolve which Controller according to applicationContext.xml configuration

-> toLoginController (authoring + configuration) / / invoke DAO model components

-> ViewerResolver (configuration) / / Encapsulation, forwarding, redirecting to JSP view

-> WEB-INF/login.jsp (written)

3.Spring Web MVC processing flow

A.RequestMappingHandlerMapping component

@ RequestMapping ("login.do") this tag is used before the Controller business method

B.Controller authoring and configuration

Canceling the implementation of Controller interfaces and method conventions, allowing programmers to flexibly define business methods on demand

Public ModelAndView or String method name (based on request,session,response)

Controller needs to scan to the Spring container and must use @ Controller

Eg: public String execute () {

Return "hello"

}

How d.Controller receives request parameters

1) using HttpServletRequest

* 2) use business method parameters (used when a small number of parameters are used)

*-- the parameter name is consistent with the request parameter key

-use @ RequestParam ("key")

* 3) use entity objects when method parameters (a large number of parameters are used)

Suggestions: use 2) for a small number of parameters; 3) for a large number of parameters; if there is no format check for client form data, it is recommended to use 1) if you encounter parameters of non-string type.

e. How to pass a value to the response JSP

* 1) use HttpServletRequest

2) use ModelAndView as the return value

* 3) using ModelMap method parameters

4) use @ ModelAttribute ("key")

Public String checkLogin (@ ModuleAttribute ("user") String username) {

Return "ok";} / / ok.jsp uses ${user}

@ ModelAttribute ("user")

Public String getName () {

Return "tom";}

Equivalent to model.put ("user", getName ()); / / ${user} is tom

How f.Controller uses Session

Code example:

Web.xml:

WebLogin2 org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:applicationContext.xml webLogin2 * .do

Handlermapping and controller:

@ Controllerpublic class LoginController {/ / login button handles @ RequestMapping ("/ login.do") public String checkLogin3 (String username, String password, ModelMap modelMap, HttpSession session) {if ("root" .equals (username) & & "1234" .equals (password)) {modelMap.put ("user", username); session.setAttribute ("username", username); return "ok" / / ok.jsp uses ${user}} else {modelMap.put ("msg", "wrong username or password"); return "login"; / / login.jsp uses ${msg}}

Spring configuration:

Ok.jsp:

${user} login success session content: ${sessionScope.username}

Login.jsp:

User logs in ${msg} username: password:

Visit: http://localhost:8090/webLogin2_war (the war package name defined here) / login.do

Enter the display with the correct username and password:

Root login success

Session content: root

4.Spring Web MVC

1) solve the problem of garbled code in Chinese reception

Myfilter

Org.springframework.web.filter.CharacterEncodingFilter

Encoding

UTF-8

Myfilter

* .do

2) how to handle exceptions

a. Global exception handling: SimpleMappingExceptionResolver

@ Controllerpublic class ExceptionController {@ RequestMapping ("/ exception.do") public String ex () {String s = null; s.length (); return "ok";}}

At this point, accessing exception.do will throw a nullpoint exception, which requires exception handling. Use the built-in global exception handling method.

ApplicationContext.xml configuration:

Process the flowchart at this point:

b. Local exception handling: @ ExceptionHandler

Public String xxx (HttpServletRequest request, Exception e) {}

@ Controllerpublic class AgeController {@ RequestMapping ("/ toage.do") public String toage () {/ / check whether there is username return "age" in the session; / / enter age.jsp} @ RequestMapping ("/ age.do") public String age (String birth, ModelMap modelMap) throws Exception {/ / receive the birthday entered by the user, and calculate the age Date now = new Date () SimpleDateFormat sdf = new SimpleDateFormat ("YYYY-MM-DD"); Date birth2 = sdf.parse (birth); int result = now.getYear ()-birth2.getYear (); modelMap.put ("msg", "age:" + result); return "age" / / enter age.jsp,$ {msg} / / enter the handleException method} / * current Controller exception handling because string cannot be returned when an exception occurs. * when this method is executed, the ExceptionResolver * / @ ExceptionHandler// local exception handling method public String handleException (HttpServletRequest request, Exception e) {request.setAttribute ("msg", "calculation fails due to incorrect input information") will not be called. Return "age"; / / returns age.jsp}}

c. Custom ExceptionResolver (implement HandlerExceptionResolver interface)

Write your own exception handling class first:

Public class MyExceptionHandler implements HandlerExceptionResolver {public ModelAndView resolveException (HttpServletRequest request, HttpServletResponse response, Object method, Exception e) {/ / write exception information to file System.out.println ("write exception information to file:" + e) / / Jump to the error page ModelAndView mav = new ModelAndView (); mav.setViewName ("error"); return mav;}}

Eorror.jsp

The system is busy

Comment out the global exception handling in applicationContext.xml and write your own exception handling class:

When visiting exception.do at this time, the page will display the word "system busy" when the program goes wrong.

3) how to check login permissions

Session is used to judge the appointed value.

Implementation method: 1. Adopt Filter (general solution); 2. Use interceptor (Spring WEB MVC)

a. Brief introduction of interceptor components

Interceptor components are SpringMVC-specific components.

Interceptor components can be intercepted before Controller; they can be intercepted after Controller; and they can be intercepted before JSP parsing is finished and output to the browser.

b. How to use the interceptor

First write an interceptor component (implement the HandlerInterceptor interface)

Add the logic to be inserted in the convention method and then configure it in applicationContext.xml

Interceptor class:

Before import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;public class LoginInterceptor implements HandlerInterceptor {@ Override / / controlller, permission check, login check public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println ("--preHandle implements login check--") HttpSession session = request.getSession (); / / get the user information placed after a successful login String name = (String) session.getAttribute ("username"); if (name! = null) {/ / log in to return true;// to continue the mvc follow-up process} else {/ / login failure (session failure) or login failure response.sendRedirect ("/ tologin.do") After return false;// terminates the subsequent process of mvc} @ Override / / controller, count the log from the beginning to the end of processing, perform time performance monitoring, and check the time-consuming items public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println ("- postHandle---") } @ Override / / the request has been processed before the output. Count the logs from the beginning to the end of processing, perform time performance monitoring, and check time-consuming items public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println ("--afterHandle---");}}

ApplicationContext.xml

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report