H tr x lý form Spring MVC
Spring MVC là framework theo mô hình Model-View-Controller nên nó lý form ba thành chính: model, view và controller
- Model: POJO (Plain Old Java Object) ra liên các form các tính (object) này vào model (model object)
- View: Các Spring MVC các
HTML và quan là ràng trong mô hình
- Controller: cùng lý các yêu liên mô hình xem và và lý cho / chuyên
Bây chúng ta hãy qua các xây ký ký).
Vi t code cho Model Class (form-backing object)
File: src/main/java/net/codejava/spring/model/User.java
14 package net.codejava.spring.model; import java.util.Date; public class User { private String username; private String password; private String email; private Date birthDate; private String profession;
L model này có (username, password, email, birthDate and profession) liên các trong view (trang JSP) Khi
(object) model liên form, nó là
Vi t code cho Registration Form dùng Spring Form Tags
code cho registration form (Registration.jsp) sau: tin: src/main/webapp/WEB-INF/views/Registration.jsp
Spring MVC Form Demo - Registration
Birthday (mm/dd/yyyy):
vai trò quan Nó HTML
thông tính commandName là khóa tên model cho form:
Ý: Spring framework 5, hãy tính modelAttribute thay
To create forms in a Spring MVC application, we utilize Spring form tags within a JSP page These tags, such as ``, ``, and ``, generate corresponding HTML elements like `` and `` with their respective options It is important to note that the "path" attribute corresponds to the model attribute name For a comprehensive list of Spring MVC form tags, refer to the official Spring documentation.
Vi t code cho l p Controller
code cho controller (RegisterController.java) sau tin: src/main/java/net/codejava/spring/controller/RegisterController.java
The code snippet defines a Spring Controller in the package `net.codejava.spring.controller`, which imports necessary classes such as `ArrayList`, `List`, and `Map` It also imports the `User ` model from `net.codejava.spring.model` and utilizes Spring's `@Controller` annotation The controller includes methods annotated with `@ModelAttribute` and `@RequestMapping`, specifying the request handling for various HTTP methods.
@RequestMapping(value = "/register") public class RegisterController {
@RequestMapping(method = RequestMethod.GET) public String viewRegistration(Map model) {
User userForm = new User(); model.put("userForm", userForm);
List professionList = new ArrayList(); professionList.add("Developer"); professionList.add("Designer"); professionList.add("IT Manager"); model.put("professionList", professionList); return "Registration";
@RequestMapping(method = RequestMethod.POST) public String processRegistration(@ModelAttribute("userForm") User user,
// implement your own registration logic here
System.out.println("username: " + user.getUsername());
System.out.println("password: " + user.getPassword());
System.out.println("email: " + user.getEmail());
System.out.println("birth date: " + user.getBirthDate());
System.out.println("profession: " + user.getProfession()); return "RegistrationSuccess";
We can see that this controller is designed to handle the request URL /register:
Ta có controller này lý request có là /register:
Ta khai hai viewRegistration() và processRegistration() lý các yêu GET và POST các lý trong
Spring linh vì ta có do tên và các tham riêng mình Hãy xem xét chi controller trên:
- viewRegistration(): trong này, ta model và nó vào model map khóa
User userForm = new User(); model.put("userForm", userForm);
- này ra ràng form trong view này (là registration form) ý khóa giá tính commandName
- thú khác là chúng ta danh sách các Strings và nó vào model map khóa
List professionList = new ArrayList(); professionList.add("Developer"); professionList.add("Designer"); professionList.add("IT Manager"); model.put("professionList", professionList);
- Collection trong trang Registration.jsp danh sách (professionList)
- cùng, này view name ánh trang registration form trên
- này lý form (thông qua POST request ) Tham quan là:
- này làm cho model khóa trong model map có khóa giá tính commandName
- Khi Spring liên các giá form
(backing object) trong model, do ta có truy các giá form do dùng thông qua này, sau:
System.out.println("username: " + user.getUsername());
- demo, pháp này in ra các chi User và cùng view name trang ký thành công
Vi t code cho trang ký thành công (Registration Success Page)
Success Page) code cho trang ký thành công (RegistrationSuccess.jsp) sau: tin: src/main/webapp/WEB-INF/views/RegistrationSuccess.jsp
Registration Succeeded!
Thank you for registering! Here's the review of your details:
Trang JSP này các EL (EL expressions) các giá tính User dùng trong model.
Xem c u trúc project trong Eclipse và t p tin pom.xml
Ta Eclipse IDE và Maven xây này nên trúc project sau:
BÀI 1: 9 là tin pom.xml trong Maven project:
http://maven.apache.org
3.2.4.RELEASE
javax.servlet-api
SpringSource Milestones Proxy
https://oss.sonatype.org/content/repositories/springsource- milestones
org.apache.maven.plugins
maven-compiler-plugin
dung tin pom.xml cho ta Spring 3.2.4.RELEASE, Java
1.7 và Servlet 3.0 có phiên chúng)
Spring framework phiên 5, cglib không còn - vì hãy xóa nó.
Ch y th ng d ng
khai trên Tomcat theo (context path ) là /SpringMvcFormExample, hãy URL sau truy trang ký: http://localhost:8080/SpringMvcFormExample/register vào cho registration form sau:
BÀI 1: 11 nút Register, ta trang ký thành công hình bên chúng ta tìm u cách lý form có Spring MVC và xây và Spring làm này dàng và linh
1.2 LAB 2: TH C HI N FORM VALIDATION
In this article, we will explore how to validate forms in Spring Web MVC using the Bean Validation API Specifically, we will implement validation for a login form, focusing on the requirements for both the email and password fields After passing these validation checks, we will proceed with the next steps in the process.
Bean Validation API xác các ràng xác các tính JavaBean.
Hi n th c Bean Validation API và Hibernate Validator
Bean Validation API hóa cách mà các trình viên khai báo các ràng xác trên các model thông qua các chú thích (annotations) là ví
@Size(min = 6, max = 15) private String password;
Chúng ta các tin validation-api-1.1.0.Final.jar và hibernate-validator-
5.0.1.Final.jar Bean Validation API trong Spring MVC
BÀI 1: 13 project Maven, hãy thêm các dependencies sau vào tin pom.xml:
Spring MVC có h tr cho Bean Validation API
Spring MVC cung cho Bean Validation hình hai jar trên vào classpath và thêm sau vào tin XML Spring ( application context XML file):
Spring MVC phát và kích xác Bây trong controller, annotation model form chú thích
@RequestMapping(value = "/login", method = RequestMethod.POST) public String doLogin(@Valid User user, BindingResult result) {
Spring MVC xác model chú thích annotation @Valid sau khi liên các tính nó inputs form JSP form tags Spring vi ràng coi là trong
BindingResult, do ta có tra vi trong controller sau:
Thông ta input form cho dùng khi có xác nào ra Và trong form JSP, ta có thông báo xác cách (form errors tag) Spring sau:
Thông báo có c trong chú thích xác (validation annotation), ví
@NotEmpty(message = "Please enter your email addresss.") private String email; ta hóa thông báo (localize the message), hãy khóa trong tính theo quy sau:
ConstraintName.CommandName.propertyName=validation error message
NotEmpty.userForm.email=Please enter your e-mail
Bây hãy áp các nguyên trên xác các trong Spring MVC
Vi t code l p Model
code model (User.java) sau:
6 package net.codejava.spring; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty;
@NotEmpty(message = "Please enter your password.")
@Size(min = 6, max = 15, message = "Your password must between 6 and 15 characters") private String password; public String getEmail() { return email;
} public void setEmail(String email) { this.email = email;
} public String getPassword() { return password;
} public void setPassword(String password) { this.password = password;
} ta các chú thích ràng xác là:
@NotEmpty, @Email và @Size danh sách các ràng xác Java Bean, hãy tham trang này: https://javaee.github.io/javaee-spec/javadocs/javax/validation/constraints/package-summary.html
Ta không thông báo cho email Thay vào các thông báo cho email trong tin tính cho hóa (localization) các thông báo xác (validation error).
Vi t code cho Input Form b ng JSP
tin LoginForm.jsp dung sau:
error { color: red; font-weight: bold;
Spring MVC Form Validation Demo - Login Form
Email:
Vi t code l p Controller
code controller (LoginController.java) sau:
The article discusses the implementation of a Spring Controller in the package `net.codejava.spring`, which utilizes Java's validation framework It imports necessary classes such as `Map`, `Valid`, `BindingResult`, and annotations for handling web requests The controller is designed to manage form submissions by using the `@ModelAttribute` annotation and defining request mappings with `@RequestMapping` for both GET and POST methods.
@RequestMapping(value = "/login", method = RequestMethod.GET) public String viewLogin(Map model) {
User user = new User(); model.put("userForm", user); return "LoginForm";
@RequestMapping(value = "/login", method = RequestMethod.POST) public String doLogin(
@Valid @ModelAttribute("userForm") User userForm,
BindingResult result, Map model) { if (result.hasErrors()) { return "LoginForm";
Vi t code trang k t qu Result Page b ng JSP
Trang LoginSuccess.jsp trong dùng email và password là code nó:
Welcome ${userForm.email}! You have logged in successfully.
C u hình ng c nh ng d ng Spring MVC
hình Spring MVC trong tin nó (spring- mvc.xml) sau: (Configuring Spring MVC Application Context)
The Spring framework utilizes XML configuration for defining beans, which are essential components in a Spring application The XML schema includes namespaces for beans, context, and MVC, ensuring proper structure and validation The schema locations specify the versions of the Spring framework being used, facilitating the integration of various Spring modules This configuration approach enhances modularity and maintainability in application development.
Vi t t p tin messages.propreties
Ta hóa các thông báo xác cho email, vì hãy các key-value sau vào tin messages.properties:
NotEmpty.userForm.email=Please enter your e-mail
Email.userForm.email=Your e-mail is incorrect.
C u hình Spring framework trong t p tin web.xml
Spring dispatcher servlet trong tin mô mô khai web (web.xml) sau:
The XML configuration for a web application defines its structure and versioning It specifies namespaces for XML schema instances and Java EE, ensuring compatibility with web standards The document outlines the web application's ID and version, which is crucial for deployment and functionality.
SpringMvcFormValidationExample
SpringController
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/spring-mvc.xml
1
SpringController
Xem xét c u trúc project và các t p tin JAR c n thi t
Các tin source code trên vào cây trong Eclipse IDE sau:
Các tin jar trong WEB-INF\lib là:
The Hibernate Validator JAR, version validation-api-1.1.0.Final.jar, is essential for integrating with Classmate and JBoss logging JARs For more information, you can visit the following links: [Classmate JAR](https://mvnrepository.com/artifact/com.fasterxml/classmate/0.5.4) and [JBoss Logging JAR](https://mvnrepository.com/artifact/org.jboss.logging/jboss-logging/3.1.0.GA).
Ch y th ng d ng
Gõ URL sau vào thanh trình http://localhost:8080/SpringMvcFormValidationExample/login
Form email không và password (ví 4 ký sau vào Login Ta thông báo xác màu bên form, sau:
Bây hãy email và password 6 15 ký
DOWNLOAD VÀ UPLOAD FIL
T o Eclipse project
Hãy project Eclipse cho web Java Trong IDE Eclipse, hãy Java EE
To create a new dynamic web project, navigate to the File menu and select New, then choose Dynamic Web Project Name the project "FileUploadSpringMVC," set the target runtime to Apache Tomcat v7.0, and select Dynamic Web Module version 3.0 After that, click Next and ensure to check the appropriate options on the following screen.
Generate web.xml deployment descriptor và vào Finish: project Project>Properties Alt + Enter) Trong
Properties for FileUploadSpringMVC, hãy Target Runtimes là Apache Tomcat v7.0, hình sau:
BÀI 2: 27 làm cho các tin jar API Servlet có trong classpath án
Sao chép các tin jar sau vào WebContent\WEB-INF\lib:
Spring framework spring-beans-3.2.0.RELEASE.jar spring-context-3.2.0.RELEASE.jar spring-core-3.2.0.RELEASE.jar spring-expression-3.2.0.RELEASE.jar spring-web-3.2.0.RELEASE.jar spring-webmvc-3.2.0.RELEASE.jar
Apache Commons File Upload commons-fileupload-1.2.2.jar
Apache Commons IO commons-io-2.3.jar
Apache Commons Logging commons-logging-1.1.1.jar
- Các tin jar Spring framework trên dành cho Spring MVC có có tin jar các tính khác Spring
- Sau khi thêm các tin jar, nó yêu làm project project và
Cho nay, ta có trúc project sau:
Bây ta hãy upload form mô trong theo.
T o upload form
T o t p JSP m i có tên UploadForm.jsp trong th m c WebContent c a d án và gõ code sau vào:
Spring MVC File Upload Demo
Spring MVC File Upload Demo
BÀI 2: 29 ý khai báo các tính sau
- method = : cho yêu HTTP POST server khi form này
- action = : tên hành lý form Ta hình này sau trong hình Spring
- enctype = - : ra form này có
(multipart data - file upload) trình web và server cách lý yêu (request)
Form này: chúng ta form này thông (text field -
Description) và hai (Pick file #1 and Pick file #2) duy 2 tin lên theo, chúng ta hình cách Spring yêu
(multipart request) và kích Spring MVC cho web.
C u hình Spring MVC và MultipartResolver
tin hình (context) Spring trong :
WebContent\WEB-INF project, là spring-mvc.xml: code vào:
I don't know!
Error
BÀI 2: DOWNLOAD 31 thích hình này chi sau:
- ra cho Spring scan gói và các gói con các thành chú thích Spring annotations, vì ta các chú thích (annotations) cho controller mình
- Ta khai báo bean viewResolver ánh các logic view name các tin JSP là cho project trên Spring MVC JSP views
MultiartResolver trong Spring là một giải pháp cho multipart request, được triển khai từ CommonsMultipartResolver của Apache Commons File Upload Cấu hình quan trọng bao gồm maxUploadSize, giới hạn kích thước tệp tải lên, với giá trị mặc định là -1 (không giới hạn), nhưng có thể đặt thành 20MB Thêm vào đó, maxInMemorySize xác định kích thước tệp tối đa được lưu trữ trong bộ nhớ, với giá trị mặc định là 10KB (10240 byte), có thể điều chỉnh thành 1MB.
- Bean SimpleMappingExceptionResolver ánh (exception type) JSP view Trong này, ta ánh các
(exception) java.lang.Exception trang Error.jsp
Bây hãy kích Spring lý các yêu này tin web.xml và copy-paste dung sau vào:
I don't know!
FileUploadSpringMVC
SpringController
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/spring-mvc.xml
1
SpringController
*.do
UploadForm.jsp
Khai báo Spring controller servlet trí tin hình
(context configuration) nó và ánh servlet này cho các URL thúc
UploadForm.jsp là trang khi truy này
Trong theo, chúng ta Spring controller lý yêu form lên.
Tri n khai Spring controller
vào src project trong Project Explorer view,
New> Class trình (context menu) Trong New Java Class , thông tin sau:
- Name: FileUploadController vào Finish Dán sau vào trình
This article discusses the implementation of a Spring Controller in Java for handling file uploads It includes necessary imports such as `HttpServletRequest`, `CommonsMultipartFile`, and annotations like `@Controller`, `@RequestMapping`, and `@RequestMethod` The focus is on creating a robust file upload feature within a Spring application.
@RequestMapping("/uploadFile.do") public class FileUploadController { private String saveDirectory = "E:/Test/Upload/";
@RequestMapping(method = RequestMethod.POST) public String handleFileUpload(HttpServletRequest request,
@RequestParam CommonsMultipartFile[] fileUpload) throws Exception {
System.out.println("description: " + request.getParameter("description")); if (fileUpload != null && fileUpload.length > 0) { for (CommonsMultipartFile aFile : fileUpload){
System.out.println("Saving file: " + aFile.getOriginalFilename()); if (!aFile.getOriginalFilename().equals("")) { aFile.transferTo(new File(saveDirectory
// returns to the view "Result" return "Result";
Trong này, ta các chú thích (annotations) Spring sau:
- @Controller: này là Spring controller
- @RequestMapping: tên hành lý controller này ý tên hành này tên trong upload form khác handleFileUpload() ra này POST request
- @RequestParam: chú thích này tham handleFileUpload() ánh form field (backing object) ta ánh có tên trong upload form lên
CommonsMultipartFile MultipartResolver multipart data vào này Do ta có truy lên tin thông qua
CommonsMultipartFile Ta các CommonsMultipartFile lý tin lên
In the handleFileUpload() function, we print the Description value, then use CommonsMultipartFile and transferTo(File) to upload the file to the server Additionally, we implement the controller logic to render the view named Result.jsp as specified.
T o result page và error page
Trong WebContent án, hãy hai tin JSP: Result.jsp và Error.jsp:
File Upload Result
The file(s) was uploaded successfully!
Trang này thông báo khi lên thành công Code tin Error.jsp:
Sorry, there was an error occurred:
Trang error page này thông báo ném
Cho nay, chúng ta các cùng trúc án trông sau:
Tri n khai và ki m tra ng d ng (application)
Bây chúng ta hãy khai trên máy Tomcat trong Eclipse sang Servers view (Window>Show View>Servers), vào liên trình máy (new server wizard):
Trong New Server view, server Tomcat v7.0 và Next:
Trên màn hình theo, di project FileUploadSpringMVC bên trái sang bên sau vào Finish:
Tomcat thêm vào Servers view và nó
FileUploadSpringMVC server, hãy vào nút Start the server:
Sau khi server hãy URL sau vào thanh trình có khác, tùy vào hình): http://localhost:8080/FileUploadSpringMVC/
Upload form hãy dung nào vào Description và hai tin tùy ý, sau Upload:
Ta trang t (result page) sau khi các tin lên thành công: ta tin kích lên hình, trang báo (error page) thay
Và là chúng ta hoàn thành lên tin mình trên Spring MVC framework
BÀI 2: 39 2.2 LAB 2: DOWNLOAD FILE B NG SPRING MVC
Bài này cách khai tin trong
Spring MVC Hình sau mô quy trình làm mà chúng ta xây trúc project Eclipse: tin i trong này là SpringProject.zip trong tên là downloads có liên quan project.
Code c a trang download
Create index.jsp file under WebContent directory with the following HTML code: tin index.jsp trong WebContent mã HTML sau:
Click here to download file
Trang này link Click here to download file URL download.do Ta hình Spring controller lý URL này.
Code c a l p Spring controller
tin FileDownloadController.java trong gói net.codejava.spring code sau:
The article discusses a Java package from the Spring framework, specifically focusing on file handling within a web application It includes essential imports for file operations, such as `File`, `FileInputStream`, and `OutputStream`, as well as servlet components like `ServletContext`, `HttpServletRequest`, and `HttpServletResponse` The content highlights the use of the `@Controller` annotation and the `@RequestMapping` for routing requests in a Spring MVC application.
64 import org.springframework.web.bind.annotation.RequestMethod;
@RequestMapping("/download.do") public class FileDownloadController {
* Size of a byte buffer to read/write file
*/ private static final int BUFFER_SIZE = 4096;
* Path of the file to be downloaded, relative to application's directory
*/ private String filePath = "/downloads/SpringProject.zip";
* Method for handling file download request from client
@RequestMapping(method = RequestMethod.GET) public void doDownload(HttpServletRequest request,
// get absolute path of the application
System.out.println("appPath = " + appPath);
// construct the complete absolute path of the file
File downloadFile = new File(fullPath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// get MIME type of the file
String mimeType = context.getMimeType(fullPath); if (mimeType == null) {
// set to binary type if MIME mapping not found mimeType = "application/octet-stream";
System.out.println("MIME type: " + mimeType);
// set content attributes for the response response.setContentType(mimeType); response.setContentLength((int) downloadFile.length());
// set headers for the response
"attachment; filename=\"%s\"", downloadFile.getName()); response.setHeader(headerKey, headerValue);
// get output stream of the response
OutputStream outStream = response.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1;
// write bytes read from the input stream into the output stream while ((bytesRead = inputStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead);
Spring Controller là một phần quan trọng trong Spring MVC, sử dụng các chú thích (annotation) để xử lý yêu cầu từ máy khách Phương thức doDownload() cho phép máy chủ gửi dữ liệu đến máy khách mà không cần chỉ định tên view, vì mục tiêu chính là truyền tải thông tin Sau khi hoàn tất việc gửi dữ liệu, quá trình sẽ kết thúc ngay lập tức.
Vi t code cho t p tin Spring configuration
tin spring-mvc.xml trong WebContent\WEB-INF dung sau:
I don't know!
là tin hình Spring nó yêu framework hành scan gói net.codejava.spring tìm các chú thích ) nhiên ta có bean (bean definitions), này, hình là
Code c a t p tin web.xml
Spring dispatcher servlet c nh c u hình x lý các yêu c u trong t p tin web.xml nh sau:
The XML configuration for a web application defines its structure and schema, ensuring compliance with Java EE standards It specifies namespaces for XML schema instances and web application definitions, along with the versioning of the web application This configuration is essential for the proper functioning and deployment of Java-based web applications.
FileDownloadSpringMVC
SpringController
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/spring-mvc.xml
1
SpringController
*.do
Các t p tin jar c n thi t
Thêm các tin jar sau vào WebContent\WEB-INF\lib:
Các tin jar Commons Logging có Apache
Commons Logging, các tin jar khác Spring framework 3.2.1 RELEASE.
Ch y th ng d ng
khai trên máy Tomcat localhost, URL sau vào thanh c trình http://localhost:8080/FileDownloadSpringMVC/
Trang tải xuống cung cấp thông tin liên quan đến việc sử dụng máy tính Chúng tôi sẽ hướng dẫn bạn cách quản lý và xử lý thông tin một cách hiệu quả Những phương pháp này sẽ giúp bạn tối ưu hóa việc sử dụng dữ liệu trên thiết bị của mình.
- Phân tin trên yêu dùng
- soát truy vào các tin: ai có và khi có
- trí các tin trên máy
- trình email Spring MVC và Java Mail
- trình email có tin kèm Spring MVC
3.1 LAB 1: G I E-MAIL CÓ S D NG JAVA MAIL
Spring này cung Spring MVC cho phép dùng e-mail cách vào form e-mail sau:
Trong này, ta làm quen phát Java EE phát các trên Spring MVC dung:
4 hình cài máy SMTP và Spring MVC
6 trang (result page) và trang (error page)
H tr e-mail c a Spring framework
trên JavaMail, Spring framework cung API cao giúp hóa quá trình e-mail cách Hãy cùng xem qua API này trong sau:
BÀI 3: - 47 tin e-mail, chúng ta có giao MailSender -
JavaMailSenderImpl xây trên JavaMail hình khai này bean trong (context) Spring:
smtp
true
true
Bean này các tính cho SMTP và JavaMail và có vào business/service e-mail, ví
Trong email là thi giao MailMessage,
SimpleMailMessage Chúng ta có xây email sau:
SimpleMailMessage email = new SimpleMailMessage(); email.setTo(toAddress); email.setSubject(subject); email.setText(body); là túy) Trong e- mail HTML kèm vào e-mail, chúng ta có
MimeMailMessage giúp MimeMessagePreparator và MimeMessageHelper Ví e-mail HTML kèm:
4 mailSender.send(new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException
MimeMessageHelper(mimeMessage, true, "UTF-8"); message.setFrom(fromEmail); message.setTo(toEmail); message.setSubject("A file for you"); message.setText("See the attached", true); message.addAttachment("CoolStuff.doc", new File("CoolStuff.doc"));
}); sau tóm các giao và cung trong gói org.springframework.mail: org.springframework.mail
T p tin jar b t bu c
yêu sao chép các jar sau vào WEB-INF\lib nó:
The Spring framework includes several essential JAR files for effective application development, such as spring-beans-3.2.0.RELEASE.jar, spring-context-3.2.0.RELEASE.jar, spring-context-support-3.2.0.RELEASE.jar, spring-core-3.2.0.RELEASE.jar, spring-expression-3.2.0.RELEASE.jar, spring-web-3.2.0.RELEASE.jar, and spring-webmvc-3.2.0.RELEASE.jar Additionally, Apache Commons Logging is supported through commons-logging-1.1.1.jar These components are crucial for building robust applications and can be integrated through hyperlinks in the development process.
- Result.jsp: thông báo thành công sau khi e-mail
- Error.jsp: thông báo trong ném ra
- SendEmailController.java: Spring controller vào e-mail form, mailSender e-mail và dùng trang thành công trang
- spring-mvc.xml: hình Spring ta hình cài máy SMTP và các tính khác nhau cho JavaMail
- web.xml: mô khai web.
T o form g i e-mail
JSP có tên EmailForm.jsp code HTML sau:
Email with Spring MVC
Sending e-mail with Spring MVC
The article discusses the structure of an email form consisting of three fields: To, Subject, and Message When this form is submitted, it triggers the action defined in sendEmail.do The handling of this action is managed by a Spring controller.
C u hình cài t máy ch SMTP và Spring MVC
tin hình Spring có tên là spring-mvc.xml, code XML sau:
The Spring Framework utilizes XML configuration to define beans and their dependencies The XML schema for beans and context is specified to ensure proper validation and structure This configuration allows developers to manage application components effectively, promoting a modular and maintainable codebase.
smtp
true
true
Error
BÀI 3: - SPRING MVC 51 hình này khá
- : yêu Spring scan gói net.codejava.spring các thành chú thích Spring annotations là Spring controller, trong này)
- Bean mailSender: là quan vì nó khai báo Spring bean khai e-mail - JavaMailSenderImpl và hình cài máy SMTP, dành cho tài Gmail trong này Bean này vào
- Bean viewResolver: ánh logical view names thành tên tin JSP
- Bean SimpleMappingExceptionResolver: ánh các java.lang.Exception lý trang Error.jsp tin mô khai web (web.xml) hình sau:
The XML configuration for a web application defines its structure and versioning It specifies namespaces for XML schema instances and Java EE, ensuring compatibility with web standards The document outlines the web application's ID and version, which is crucial for deployment and functionality.
EmailSpringMVC
SpringController
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/spring-mvc.xml
1
SpringController
*.do
EmailForm.jsp
The Spring controller servlet is declared in the configuration file located at /WEB-INF/spring-mvc.xml This controller handles requests with URLs ending in *.do, and the corresponding view for these requests is the EmailForm.jsp page.
T o l p controller trong Spring MVC
lý e-mail, ta Spring controller sau:
The article discusses the implementation of a Spring framework controller that utilizes JavaMailSender for sending emails It includes necessary imports such as HttpServletRequest and SimpleMailMessage, and demonstrates the use of the @Autowired annotation for dependency injection The controller is mapped to handle HTTP requests through the @RequestMapping annotation, specifying the request method for email functionality.
@RequestMapping("/sendEmail.do") public class SendEmailController {
@RequestMapping(method = RequestMethod.POST) public String doSendEmail(HttpServletRequest request) {
// takes input from e-mail form
String recipientAddress = request.getParameter("recipient");
String subject = request.getParameter("subject");
String message = request.getParameter("message");
System.out.println("To: " + recipientAddress);
System.out.println("Subject: " + subject);
System.out.println("Message: " + message);
SimpleMailMessage email = new SimpleMailMessage(); email.setTo(recipientAddress); email.setSubject(subject); email.setText(message);
// sends the e-mail mailSender.send(email);
// forwards to the view named "Result" return "Result";
BÀI 3: - 53 controller này khá Nó khai báo là Spring MVC controller chú thích @Controller và ánh hành e-mail chú thích
Để gửi email trong Spring MVC, chúng tôi khai báo bean mailSender trong tệp spring-mvc.xml và sử dụng chú thích @Autowired trong controller Phương thức doSendEmail() sẽ tạo một đối tượng SimpleMailMessage và gọi phương thức send() trên bean mailSender để gửi email Kết quả trả về sẽ được xử lý bởi Spring viewResolver để tìm và hiển thị trang JSP tương ứng (Result.jsp).
Trang k t qu (result page) và trang báo l i (error page)
Code tin Result.jsp sau:
Send e-mail result
Thank you, your email has been sent.
Và code trang Error.jsp sau:
Sorry, the email was not sent because of the following error:
chúng ta trang cho dùng e-mail trong khi trang thông báo có nào ra trong quá trình e-mail.
Ch y ng d ng
To access the servlet container Tomcat, deploy the application and navigate to the following URL in your browser: http://localhost:8080/EmailSpringMVC Please note that the hostname may vary depending on your machine's configuration.
E-mail form ta thông tin vào: nút Send E-mail , có lúc e-mail thông báo thành công trang trong ra
Trong y ra không truy máy
3.2 LAB 2: G I E-MAIL CÓ T P TIN KÈM e-mail Spring MVC mô cách phát web
Java e-mail trong Spring MVC và JavaMail cho phép gửi e-mail với các thành phần cơ bản như người nhận, tiêu đề và nội dung Khi cần gửi thêm tệp đính kèm, có thể sử dụng các phương thức để thêm tệp vào e-mail một cách dễ dàng.
Form e-mail trông sau: khi e-mail, chúng ta lý tin lên (xem tin lên Spring MVC các bài Ta hãy xem khai nào dung:
2 form e-mail (có tin kèm)
3 hình Spring MVC lên tin và e-mail
5 các trang (result page) và trang (error page)
6 hình tin mô khai web
Các t p tin jar b t bu c
sau kê các jar cho này:
The Spring Framework includes several essential JAR files for building Java applications, such as spring-beans-3.2.0.RELEASE.jar, spring-context-3.2.0.RELEASE.jar, spring-context-support-3.2.0.RELEASE.jar, spring-core-3.2.0.RELEASE.jar, spring-expression-3.2.0.RELEASE.jar, spring-web-3.2.0.RELEASE.jar, and spring-webmvc-3.2.0.RELEASE.jar These components provide the necessary infrastructure for dependency injection, application context management, and web application development, ensuring a robust and scalable architecture for developers.
Apache Commons Logging commons-logging-1.1.1.jar
Apache Commons File Upload commons-fileupload-1.2.2.jar
Apache Commons IO commons-io-2.3.jar bao các sau:
Bây hãy xem xét chi sau
Vi t form g i e-mail (có t p tin kèm)
Code e-mail form (EmailForm.jsp) sau:
Spring MVC - Email
Spring MVC - Send e-mail with attachments
Có ba thông báo cho HTML form này:
- action = : tên hành lý form này
- enctype = "multiart/form-data": cho trình g form này
(multipart data) nên nó xây yêu (multipart request) máy
- nút tin (browse button) mà dùng có tin.
nh c u hình Spring MVC t i lên t p tin và e-mail
tin hình Spring spring-mvc.xml code XML sau:
I don't know!
smtp
true
true
Error
Có bean khai báo trong hình này thu hút chú ý:
1 mailSender: hình cài SMTP và tính JavaMail là hình dành cho tài GMail Vì vui lòng này phù cài tài
2 MultiartResolver: bean này dùng phân tích cú pháp yêu
(multipart request) khai CommonsMultipartResolver trên Apache Commons File Upload Chúng ta hình hai cài tin lên:
- maxUploadSize: kích (tính byte) yêu bao lên, thành 20 MB
- maxInMemorySize: quá mà lên vào thay vì trong nó thành 1MB
3 viewResolver: ánh logical view names thành tên tin JSP
4 SimpleMappingExceptionResolver: trang (Error.jsp) lý các ném ra các java.langException)
yêu Spring tìm trong gói net.codejava.spring các có chú thích (vì chúng tôi Spring controller cách chú thích, annotations sau này).
Tri n khai controller b ng Spring MVC
Java có tên là SendEmailAttachController code sau:
This article discusses the implementation of email functionality in a Spring application using the JavaMailSender It highlights the necessary imports, including MimeMessage and MimeMessageHelper, and outlines the use of annotations such as @Controller and @RequestMapping to handle HTTP requests Additionally, it mentions the handling of file uploads through CommonsMultipartFile, enabling users to send emails with attachments The integration of these components facilitates efficient email communication within the application.
@RequestMapping("/sendEmail.do") public class SendEmailAttachController {
@RequestMapping(method = RequestMethod.POST) public String sendEmail(HttpServletRequest request, final @RequestParam CommonsMultipartFile attachFile) {
// reads form input final String emailTo = request.getParameter("mailTo"); final String subject = request.getParameter("subject"); final String message = request.getParameter("message");
System.out.println("emailTo: " + emailTo);
System.out.println("subject: " + subject);
System.out.println("message: " + message);
System.out.println("attachFile: " + attachFile.getOriginalFilename());
@Override public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper messageHelper = new MimeMessageHelper( mimeMessage, true, "UTF-8"); messageHelper.setTo(emailTo); messageHelper.setSubject(subject); messageHelper.setText(message);
// determines if there is an upload file, attach it to the e-mail String attachName = attachFile.getOriginalFilename(); if (!attachFile.equals("")) { messageHelper.addAttachment(attachName, new InputStreamSource() {
@Override public InputStream getInputStream() throws IOException { return attachFile.getInputStream();
Spring Controller này chú thích @Controller) trách lý e-mail form hình hai chú thích
Tham hai sendEmail() chú thích chú thích
@RequestParam ánh attachFile CommonsMultipartFile n cho tin lên
Trong sendEmail(), ta các (field) vào e-mail form (mailTo, subject và message) và e-mail cách send() trên mailSender vào controller này qua tính mailSender) send() danh giao
MimeMessagePreparator và khai prepare() Trong prepare(), Ta xây ng thông báo e-mail giúp
The MimeMessageHelper class and its addAttachment() method are used to attach files to emails This functionality is essential for including attachments in the email Additionally, a logic page named Result is utilized to manage the attachment details, allowing us to add specific file names as needed.
Trang k t qu (result page) và trang l i (error pages)
Code trang (Result.jsp) sau:
Send e-mail result
Thank you, your email has been sent.
Trang này thông báo thành công sau khi lên và e-mail
Và code trang (Error.jsp) sau:
Sorry, the email was not sent because of the following error:
Trang này thông báo chi trong có kích lên quá cài SMTP sai.
nh c u hình t p tin mô t tri n khai web
hình tin web.xml sau:
The XML configuration for a web application defines its structure and schema, specifying namespaces and versioning It includes essential attributes such as `xmlns:xsi`, `xmlns`, and `xsi:schemaLocation`, which ensure compliance with Java EE standards The document is identified by `id="WebApp_ID"` and is set to version `3.0`, indicating its compatibility with the Java EE framework.
EmailAttachSpringMVC
SpringController
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/spring-mvc.xml
1
SpringController
*.do
EmailForm.jsp
khai báo Spring controller servlet các yêu và trang (EmailForm.jsp) khi truy
- trình có tích JdbcTemplate trong Spring
- trình có tích Spring và Hibernate c hình XML
- trình có tích Spring và Hibernate c hình Java.
LAB1: JDBC TEMPLATE TRONG SPRING MVC
Spring hỗ trợ việc sử dụng JDBC thông qua JdbcTemplate và các thành phần trong gói org.springframework.jdbc.core Bài viết này sẽ trình bày cách tích hợp JdbcTemplate trong Spring MVC.
4.1.1 T o s d li u b ng MySQL thi MySQL script sau có tên contactdb và có tên contact:
`contact_id` int(11) NOT NULL AUTO_INCREMENT,
) ENGINE=InnoDB AUTO_INCREMENT% DEFAULT CHARSET=utf8
4.1.2 T o Maven Project b ng Eclipse spring-mvc-archetype project là trúc cùng project: phát cách các và công sau ( có các phiên
- Maven 3 trong này lý danh sách các contact (danh sau:
XML sau trong tin pom.xml là thêm các dependencies vào project:
4.0.3.RELEASE
javax.servlet-api
javax.servlet.jsp
javax.servlet.jsp-api
4.1.3 Vi t code cho l p Model dung model tên là Contact.java khá sau:
10 package net.codejava.spring.model; public class Contact { private int id; private String name; private String email; private String address; private String telephone; public Contact() {
} public Contact(String name, String email, String address, String telephone) { this.name = name; this.email = email; this.address = address; this.telephone = telephone;
} này là ánh hàng trong contact plain old Java object (POJO) - Contact
4.1.4 Vi t code cho các l p DAO
Interface tên là ContactDAO các các hành
19 package net.codejava.spring.dao; import java.util.List; import net.codejava.spring.model.Contact;
* Defines DAO operations for the contact model
*/ public interface ContactDAO { public void saveOrUpdate(Contact contact); public void delete(int contactId); public Contact get(int contactId); public List list();
Và là (implementation) - ContactDAOImpl.java:
The article discusses the Java package `net.codejava.spring.dao`, which includes imports for handling SQL operations, such as `ResultSet` and `SQLException` It also emphasizes the use of a `DataSource` and the management of `Contact` model objects, while addressing potential `DataAccessException` issues in Spring applications.
47 import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.jdbc.core.RowMapper;
* An implementation of the ContactDAO interface
*/ public class ContactDAOImpl implements ContactDAO { private JdbcTemplate jdbcTemplate; public ContactDAOImpl(DataSource dataSource) { jdbcTemplate = new JdbcTemplate(dataSource);
@Override public void saveOrUpdate(Contact contact) {
@Override public void delete(int contactId) {
@Override public List list() {
@Override public Contact get(int contactId) {
Hãy chú ý khai báo JdbcTemplate và
DataSource vào thông qua hàm (constructor):
5 private JdbcTemplate jdbcTemplate; public ContactDAOImpl(DataSource dataSource) { jdbcTemplate = new JdbcTemplate(dataSource);
Insert update contact contact có ID 0, hãy nó (update); không thì là hành insert (chèn
2 public void saveOrUpdate(Contact contact) { if (contact.getId() > 0) {
String sql = "UPDATE contact SET name=?, email=?, address=?, "
+ "telephone=? WHERE contact_id=?"; jdbcTemplate.update(sql, contact.getName(), contact.getEmail(), contact.getAddress(), contact.getTelephone(), contact.getId());
String sql = "INSERT INTO contact (name, email, address, telephone)" + " VALUES (?, ?, ?, ?)"; jdbcTemplate.update(sql, contact.getName(), contact.getEmail(), contact.getAddress(), contact.getTelephone());
4 public void delete(int contactId) {
String sql = "DELETE FROM contact WHERE contact_id=?"; jdbcTemplate.update(sql, contactId);
String sql = "SELECT * FROM contact";
List listContact jdbcTemplate.query(sql, new RowMapper() {
@Override public Contact mapRow(ResultSet rs, int rowNum) throws SQLException {
To create a new contact, initialize a Contact object and set its properties using data retrieved from the database, including the contact ID, name, email, address, and telephone number Finally, return the populated Contact object.
} ý RowMapper ánh hàng trong (result set) thành POJO ta có
String sql = "SELECT * FROM Contact";
5 return jdbcTemplate.query(sql, BeanPropertyRowMapper.newInstance(Contact.class)); }
Contact khai báo tên chính xác tên trong
22 public Contact get(int contactId) {
String sql = "SELECT * FROM contact WHERE contact_id=" + contactId; return jdbcTemplate.query(sql, new ResultSetExtractor() {
@Override public Contact extractData(ResultSet rs) throws SQLException,
The code snippet creates a new instance of the Contact class and populates its fields with data retrieved from a result set It sets the contact's ID, name, email, address, and telephone number using the corresponding values from the database Finally, it returns the populated contact object.
} ý ResultSetExtractor trích hàng POJO có BeanPropertyRowMapper sau:
5 public Contact get(int contactId) {
String sql = "SELECT * FROM Contact WHERE id=" + contactId; return jdbcTemplate.queryForObject(sql,
4.1.5 Vi t code t p tin Spring MVC Configuration
Các và chú thích (annotations) trên Java hình Spring MVC này là code MvcConfiguration:
4 package net.codejava.spring.config; import javax.sql.DataSource;
This article discusses the configuration of a Spring application, highlighting the importation of essential classes such as `ContactDAO` and `ContactDAOImpl` It emphasizes the use of annotations like `@Bean`, `@ComponentScan`, and `@Configuration` to define beans and manage component scanning The article also mentions the setup of a `DriverManagerDataSource` for database connectivity and the implementation of `ViewResolver` for handling views Additionally, it covers the enabling of Spring MVC through the `@EnableWebMvc` annotation and the configuration of resource handling with `ResourceHandlerRegistry`, all while utilizing the `WebMvcConfigurerAdapter` for enhanced web application configuration.
@ComponentScan(basePackages="net.codejava.spring")
@EnableWebMvc public class MvcConfiguration extends WebMvcConfigurerAdapter{
InternalResourceViewResolver resolver new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver;
@Override public void addResourceHandlers(ResourceHandlerRegistry registry)
{ registry.addResourceHandler("/resources/**") addResourceLocations("/resources/");
DriverManagerDataSource dataSource new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/contactdb"); dataSource.setUsername("root"); dataSource.setPassword("P@ssw0rd"); return dataSource;
@Bean public ContactDAO getContactDAO() { return new ContactDAOImpl(getDataSource());
} ý getDataSource () bean DataSource hình có thay database URL, username và password tùy theo môi
BÀI 4: 73 getContactDAO() khai giao ContactDAO, là
ContactDAOImpl Bean này vào controller, mô sau
4.1.6 C u hình Spring MVC Dispatcher Servlet
Và kích Spring MVC cho web Java chúng ta, hãy tin mô khai web (web.xml) bên
Java is a powerful programming language that drives innovation in the digital world It offers a range of resources for students, hobbyists, developers, and IT leaders, enabling them to harness its potential The latest versions of Java, including Java SE 24, provide essential tools and features for developers Oracle's commitment to Java is evident through its extensive support, including APIs, certification, and community engagement With a focus on security and cloud technologies, Java continues to evolve, making it a vital choice for modern software development.
SpringMvcJdbcTemplate
contextClass
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
org.springframework.web.context.ContextLoaderListener
SpringDispatcher
org.springframework.web.servlet.DispatcherServlet
contextClass
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
contextConfigLocation
net.codejava.spring
1
SpringDispatcher
4.1.7 Vi t code cho l p Spring Controller khung HomeController sau:
Ta chú thích @Autowosystem Spring phiên khai ContactDAO vào controller này lý contactDAO này các hành CRUD Hãy xem chi khai sau kê các contacts xem là home page):
@RequestMapping(value="/") public ModelAndView listContact(ModelAndView model) throws IOException{
List listContact = contactDAO.list(); model.addObject("listContact", listContact); model.setViewName("home"); return model;
@RequestMapping(value = "/newContact", method = RequestMethod.GET) public ModelAndView newContact(ModelAndView model) {
Contact newContact = new Contact(); model.addObject("contact", newContact); model.setViewName("ContactForm"); return model;
@RequestMapping(value = "/saveContact", method = RequestMethod.POST) public ModelAndView saveContact(@ModelAttribute Contact contact) { contactDAO.saveOrUpdate(contact); return new ModelAndView("redirect:/");
@RequestMapping(value = "/deleteContact", method = RequestMethod.GET) public ModelAndView deleteContact(HttpServletRequest request) { int contactId = Integer.parseInt(request.getParameter("id"));
6 contactDAO.delete(contactId); return new ModelAndView("redirect:/");
@RequestMapping(value = "/editContact", method = RequestMethod.GET) public ModelAndView editContact(HttpServletRequest request) { int contactId = Integer.parseInt(request.getParameter("id"));
Contact contact = contactDAO.get(contactId);
ModelAndView model = new ModelAndView("ContactForm"); model.addObject("contact", contact); return model;
4.1.8 Vi t code cho trang li t kê các Contact (Home Page) là mã trang home.jsp danh sách contact các liên hành và xóa contact
Contact Manager Home
Edit
Delete
Trang JSP này các JSTL và EL
4.1.9 Vi t code cho trang Contact Form
Trang contact form (ContactForm.jsp) chi contact contact là code nó:
New/Edit Contact
Trang JSP này Spring form tags liên các giá form model
4.2 LAB2: HIBERNATE C U HÌNH B NG XML
Trong phát enterprise Java (doanh , có tích Spring và
Hibernate là một framework ORM phổ biến mà các lập trình viên thường sử dụng, trong khi Spring là một framework doanh nghiệp mạnh mẽ Cả hai framework này đều được phát triển để hỗ trợ các ứng dụng doanh nghiệp hiệu quả.
là giúp ta dàng xây Spring-Hibernate cách rõ ràng và Trong tiên này trình bày cách code
Spring MVC danh sách ng dùng
MySQL khai DAO SessionFactory truy thay vì JdbcTemplate
Các pháp hình sau trong demo này:
- Spring MVC: chú thích (annotation) cho controller và XML cho các bean
- Hibernate: ánh XML cho model
- Web Application: mô khai web.xml
Các công và sau trong này:
- Tomcat 7 nhiên ta có các phiên các công và nói trên
4.2.1 Cách Spring h tr tích h p Hibernate tích Hibernate, Spring cung hai bean chính có trong gói org.springframework.orm.hibernate4:
- HibernateTransactionManager: cung code giao cho
SessionFactory Các trình viên có chú thích @Transactional trong các DAO tránh code giao boiler-plate cách rõ ràng Hãy xem các khái này khai nào trong project
Hãy project Spring MVC tên là SpringMvcHibernateXML thi MySQL script sau có tên usersdb có tên là users:
`user_id` int(11) NOT NULL AUTO_INCREMENT,
) ENGINE=InnoDB AUTO_INCREMENT DEFAULT CHARSET=latin1
Hãy (insert) cho trúc project
Hình sau cho trúc cùng project:
Sau khi hoàn thành này, ta có trúc project trên Maven Dependencies
Khai báo các phiên cho Java và Spring framework:
4.0.3.RELEASE
tin pom.xml các dependencies sau:
${org.springframework-version}
${org.springframework-version}
${org.springframework-version}
- Java Servlet và JSP dependencies (dành cho biên
javax.servlet-api
javax.servlet.jsp
javax.servlet.jsp-api
org.apache.commons
- MySQL Connector Java dependency (JDBC driver dành cho MySQL):
mysql-connector-java
4.2.3 Vi t code l p Model c u hình Hibernate Mapping code Model có tên User.java trong gói net.codejava.spring.model mã sau:
11 package net.codejava.spring.model; public class User { private int id; private String username; private String password; private String email;
// getters and setters are removed for brevity
} model này ánh users và
Java túy (plain-old Java object - POJO)
Hibernate XML Mapping cho Model
Ta t tin ánh XML Hibernate ánh User users trong t tin User.hbm.xml trong cùng gói User code XML sau:
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
tin Hibernate XML Configuration t tin hibernate.cfg.xml classpath (ngay trong src project) code XML sau:
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
org.hibernate.dialect.MySQLDialect
true
T tin hình Hibernate này khai báo tài nguyên nào ánh
User.hbm.xml trong này)
UserDAO interface giao DAO cho User UserDAO.java sau:
9 package net.codejava.spring.dao; import java.util.List; import net.codejava.spring.model.User; public interface UserDAO { public List list();
Interface này khai báo tên là list() truy user code cho UserDAO implementation là ta code implementation of the UserDAO interface, UserDAOImpl sau:
The `User DAOImpl` class, part of the `net.codejava.spring.dao` package, implements the `User DAO` interface and utilizes Hibernate for database operations It imports necessary classes such as `List`, `User `, `Criteria`, and `SessionFactory`, and is annotated with `@Transactional` to manage transactions effectively.
29 private SessionFactory sessionFactory; public UserDAOImpl(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory;
@Transactional public List list() {
List listUser = (List) sessionFactory.getCurrentSession()
setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list(); return listUser;
} ý trong này, SessionFactory Hibernate vào thông qua Spring list() phiên (current session) SessionFactory và truy danh sách users trong
Pay attention to the @Transactional annotation provided by Spring When this annotation is used, Spring automatically supports transaction management, even if the code does not explicitly handle transactions.
We connect Spring and Hibernate through an XML configuration file, specifically the `servlet-context.xml` located in `src/main/webapp/WEB-INF/spring/appServlet` This file is utilized for configuring Spring MVC View Resolvers To implement the annotation-driven approach in Spring MVC, additional declarations must be added.
Khai báo sau cho common view resolver logical view names thành các trang JSP
1
S Apache Commons DBCP cho data source có
Thay database URL, username và password theo các giá trong môi này vào bean SessionFactory bên hình SessionFactory Bean
Spring 4 cung cho SessionFactory Hibernate 4 thông qua LocalSessionFactoryBean là FactoryBean ra
SessionFactory, sau vào các Hibernate-based DAO beans là khai báo bean:
LocalSessionFactoryBean này yêu bean DataSource khai báo
Trong này, là hibernate.cfg.xml trong classpath hình TransactionManager Bean
Khai báo sau dành cho giao (automatic transaction) cho SessionFactory:
BÀI 4: 85 trong UserDAOImpl, ta có giao cách chú thích @Transactional cho các giao hình DAO Bean
Và cùng, hình cho bean UserDAOImpl khá
Sau bean này vào Spring MVC controller mô bên
4.2.6 Vi t code cho các l p Controller
Write our Spring MVC controller class (HomeController.java) under the net.codejava.spring package with the following code:
Spring MVC controller (HomeController.java) trong gói net.codejava.spring code sau:
The article discusses a Java package named `net.codejava.spring`, which imports essential classes and interfaces for managing user data It includes the `User DAO` for data access and the `User ` model for user representation The `@Controller` annotation indicates that the class serves as a Spring MVC controller, while `@Autowired` is used for dependency injection The `RequestMapping` annotation is utilized to define request handling methods, and `ModelAndView` is employed to return the view and model data in response to web requests.
* Handles requests for the application home page
@RequestMapping(value="/") public ModelAndView home() {
List listUsers = userDao.list();
ModelAndView model = new ModelAndView("home");
30 model.addObject("userList", listUsers); return model;
} khai UserDAO Spring vào (do chú thích
@Autowosystem có bean UserDAOImpl mà ta khai báo trong t tin hình Spring (Spring application context configuration file) không? Nó vào controller này lý home() có nó kê users
Và cùng, home() view có tên là home phân là trang JSP mô
4.2.7 Vi t code cho View Page trang home.jsp trong src/main/webapp/WEB-INF/views dung sau:
Trang JSP này danh sách users controller thông qua cách các JSTL
To deploy the SpringMvcHibernateXML application on a Tomcat server, access its default page using the URL: http://localhost:8080/SpringMvcHibernateXML Ensure that the server is running properly to avoid connection issues.
Xin chúc hoàn thành tiên tích Spring-
4.3 LAB3: HIBERNATE C U HÌNH B NG JAVA
Bài tích Spring và Hibernate này trình bày cách phát
Spring MVC - Hibernate mà không hình XML nào Các pháp hình sau cho demo này:
- Spring MVC: chú thích (annotation) cho controller, DAO và hình trên Java cho các bean
- Hibernate: ánh annotation cho model
- là và r 1 hình XML), nên không project (bao và hình
- hình trên XML Java là nào là tùy vào thích và tình hình Bài này không có ý phân cái nào thích
Các công và sau trong này nhiên ta có các phiên
- Java EE: Servlet 3.1, JSP 2.3, JSTL 1.2
Thay vì XML trong tin web.xml ký Spring Dispatcher Servlet, chúng ta có di mã bootstrap vào Java khai
ServletContainerInitializerinterface Servlet 3.0 Spring framework cung khai (implementation) - SpringServletContainerInitializer
Servlet cho khai nào giao
Do hãy SpringWebAppInitializer mã bootstrap chúng ta sau:
The `SpringWebAppInitializer` class implements the `WebApplicationInitializer` interface, allowing for the configuration of a Spring web application It imports necessary packages such as `javax.servlet` for servlet context management and `org.springframework.web` for Spring framework integration The class sets up an `AnnotationConfigWebApplicationContext` and registers a `DispatcherServlet`, which is essential for handling incoming web requests in a Spring MVC application.
@Override public void onStartup(ServletContext servletContext) throws ServletException
AnnotationConfigWebApplicationContext appContext new AnnotationConfigWebApplicationContext(); appContext.register(ApplicationContextConfig.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"SpringDispatcher", new DispatcherServlet(appContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/");
} code trong onStartup() khi vùng Servlet này Spring Dispatcher Servlet lý các yêu ánh
Spring Dispatcher Servlet AnnotationConfigWebApplicationContext, trách các liên quan Spring cách các chú thích các hình là ApplicationContextConfig, trong các bên Spring-web-VERSION.jar trên classpath bootstrap này có
4.3.2 Ánh x Model Class s d ng JPA Annotations
Thay vì ánh Hibernate XML cho model 1, chúng ta nhúng các chú thích JPA vào model sau (User.java):
26 package net.codejava.spring.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table;
@Table(name = "USERS") public class User { private int id; private String username; private String password; private String email;
@Column(name = "USER_ID") public int getId() { return id;
// other getters and setters are hidden for brevity
} ý tên tính model tên trong chúng ta không ánh cách rõ ràng
Trong 1, UserDAO interface khai báo list() Bây ta nó cho các hành CRUD Do hãy c UserDAO interface code sau:
6 package net.codejava.spring.dao; import java.util.List; import net.codejava.spring.model.User;
15 public interface UserDAO { public List list(); public User get(int id); public void saveOrUpdate(User user); public void delete(int id);
} khai nó - UserDAOImpl sau code sau:
The code snippet demonstrates a Spring Data Access Object (DAO) implementation for managing user data It imports necessary classes and interfaces, including Hibernate's Criteria and Query for database operations The DAO is annotated with @Repository, indicating its role in data persistence, and it utilizes @Transactional to manage transactions The SessionFactory is injected using @Autowired, allowing for the creation of database sessions.
@Repository public class UserDAOImpl implements UserDAO {
@Autowired private SessionFactory sessionFactory; public UserDAOImpl() {
} public UserDAOImpl(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory;
@Transactional public List list() {
List listUser (List) sessionFactory.getCurrentSession()
setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list(); return listUser;
@Transactional public void saveOrUpdate(User user) { sessionFactory.getCurrentSession().saveOrUpdate(user);
@Transactional public void delete(int id) {
User userToDelete = new User(); userToDelete.setId(id); sessionFactory.getCurrentSession().delete(userToDelete);
@Transactional public User get(int id) {
String hql = "from User where id=" + id;
Query query sessionFactory.getCurrentSession().createQuery(hql);
List listUser = (List) query.list(); if (listUser != null && !listUser.isEmpty()) { return listUser.get(0);
Chúng ta xem cách hình SessionFactory và TransationManager trong theo bên
4.3.4 C u hình Spring Application Context b ng Java
Bây ta quan và thú này hình các bean cách mã Java thay vì XML
ApplicationContextConfig các chú thích Spring sau:
Chú thích @Configuration là hình trên Java nào trong Spring Chú thích @ComponentScan yêu Spring quét gói tìm các chú thích HomeController trong này)
Chú thích @EnableTransactionManager cho phép lý giao theo chú thích Spring annotation-driven transaction management)
Hãy xem cách thành hình mã Java
BÀI 4: 93 hình Spring MVC View Resolvers sau hình view resolver tên logical view thành các trang JSP
@Bean(name = "viewResolver") public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver;
} hình DataSource Bean sau hình DataSource SessionFactory:
@Bean(name = "dataSource") public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/usersdb"); dataSource.setUsername("root"); dataSource.setPassword("secret"); return dataSource;
- Chúng tôi DataSource Apache Commons DBCP cho tiêu
- Hãy thay các tính DataSource theo môi (your environment)
Data source này vào bean SessionFactory bên hình SessionFactory Bean sau hình bean SessionFactory:
@Bean(name = "sessionFactory") public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder(dataSource); sessionBuilder.addAnnotatedClasses(User.class); return sessionBuilder.buildSessionFactory();
} hình trên Java, Spring cung LocalSessionFactoryBuilder
LocalSessionFactoryBean thay ý câu này yêu
Hibernate User vào các ánh nó:
1 sessionBuilder.addAnnotatedClasses(User.class); thêm
1 sessionBuilder.addAnnotatedClasses(User.class, Object.class); quét các gói tìm các chú thích (annotated classes):
1 sessionBuilder.scanPackages("net.codejava.model");
1 sessionBuilder.setProperty("hibernate.show_sql", "true"); các tính Hibernate:
Trong khi getHibernateProperties() khai sau:
Properties properties = new Properties(); properties.put("hibernate.show_sql", "true"); properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); return properties;
Bean SessionFactory này bean UserDAO bên hình TransactionManager Bean sau hình HibernateTransactionManager cho SessionFactory:
@Bean(name = "transactionManager") public HibernateTransactionManager getTransactionManager(
HibernateTransactionManager transactionManager new HibernateTransactionManager(sessionFactory); return transactionManager;
} cách transaction manager, code trong DAO không quan tâm lý giao cách rõ ràng Thay vào chú thích
@Transactional thông báo cho Spring chèn mã lý giao vào bytecode hình DAO Bean sau hình bean là UserDAO implementation:
@Bean(name = "userDao") public UserDAO getUserDao(SessionFactory sessionFactory) { return new UserDAOImpl(sessionFactory);
Bean UserDAO này vào controller kê bên
Ngoài list() duy trong 1, HomeController lý các hành CRUD danh sách các users:
The article discusses a Java Spring controller package, specifically focusing on the importation of necessary classes such as List, HttpServletRequest, UserDAO, and User model It highlights the use of annotations like @Autowired and @Controller, as well as the @ModelAttribute and @RequestMapping for handling user data and requests within the application.
62 import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView;
* Handles requests for the application home page
@RequestMapping("/") public ModelAndView handleRequest() throws Exception {
List listUsers = userDao.list();
ModelAndView model = new ModelAndView("UserList"); model.addObject("userList", listUsers); return model;
@RequestMapping(value = "/new", method = RequestMethod.GET) public ModelAndView newUser() {
ModelAndView model = new ModelAndView("UserForm"); model.addObject("user", new User()); return model;
@RequestMapping(value = "/edit", method = RequestMethod.GET) public ModelAndView editUser(HttpServletRequest request) { int userId = Integer.parseInt(request.getParameter("id"));
User user = userDao.get(userId);
ModelAndView model = new ModelAndView("UserForm"); model.addObject("user", user); return model;
@RequestMapping(value = "/delete", method = RequestMethod.GET) public ModelAndView deleteUser(HttpServletRequest request) { int userId = Integer.parseInt(request.getParameter("id")); userDao.delete(userId); return new ModelAndView("redirect:/");
@RequestMapping(value = "/save", method = RequestMethod.POST) public ModelAndView saveUser(@ModelAttribute User user) { userDao.saveOrUpdate(user); return new ModelAndView("redirect:/");
} controller này trách lý công kê users, và xóa user
4.3.6 C p nh t trang li t kê User
UserList.jsp JSTL kê danh sách users controller:
Edit
Delete
Trang này kê users và cung các hành và xóa
4.3.7 Vi t code cho trang User Form
UserForm.jsp các Spring ( form tags) ánh
User trong model và HTML form:
New or Edit User
Trang này khi user user có
Hình sau cho cùng project trong Eclipse STS (Spring Tools Suite):
LAB1
này giúp làm quen các Spring
Security framework các trên Spring Ta cách Spring
Security hóa xác và phóng các trình viên code
Trong này, ta hình XML
Spring Security là framework soát truy và xác và có tùy cao là tiêu các trên
Spring Security là framework trung vào cung xác và (authentication and authorization) cho các Java các án Spring, Spring Security tìm nó có dàng các yêu tùy
Spring Security có tích API Servlet và Spring Web MVC Tính Spring Security, khi tích Spring MVC, là nó cung các và hình dàng xác và
6.1.2 Ví d m u v ng d ng Spring Security
Bài này các xây Spring MVC trang có truy cho và trang viên có truy dùng
Khi dùng truy trang viên, yêu tên dùng và ta trang viên không, thông báo
Và sau khi dùng có t.
6.1.3 T o m t Dynamic Web Project v i Maven tiên, project trong Eclipse Ta có Maven project (File > New
> Maven Project) cho web Java cách xác tùy gói thành tin war ta có án web (Dynamic WebProject)
(File > New > Dynamic WebProject), (convert) án thành Maven
Trong án này, các và công sau có version chúng):
6.1.4 Thêm vào các Maven Dependencies
Trong tin Maven project (pom.xml), khai báo các tính sau:
4.2.4.RELEASE
4.0.3.RELEASE
là các phiên Spring framework, Spring security và JSTL theo, khai báo các (dependency) cho Spring và Spring Web MVC:
Dependencies cho Spring Security Web và Spring Security Config:
org.springframework.security
spring-security-web
${spring.security.version}
org.springframework.security
spring-security-config
${spring.security.version}
Và dependency cho JSTL khi ta các JSTL trong các trang JSP:
6.1.5 Vi t code cho trang Index (Index Page) là các views trong /WEB-INF, sau tin index.jsp code HTML sau:
Spring Security Basic Demo (XML)
Spring Security Basic Demo (XML)
Go to Administrator Page
là trang tiêu Security Basic Demo và hyperlink trang viên (administrator page)
6.1.6 Vi t code cho trang Admin (Admin Page) theo, tin admin.jsp trong /WEB-INF/views mã sau:
Spring Security Basic Demo (XML)
Welcome : ${pageContext.request.userPrincipal.name} |
Logout
BÀI 6: 131 là trang viên (administrator page) yêu xác (authentication) và (authorization) truy Ta các JSTL tiêu và thông báo trong model dùng hãy tên dùng cùng liên (logout link)
6.1.7 Vi t code cho Spring MVC Controller theo, ta code cho Spring controller lý các yêu (requests)
Java có tên MainController gói net.codejava.spring code sau:
24 package net.codejava.spring; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView;
@RequestMapping(value="/", method = RequestMethod.GET) public ModelAndView visitHome() { return new ModelAndView("index");
@RequestMapping(value="/admin", method = RequestMethod.GET) public ModelAndView visitAdmin() {
ModelAndView model = new ModelAndView("admin"); model.addObject("title", "Admministrator Control Panel"); model.addObject("message",
"This page demonstrates how to use Spring security."); return model;
} có controller này lý 2 yêu
- yêu trang ( context root) trang
- yêu trang viên, trang này Spring security.
Các annotations (chú thích) @Controller và @RequestMapping khai báo là controller có hai lý HTTP GET Các chú thích này
Spring scan vì ta hình trong
6.1.8 C u hình Web Deployment Descriptor (web.xml)
Trong tin mô khai web (web.xml trong /WEB-INF), ta hình cách Spring MVC và Spring Security trong gian g là dung tin web.xml:
The provided XML snippet defines a web application configuration for Java EE, specifying the XML namespaces and schema locations It includes attributes such as the application ID and version, indicating compliance with the Java EE 3.1 specification.
Spring Security Basic XML
SpringController
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/spring-mvc.xml
1
SpringController
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
/WEB-INF/spring-security.xml
springSecurityFilterChain
org.springframework.web.filter.DelegatingFilterProxy
springSecurityFilterChain
The Spring framework utilizes a servlet to manage URL declarations, while the Spring Web Context Loader Listener is essential for initializing the Spring context It is important to note that the Spring Security configuration is defined in the spring-security.xml file located in the /WEB-INF directory, which plays a crucial role in the Spring Security Filter.
springSecurityFilterChain
org.springframework.web.filter.DelegatingFilterProxy
springSecurityFilterChain
Spring Security Filter là (ntercept) URL áp xác và hình trong tin Spring security configuratio.
6.1.9 C u hình Spring MVC Application Context theo, ta hình Spring MVC scan các Java cho controller và resolve view names tin spring-mvc.xmlfile trong /WEB-INF mã sau:
I don't know!
ta quen Spring MVC, yêu Spring phân tích các chú thích configurations and controllers
gói Java nào tìm các thành Spring
Và bean tên là InternalResourceViewResolver khai báo cho Spring cách phân (resolve) logical view names thành physical view pages
6.1.10 C u hình Spring Security cùng là khai báo xác (ai có và (ai có truy trang nào) tin spring-security.xml trong /WEB-INF code sau:
I don't know!
có hai xác và
- khai báo dùng (user) username, password and role (ROLE_ADMIN cho hình này) dùng này có xác truy
- Trong , ta khai báo URL nào
Spring, Theo hình này, các URL
/admin** và dùng có role (vai trò) là
ROLE_ADMIN có phép truy các URL này ý yêu Spring (Spring security filter) liên /logout yêu HTTP GET
6.1.11 C u trúc toàn b project cùng, chúng ta thúc trúc project sau:
6.1.12 Ch y ki m tra ng d ng Spring Security m u khai án trên Tomcat, sau URL sau vào trình http://localhost:8080/SpringSecurityBasicXML
Ta trang index (index page) sau:
Trên trang này, vào liên Go to Administrator Page, gõ http://localhost:8080/SpringSecurityBasicXML/admin
Spring security trang (default login page) sau: sai tên dùng và (username và password), Spring security thông báo màu form, trong hình sau:
Bây tên dùng và chính xác (admin và nimda, theo hình trong này), Spring trang t
Bây hãy tra (logout) vào liên Logout,
Spring security URL/logout, làm phiên (session) và ta trang (login page):
Chú ý là thông báo You have been logged và URL thay thành http://localhost:8080/SpringSecurityBasicXML/login?logout
Spring security làm phiên (session), hãy truy vào trang: http://localhost:8080/SpringSecurityBasicXML/admin ta trang
Chúng ta Spring security project hình XML
Bài này Spring Web MVC hình code Java
Tham thêm Spring Web MVC hình XML
Spring Security framework Bây tìm cách chú thích (annotation) và hình Java Spring Web MVC
Ta Eclipse IDE project web (dynamic web project), sau nó thành Maven project
Project Spring MVC Security Java Config phát cách các công sau nhiên ta có các phiên
- Eclipse IDE, Mars Release (4.5.0) hình cho các dependencies Maven liên quan Spring Security sau:
org.springframework.security
spring-security-web
${spring.security.version}
org.springframework.security
spring-security-config
${spring.security.version}
6.2.2 Vi t code cho trang Index Page có tên là views trong /WEB-INF, sau tin index.jsp code HTML sau:
Spring Security Basic Demo (Java Config)
Spring Security Basic Demo (Java Config)
Go to Administrator Page
là trang tiêu Security Basic Demo (Java và hyperlink trang viên (administrator page) yêu xác truy
6.2.3 Vi t code trang Admin (Admin Page) theo, tin admin.jsp trong /WEB-INF/views code sau:
Spring Security Basic Demo (Java Config)
Welcome : ${pageContext.request.userPrincipal.name} |
Logout
ây là trang viên (administrator page) yêu xác và
(authentication và authorization) truy Ta các JSTL tiêu và thông báo trong model dùng hãy tên dùng cùng liên (logout link)
6.2.4 Vi t code cho Spring MVC Controller theo, ta code cho Spring controller lý các yêu
Java có tên MainController trong gói net.codejava.spring code sau:
24 package net.codejava.spring; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView;
* Spring Web MVC Security Java Config Demo Project
* Primary controller of the application
@RequestMapping(value="/", method = RequestMethod.GET) public ModelAndView visitHome() { return new ModelAndView("index");
@RequestMapping(value="/admin", method = RequestMethod.GET) public ModelAndView visitAdmin() {
ModelAndView model = new ModelAndView("admin"); model.addObject("title", "Admministrator Control Panel"); model.addObject("message",
"This page demonstrates how to use Spring security."); return model;
Controller này lý 2 yêu (requests):
- yêu context root, là trang (home page)
- yêu trang viên (administrator page), trang này
Các annotation (chú thích) @Controller và @RequestMapping khai báo là controller có hai x lý HTTP GET Các chú thích này
Spring quét vì chúng tôi hình trong tin Spring application context file)
Thay vì hình XML trong web.xml bình chúng tôi mã Java hình Java có tên SpringWebAppInitializer dung code sau:
The `SpringWebAppInitializer` class implements the `WebApplicationInitializer` interface, allowing for the configuration of a Spring web application It imports necessary packages such as `ServletContext`, `ServletException`, and `DispatcherServlet` This setup facilitates the creation of an `AnnotationConfigWebApplicationContext`, which is essential for initializing the Spring framework within a servlet environment.
@Override public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext appContext new AnnotationConfigWebApplicationContext(); appContext.register(MvcConfig.class);
ServletRegistration.Dynamic dispatcher servletContext.addServlet("SpringDispatcher", new DispatcherServlet(appContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/");
Servlet 3.0+ container nào code trên mã XML sau trong web.xml:
SpringController
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/spring-mvc.xml
1
SpringController
Spring Security Filter là servlet các yêu vì ta nó khi
Thay vì XML, là mã Java Spring Security Filter:
17 package net.codejava.spring; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
* Spring Web MVC Security Java Config Demo Project
AbstractSecurityWebApplicationInitializer { public SecurityWebApplicationInitializer() { super(SecurityConfig.class);
Nó code XML sau trong web.xml:
springSecurityFilterChain
org.springframework.web.filter.DelegatingFilterProxy
springSecurityFilterChain
ý SecurityWebApplicationInitializer SecurityConfig.class hàm constructor cha constructor), này cho Spring Security tìm hình trong có tên SecurityConfig - mô bên
6.2.7 C u hình Authentication và Authorization cho ng d ng Spring MVC có tên SecurityConfig WebSecurityConfigurerAdapter code sau:
The article discusses the configuration of Spring Security in a Java application It highlights the use of annotations such as @Configuration and @EnableWebSecurity to set up security features Additionally, it mentions the importance of the AuthenticationManagerBuilder and HttpSecurity for managing authentication and securing web requests.
* Spring Web MVC Security Java Config Demo Project
* Configures authentication and authorization for the application
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth
withUser("admin").password("nimda").roles("ADMIN");
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests()
antMatchers("/admin**").access("hasRole('ADMIN')")
and().formLogin(); http.csrf().disable();
} này hình sau trong XML:
ý ta vô hóa CSRF vì trong này: http.csrf ().Disable(); yêu Spring Security liên /logout yêu HTTP GET Ta nên CSRF có pháp
6.2.8 Configuring Spring MVC Application Context
Thay vì XML, chúng tôi hình view resolvers trong Spring MVC cách code Java sau:
25 package net.codejava.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.view.InternalResourceViewResolver;
* Spring Web MVC Security Java Config Demo Project
@ComponentScan("net.codejava.spring") public class MvcConfig {
@Bean(name = "viewResolver") public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver;
} ta có hình bean InternalResourceViewResolver này phân logical view names thành các trang JSP lý Nó XML sau:
6.2.9 C u trúc toàn b Project cùng, trúc project này trong IDE Eclipse:
6.2.10 Ch y ki m tra ng d ng Spring Security m u lúc Spring MVC Security mà ta xây cho
Sau khi khai án trên Tomcat, hãy URL sau vào trình http://localhost:8080/SpringMVCSecurityJavaConfig
Trang (home page) vào hyperlink Go to Administrator Page, http://localhost:8080/SpringMVCSecurityJavaConfig/admin
Spring Security là một công cụ quan trọng giúp xác thực và phân quyền người dùng trong ứng dụng Để sử dụng Spring Security hiệu quả, bạn cần đảm bảo rằng tên đăng nhập và mật khẩu được nhập chính xác (ví dụ: admin và nimda) Sau khi xác thực thành công, người dùng sẽ được chuyển đến trang quản trị (administrator page) để quản lý hệ thống.
Bây hãy tra (logout functionality) vào liên Logout, Spring security filter /logout URL, làm phiên
(session) và trang (login page): ý thông báo màu xanh form và URL thay thành http://localhost:8080/ SpringMVCSecurityJavaConfig/login?logout
Spring security vô hóa phiên (session), hãy truy l trang http://localhost:8080/SpringMVCSecurityJavaConfig/admin chúng ta trang (login page).