Get HttpServletRequest from another server and set cookie into httpServletResponse and send back origin server was request come - spring-boot

I am using spring boot to build example SSO include guest Server at 8280 and authenticate server at 8080 , when access 8280, user will be redirect to server 8080 , login to authority. Now i want get all info of HttpServletRequest, and set cookie for guest server by httpServletResponse. How to i make it ?
I am using spring boot in both server
Here is my code
Configuration Filter Bean at 8280
#Configuration
public class FilterBeanRegistrationConfig {
#Value("${services.auth}")
private String authService;
#Bean
public FilterRegistrationBean <JwtFilter> jwtFilter() {
final FilterRegistrationBean<JwtFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new JwtFilter());
registrationBean.setInitParameters(Collections.singletonMap("services.auth", authService));
registrationBean.addUrlPatterns("/protected-resource");
return registrationBean;
}
} // END
application.propertie at 8280
services.auth=http://localhost:8080/login
server.port=8280
AuthenticatedUser.java
public class AuthenticatedUser {
private String email;
private String username;
private String password;
private String resourcesUrl;
private String token;
public AuthenticatedUser(){
}
public AuthenticatedUser(String email, String username, String password, String resourcesUrl, String token) {
this.email = email;
this.username = username;
this.password = password;
this.resourcesUrl = resourcesUrl;
this.token = token;
}
// getter and setter
} // end class
Controller at 8080
#Controller
public class LoginControllerFromVue {
private static final String jwtTokenCookieName = "JWT-TOKEN";
private static final String signingKey = "signingKey";
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
#Autowired
private UserService userService;
#RequestMapping("/")
public String home(){
return "redirect:/login";
}
#RequestMapping("/login")
public RedirectView method(HttpServletResponse httpServletResponse , HttpServletRequest httpServletRequest){
RedirectView redirectView = new RedirectView("http://localhost:4000/login?");
redirectView.setPropagateQueryParams(true);
return redirectView;
}
#PostMapping("/api/login")
public String loginUser(#RequestBody AuthenticatedUser theUser , HttpServletResponse httpServletResponse) {
if (theUser == null || userService.findUserByUsername(theUser.getUsername()) == null) {
return null;
}
if (! passwordEncoder.matches(theUser.getPassword(),userService.findUserByUsername(theUser.getUsername()).getPassword())) {
return null;
}
String token = JwtUtil.generateToken(signingKey, theUser.getUsername());
CookieUtil.create(httpServletResponse, jwtTokenCookieName, token, false, -1, httpServletRequest.getServerName());
return "redirect:"+theUser.getResourcesUrl();
}
}
Config Axios in Vuejs
import axios from "axios";
export default axios.create({
baseURL: "http://localhost:8080/api",
headers: {
"Content-type": "application/json",
}
});
Login.vue
<template>
<div class="submitform">
<form class="form" #submit.prevent="loginUser">
<div v-if="!submitted" >
<div class="form-group">
<label for="name">Username</label>
<input type="text" class="form-control" id="username" required v-model="user.username" name="username">
</div>
<div class="form-group">
<label for="age">Password</label>
<input type="password" class="form-control" id="password" required v-model="user.password" name="password">
</div>
<div id="error">
<span v-if="error">Username or Password invalid</span>
</div>
<hr>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
<hr>
<button v-on:click="getPathResources" class="btn btn-warning">Get Resources</button>
|
<button v-on:click="authorisedRedirect" class="btn btn-warning">Appcept Redirect</button>
</div>
</template>
<script>
import http from "../http-common";
export default {
name: "login-User",
data() {
return {
user: {
id: 0,
email : "",
username: "",
password: "",
// resourcesUrl:location.host
resourcesUrl : this.$route.query.redirect
},
error: false,
submitted: false
};
},
methods: {
loginUser() {
var data = {
username: this.user.username,
password: this.user.password,
// resourcesUrl:location.host
resourcesUrl : this.$route.query.redirect
};
http
.post("/login", data)
.then(model => {
// this.user.id = response.data.id;
console.log(model.data);
if (model.data !== "") {
this.$router.push('/authorised');
this.submitted = true;
} else {
this.submitted = false;
this.user.username = "";
this.user.password = "";
this.error = true;
}
})
.catch(e => {
console.log(e);
});
},
getPathResources(){
// var currentServername = location.hostname;
var currentHost = location.host;
var currentUrl = location.pathname;
console.log(currentHost + currentUrl);
console.log(this.$route.query.redirect);
},
authorisedRedirect(){
window.open("http://localhost:8280/protected-resource", "_blank");
}
}
};
</script>
<style>
.submitform {
max-width: 300px;
margin: auto;
}
.form {
background-color: rgb(245, 245, 245)
}
#error {
background-color: beige;
border-radius: 3px;
}
</style>
When I log in with a valid account, I still cannot transfer to 8280 and still remain in the login page, it seems that setting the cookie to the 8280 server has not been successfully implemented by httpservletResponse. how to i setup it or any other solution to it work , if anyone know where's this problem please tell he how to sovle it and i appreciate!!!

Related

Problem with controller return statement not performed (about redirect)

I'm working on a side project and it's been delayed for several days. When I run my code, I always can't run it from the "return redirect:/" part of the controller.
The result I expected is that I think of moving from sentence "return redirect:/" to another page, but everything seems fine inside, but only sentence "return redirect:/" is not performed.
I am using Mysql, SpringBoot, JPA, Spring Data Jpa, Lombok. What is the problem?
This is View to receive email and password.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel = "stylesheet" href ="/css/sample.css">
<link href="https://getbootstrap.com/docs/5.2/assets/css/docs.css" rel="stylesheet">
<link href="/css/font.css" rel = "stylesheet">
<link href="/css/navbar.css" rel = "stylesheet">
<title>loginpage</title>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
function functionclick() {
let email = document.getElementById('exampleDropdownFormEmail1').value;
let password = document.getElementById('exampleDropdownFormPassword1').value;
if (email == "" || password == "") {
alert("회원 정보를 입력하세요");
history.back();
} else{
const url = new URL("/trylogin",location);
url.searchParams.append('email',email);
url.searchParams.append('password',password);
location = url;
}
}
</script>
</head>
<body class="p-3 m-0 border-0 bd-example">
<!-- Example Code -->
<div class="dropdown-menu">
<form class="px-4 py-3" method="get" action="login">
<div class="mb-3">
<label for="exampleDropdownFormEmail1" class="form-label">이메일을 입력하세요</label>
<input type="text" class="form-control" id="exampleDropdownFormEmail1" placeholder="email#example.com" name = "email">
</div>
<div class="mb-3">
<label for="exampleDropdownFormPassword1" class="form-label">비밀번호를 입력하세요.</label>
<input type="password" class="form-control" id="exampleDropdownFormPassword1" placeholder="Password" name = "password">
</div>
<div class="mb-3">
<div class="form-check">
<input type="checkbox" class="form-check-input" id="dropdownCheck">
<label class="form-check-label" for="dropdownCheck">
비밀번호 기억하기
</label>
</div>
</div>
<button type="submit" class="btn btn-primary" ONCLICK="functionclick()">확인</button>
</form>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="http://localhost:8080/signup">회원가입 하기</a>
<a class="dropdown-item" href="http://localhost:8080/forgotpassword">비밀번호 찾기</a>
</div>
<!-- End Example Code -->
</body>
</html>
This is LoginController
#Controller
public class LoginController {
#Autowired
private
UserService userService;
#GetMapping("/trylogin")
public String login(LoginDto loginDto) {
try {
if(userService.login(loginDto).isPresent()) {
return "redirect:/loginSuccess";
}
} catch (Exception e) {
e.printStackTrace();
return "redirect:/loginFailed";
}
return "redirect:/loginFailed";
}
#GetMapping("/loginSuccess")
public String loginSuccess() {
return "login_success";
}
#GetMapping("/loginFailed")
public String loginFailed() {
return "login_failed";
}
}
It is a service layer and the Repository used spring data jpa.
#Service
#RequiredArgsConstructor
#Getter
public class UserService {
#Autowired
private UsersRepository usersRepository;
#Transactional
public Optional<Users> login(LoginDto loginDto) throws Exception{
return usersRepository.findByEmailAndPassword(loginDto.getEmail(), loginDto.getPassword());
}
}
This is the Users entity to perform the query.
#Entity
#Getter
#NoArgsConstructor
#AllArgsConstructor
#Table(uniqueConstraints = {#UniqueConstraint(columnNames = {"ssn","phone_number"})})
public class Users {
#Column(name = "email", length = 40, updatable = false, nullable = false)
#Id
private String email;
#Column(name = "password", length = 20, nullable = false)
private String password;
#Column(name = "name", length = 25, nullable = false)
private String name;
#Column(name = "phone_number", length = 12, nullable = false)
private String phoneNumber;
#Column(name = "ssn", length = 13, nullable = false, updatable = false)
private String ssn;
#Embedded
private Address address;
#Column(name = "point")
private Long point;
#OneToMany(mappedBy = "postedUser")
private List<PostInfo> uploadedPost = new ArrayList<>();
#OneToMany(mappedBy = "userId")
private List<PointHistory> pointHistories = new ArrayList<>();
#Embedded
private Dates dates;
public Users(UserInfoDto userInfoDto){
this.setEmail(userInfoDto.getEmail());
this.setPassword(userInfoDto.getPassword());
this.setPhoneNumber(userInfoDto.getPhone_number());
this.setSsn(userInfoDto.getSsn());
this.setPoint(0L);
this.setName(userInfoDto.getName());
Address address = new Address(
userInfoDto.getCity_name(),
userInfoDto.getTown_name(),
userInfoDto.getStreet_name(),
userInfoDto.getZip_code(),
userInfoDto.getDetails()
);
this.setAddress(address);
List<PostInfo> postInfoList = new ArrayList<>();
List<PointHistory> pointHistoryList = new ArrayList<>();
this.setUploadedPost(postInfoList);
this.setPointHistories(pointHistoryList);
Dates dates = new Dates(LocalDateTime.now(), LocalDateTime.now());
this.setDates(dates);
}
public void setEmail(String id) {
this.email = id;
}
public void setPassword(String password) {
this.password = password;
}
public void setName(String name) {
this.name = name;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public void setAddress(Address address) {
this.address = address;
}
public void setPoint(Long point) {
this.point = point;
}
public void setUploadedPost(List<PostInfo> uploadedPost) {
this.uploadedPost = uploadedPost;
}
public void setPointHistories(List<PointHistory> pointHistories) {
this.pointHistories = pointHistories;
}
public void setDates(Dates dates) {
this.dates = dates;
}
}
This is LoginDto (To transfer to the controller)
#Getter
#Setter
#AllArgsConstructor
public class LoginDto {
private String email;
private String password;
}
The page for redirection.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Success</title>
<script type = "text/javascript">
alert("로그인 성공");
location.href = "/";
</script>
</head>
<body>
</body>
</html>

Spingboot Thymeleaf form passes null values into the controller

could someone help me figure out why it is passing null values instead of actual names? The form has a input textbox for last name and fistname but I would only get null values when I access "authorRequest.getLastName() or authorRequest.getFirstName().
Controller:
#Controller
public class AuthorController {
private BooktownService __authorService = BooktownServiceFactory.getInstance();
private Model mod;
private String msg = "";
first endpoint, return a collection of authors
#GetMapping("/booktown/list")
public List<Author> returnAuthors() {
return __authorService.getAuthors();
}
#GetMapping("/booktown/list")
public String returnAuthors(Model model) {
this.mod = model;
Author auth= new Author();
List<Author> auths = __authorService.getAuthors();
if(msg == ""){
msg = "Listing page for Authors";
}
mod.addAttribute("authors", auths);
mod.addAttribute("authorRequest", auth);
mod.addAttribute("msg",msg);
return "list_form";
}
// third endpoint, create an Author via POST
#PostMapping("/booktown/add")
public String createAuthor(#ModelAttribute("authorRequest") Author authorRequest) {
__authorService.createAuthor(authorRequest.getLastName(), authorRequest.getFirstName());
msg = "Added Author" + authorRequest.getFirstName() + " " + authorRequest.getLastName();
return "redirect:/booktown/list";
}
// Sixth endpoint: DELETE
#GetMapping("/booktown/delete")
public String deleteAuthor(#RequestParam Integer id) {
// returns a boolean
__authorService.deleteAuthor(id);
msg = "Deleted Author " + id;
System.out.println("deleted");
return "redirect:/booktown/list";
}
}
Html:
<form action="#" th:action="#{/booktown/add}" th:object="${authorRequest}" method="post">
<p>Last name: <input type="text" th:field="*{__lastName}" /></p>
<p>First name: <input type="text" th:field="*{__firstName}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
Author.java:
package com.booktown.booktownservice;
public class Author {
public Author(){}
public Author(int id, String lname, String fname) {
__id = id;
__lastName = lname;
__firstName = fname;
}
public int getAuthorID() {
return __id;
}
public String getLastName() {
return __lastName;
}
public String getFirstName() {
return __firstName;
}
public int get__id() {
return __id;
}
public String get__lastName() {
return __lastName;
}
public String get__firstName() {
return __firstName;
}
private int __id;
private String __lastName;
private String __firstName;
}

Cannot update my form in spring boot

My model is
#Entity
#Table(name = "sls_notifications")
public class SLSNotification {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(length = 11)
private Integer snumber;
#JsonFormat(pattern="yyyy-MM-dd")
#Column(nullable = false)
private Date date = new Date();
#Column(length = 8)
private String cusOffice;
#Column(length = 1)
private String cusSerial;
#Column(length = 50)
private String cusDecNo;
#JsonFormat(pattern="yyyy-MM-dd")
private Date cusDate;
#Column(length = 300)
private String manufacturer;
#Column(length = 300)
private String exporterAddress;
#Column(length = 20)
private String importerVAT;
#NotEmpty
#Column(length = 20, nullable = false)
private String declarantVAT;
private String declarantDetails;
private String vessel;
private String blNo;
private String loadingPort;
private String tradingCountry;
private String countryOrigin;
private String invoiceNo;
#JsonFormat(pattern="yyyy-MM-dd")
private Date invoiceDate;
private Double invoiceValue;
private String uom;
private Double totalQty;
private String marksNumber;
private String goodsDesc;
private String purpose;
private String hsCode;
private String issuerQltyCert;
private String qltyCertifacateNo;
private String slsNo;
private String invoiceLoc;
private String blLoc;
private String packlistLoc;
private String qcLoc;
private String otherLoc;
private String accRep;
private String accRepLoc;
#NotEmpty
#Column(length = 255, nullable = false)
private String status = "PENDING";
private String userId;
private String slsiUnit;
private String importerDetails;
private String productDesc;
private String certRefNo;
#JsonFormat(pattern="yyyy-MM-dd")
private Date blDate;
private String loadCountry;
}
My repositary is
public interface SLSNotificationRepository extends
CrudRepository<SLSNotification, Integer> {
#Override
SLSNotification save(SLSNotification slsNotification);
#Override
SLSNotification findOne(Integer snumber);
#Override
long count();
#Override
void delete(Integer integer);
#Override
void delete(SLSNotification slsNotification);
#Override
void delete(Iterable<? extends SLSNotification> iterable);
#Override
List<SLSNotification> findAll();
#Query("select a from SLSNotification a where a.slsiUnit in :unitList")
List<SLSNotification> getApplicationsByUnit(#Param("unitList")List <String> unitList);
#Query("select a from SLSNotification a where a.userId = :userId")
List<SLSNotification> getApplicationsByUserId(#Param("userId")String userId);
#Query("select a from SLSNotification a where a.slsNo = :slsNo")
SLSNotification getApplicationBySLSNumber(#Param("slsNo") String slsNo);
#Query("select a from SLSNotification a where a.importerVAT = :importerVAT group by slsNo")
List<SLSNotification> getproductByUserId(#Param("importerVAT")String importerVAT);
}
My services is
package lk.slsi.services;
import lk.slsi.domain.SLSNotification;
import lk.slsi.repository.SLSIWorkflowRepository;
import lk.slsi.repository.SLSNotificationRepository;
import lk.slsi.storage.FileSystemStorageService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import org.springframework.data.repository.query.Param;
#Service
#Scope("session")
public class ApplicationServices {
private static final Logger serviceLogger = LogManager.getLogger(ApplicationServices.class);
#Autowired
private SLSNotificationRepository slsNotificationRepository;
#Autowired
private WorkflowServices workflowServices;
#Autowired
private FileSystemStorageService storageService;
#Autowired
private FileUploadRollBack rollBack;
#Value("${slsi.filePaths.packlist}")
private String packlist;
#Value("${slsi.filePaths.qc}")
private String qc;
#Value("${slsi.filePaths.bl}")
private String bl;
#Value("${slsi.filePaths.invoice}")
private String invoice;
#Value("${slsi.filePaths.otherDoc}")
private String otherDoc;
#Value("${slsi.filePaths.accept}")
private String accept;
public boolean updateOrAddApplication(SLSNotification slsNotification,
MultipartFile attachInv,
MultipartFile attachBL,
MultipartFile attachPackList,
MultipartFile attachQc,
MultipartFile attachOther,
MultipartFile fileAccRep) {
serviceLogger.info("Staring adding/updating the SLS Notification data . data : [{}]", slsNotification);
try {
if (!attachInv.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", attachInv.getOriginalFilename());
slsNotification.setInvoiceLoc(storageService.store(attachInv, invoice));
rollBack.addRollbackPoint(invoice,slsNotification.getInvoiceLoc());
}
if (!attachBL.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", attachBL.getOriginalFilename());
slsNotification.setBlLoc(storageService.store(attachBL, bl));
rollBack.addRollbackPoint(bl,slsNotification.getBlLoc());
}
if (!attachPackList.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", attachPackList.getOriginalFilename());
slsNotification.setPacklistLoc(storageService.store(attachPackList, packlist));
rollBack.addRollbackPoint(packlist,slsNotification.getPacklistLoc());
}
if (!attachQc.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", attachQc.getOriginalFilename());
slsNotification.setQcLoc(storageService.store(attachQc, qc));
rollBack.addRollbackPoint(qc,slsNotification.getQcLoc());
}
if (!attachOther.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", attachOther.getOriginalFilename());
slsNotification.setOtherLoc(storageService.store(attachOther, otherDoc));
rollBack.addRollbackPoint(otherDoc,slsNotification.getOtherLoc());
}
if (!fileAccRep.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", fileAccRep.getOriginalFilename());
slsNotification.setAccRepLoc(storageService.store(fileAccRep, accept));
rollBack.addRollbackPoint(accept,slsNotification.getAccRepLoc());
}
serviceLogger.info("Saving data in the database. [{}]", slsNotification);
slsNotificationRepository.save(slsNotification);
workflowServices.initWorkflow(slsNotification.getSnumber());
return true;
} catch (Exception e) {
serviceLogger.error("Error occurred while saving SLS Common data . [{}]", e);
rollBack.rollback();
return false;
}
}
public boolean update(SLSNotification slsNotification) {
serviceLogger.info("Staring adding/updating the SLS Notification data . data : [{}]", slsNotification);
try {
serviceLogger.info("Saving data in the database. [{}]", slsNotification);
slsNotificationRepository.save(slsNotification);
return true;
} catch (Exception e) {
serviceLogger.error("Error occurred while saving SLS Common data . [{}]", e);
rollBack.rollback();
return false;
}
}
public List<SLSNotification> getAll(){
return slsNotificationRepository.findAll();
}
public SLSNotification getSLSNotificationBySerialNumnber(Integer serialNumber) {
return slsNotificationRepository.findOne(serialNumber);
}
public List<SLSNotification> getApplicationsByUserId(String userId){
return slsNotificationRepository.getApplicationsByUserId(userId);
}
public List<SLSNotification> getproductByUserId(String importerVAT){
return slsNotificationRepository.getproductByUserId(importerVAT);
}
public List<SLSNotification> getApplicationsByUnit(List <String> unitList){
return slsNotificationRepository.getApplicationsByUnit(unitList);
}
public SLSNotification getApplicationById(Integer snumber){
return slsNotificationRepository.findOne(snumber);
}
public Resource getFile(String filename){
return storageService.getFileResource(filename);
}
}
My controller is
package lk.slsi.controller;
import lk.slsi.domain.SLSNotification;
import lk.slsi.exceptions.ProductWithSameSerialExistsException;
import lk.slsi.security.domain.AuthenticatedUser;
import lk.slsi.services.ApplicationServices;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.util.SimpleFileResolver;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import static org.hibernate.annotations.common.util.impl.LoggerFactory.logger;
/**
* Created by ignotus on 2/18/2017.
*/
#Controller
#RequestMapping(path = "/")
#Scope("session")
public class ApplicationUrlMapController {
private static final Logger slsiLogger = LogManager.getLogger(ApplicationUrlMapController.class);
private static final String MESSAGE_KEY = "message";
private static final String APPLICATION_REDIRECT = "redirect:/application";
#Autowired
private ServletContext servletContext;
#Autowired
private ApplicationServices applicationServices;
#Autowired
private ProductServices productServices;
private MailService mailservice;
#Autowired
private ManufacturerServices manufacturerServices;
#Autowired
private WorkflowServices workflowServices;
#Value("${slsi.reportData}")
private String reportDataLocation;
#RequestMapping(path = "/application")
public String viewApplication(Model model) {
model.addAttribute("manu", manufacturerServices.getManufacturerListbyStatus());
model.addAttribute("edit", true);
return "application";
}
#RequestMapping(path = "/EditApplication/{snumber}",method = RequestMethod.POST)
public String addApplication(#PathVariable("snumber") #ModelAttribute("snumber") String snumber, Model model) {
model.addAttribute("app", applicationServices.getApplicationById(Integer.parseInt(snumber)));
model.addAttribute("manu", manufacturerServices.getManufacturerListbyStatus());
model.addAttribute("edit", true);
return "editApplication";
}
#RequestMapping(path = "/executeApplication", method = RequestMethod.POST)
public String registerApplication(#ModelAttribute("applicationForm") #Valid SLSNotification application,
BindingResult result,
HttpSession session,
#RequestParam("attachInv") MultipartFile attachInv,
#RequestParam("attachBL") MultipartFile attachBL,
#RequestParam("attachPackList") MultipartFile attachPackList,
#RequestParam("attachQc") MultipartFile attachQc,
#RequestParam("attachOther") MultipartFile attachOther,
#RequestParam("fileAccRep") MultipartFile fileAccRep) {
if (result.hasErrors()) {
session.setAttribute(MESSAGE_KEY, "application validation failed");
return "redirect:/application?" + MESSAGE_KEY;
}
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal != null && principal instanceof AuthenticatedUser) {
AuthenticatedUser auth = (AuthenticatedUser) principal;
application.setUserId(String.valueOf(auth.getUserId()));
}
//Setting the slsiUnit of the notification
// String sls = application.getSlsNo();
// Product p = productServices.getProductBySlsNo(Integer.parseInt(sls));
// int slsUnitNumber =p.getSlsiUnit();
//
// application.setSlsiUnit("UNIT"+ slsUnitNumber);
slsiLogger.info("Executing application update. application : [{}]", application);
if (applicationServices.updateOrAddApplication(application,
attachInv, attachBL, attachPackList, attachQc, attachOther, fileAccRep)) {
session.setAttribute(MESSAGE_KEY, "application update successful!");
} else {
session.setAttribute(MESSAGE_KEY, "application update was not successful");
}
return "redirect:/applicationManage?" + MESSAGE_KEY;
}
#RequestMapping(path = "/updateUserApplication", method = RequestMethod.POST)
public String updateApplication(#ModelAttribute("updateapplicationForm") #Valid SLSNotification slsNotification,
BindingResult result,
HttpSession session) {
slsiLogger.info("Request received to register new product. [{}]", slsNotification);
if (result.hasErrors()) {
slsiLogger.error("Rejecting the request due to binding errors, [{}]", result.getFieldErrors());
return "redirect:/applicationManage?";
}
if (applicationServices.update(slsNotification)) {
slsiLogger.info("Product registered successfully");
session.setAttribute(MESSAGE_KEY, "Product registered successfully");
} else {
session.setAttribute(MESSAGE_KEY, "Error occurred while registering the product");
}
return "redirect:/applicationManage?" + MESSAGE_KEY;
}
#RequestMapping(path = "/applicationManage")
public String viewApplicationPage(Model model) {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
long userId = 0;
String agency = "";
String units = "";
String jobroles = "";
if (principal != null && principal instanceof AuthenticatedUser) {
AuthenticatedUser auth = (AuthenticatedUser) principal;
userId = auth.getUserId();
agency = auth.getAgency();
if (agency.equalsIgnoreCase("slsi")) {
System.out.println("Agency of the User is " + agency);
model.addAttribute("applications", applicationServices.getApplicationsByUnit(auth.getJobUnits()));
} else {
model.addAttribute("applications", applicationServices.getApplicationsByUserId(String.valueOf(userId)));
}
}
return "applicationManage";
}
#RequestMapping(path = "/applicationView", method = RequestMethod.POST)
public String viewApplicationUpdatePage(#ModelAttribute("appId") String appId, Model model) {
model.addAttribute("application", applicationServices.getApplicationById(Integer.parseInt(appId)));
return "view";
}
#RequestMapping(value = "/download/{fileName}*", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<Resource> downLoadFile(#PathVariable("fileName") String filename) {
Resource file = applicationServices.getFile(filename);
return ResponseEntity
.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
.body(file);
}
#RequestMapping(path = "/viewPdf/{snumber}", method = RequestMethod.POST)
public ModelAndView getPDFReport(#PathVariable("snumber") String snumber) {
File reportsDir = Paths.get(servletContext.getRealPath(reportDataLocation)).toFile();
if (!reportsDir.exists()) {
throw ProductWithSameSerialExistsException.getInstance();
}
JRDataSource dataSource = new JRBeanCollectionDataSource(Arrays.asList(applicationServices.getApplicationById(Integer.parseInt(snumber))));
Map<String, Object> parameterMap = new HashMap<>();
parameterMap.put("datasource", dataSource);
parameterMap.put("JasperCustomSubReportDatasource", dataSource);
parameterMap.put(JRParameter.REPORT_FILE_RESOLVER, new SimpleFileResolver(reportsDir));
System.out.println(dataSource);
return new ModelAndView("pdfReport", parameterMap);
}
}
My JSP IS (EDIT JSP).I want to edit some selected fields only in my form.So i creaded new JSP for edit application,
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Application</title>
<meta charset="UTF-8">
<%#include file="template/styles.jsp" %>
<script src="${pageContext.request.contextPath}/view/public/js/jquery.min.js"></script>
<script src="${pageContext.request.contextPath}/view/public/js/jquery-ui.min.js"></script>
</head>
<sec:authorize/>
<body>
<div class="container">
<!-- Start of common header -->
<div class="row headerRow1">
<div class="col-md-12">
<jsp:include page="template/banner.jsp"/>
</div>
</div>
<div class="row">
<div class="authheader">
<%#include file="template/message.jsp" %>
</div>
</div>
<div class="col-sm-12">
<div class="row">
<div class="col-lg-12">
<div class="well lead">UPDATE NOTIFICATION FORM - SLSI ENTRY NO ${app.snumber}</div>
</div>
</div>
<div id="" style="color: red">Use Google Chrome Web browser for update your Application.</div>
<div class="row">
<!-- Start of common navigation -->
<form:form name="updateapplicationForm" id="updateapplicationForm" action="updateUserApplication" commandName="app" method="post" enctype="application/x-www-form-urlencoded">
<c:if test="${edit}">
<input type="text" id="snumber" name="snumber" value="${app.snumber}"/>
</c:if>
<div class="panel panel-default">
<div class="panel-body" >
<div class="row">
<label id="aaa" for="manufacturer" class="col-sm-2 col-form-label col-form-label-lg">Manufacturer Name &
Address <div class="req" > *</div></label>
<label id="bbb" for="manufacturer" class="col-sm-2 col-form-label col-form-label-lg">Manufacturer Name <div class="req" > *</div></label>
<div id="">
<div class="col-sm-4">
<div class="checkbox">
<label><input type="checkbox" value="" id="registered">Registered Manufacturer in SLSI</label>
</div>
<div id="regManu">
<select id="companies">
<c:forEach items="${manu}" var="com">
<option value="${com.manufacturerName}">${com.manufacturerName}</option>
</c:forEach>
</select>
</div>
<textarea name="manufacturer" class="form-control form-control-lg"
id="manufacturer"
placeholder="Enter the name & Address. Press Enter at the end of each line"
aria-descrribedby="exportertHelp" data-error="Name & Address is required!"
required rows="4" maxlength="254"></textarea>
<input type="hidden" id="manufacture" name="manufacture" value="${app.manufacturer}"/>
<div class="help-block with-errors"></div>
</div>
<label for="exporterAddress" class="col-sm-2 col-form-label col-form-label-lg">Exporter Name &
Address <div class="req"> *</div></label>
<div class="col-sm-4">
<textarea name="exporterAddress" class="form-control form-control-lg" id="exporterAddress"
placeholder="Enter the name & Address. Press Enter at the end of each line"
aria-descrribedby="exportertHelp" data-error="Name & Address is required!"
required rows="5" maxlength="254"></textarea><br/><br/>
<input type="hidden" id="exp" name="exp" value="${app.exporterAddress}"/>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<br/> <label for="importerVAT" class="col-sm-2 col-form-label col-form-label-lg">Importer VAT <div class="req"> *</div></label>
<div class="col-sm-4">
<input class="form-control" type="text" name="importerVAT" id="importerVAT"
aria-describedby="importerVATHelp" placeholder="Ex : 174625588-7000 (White spaces not allowed)"
data-error="VAT number is required!" onkeyup="lettersOnly(this)" required value="${app.importerVAT}">
<div class="help-block with-errors"></div>
</div>
<label for="declarantVAT" class="col-sm-2 col-form-label col-form-label-lg">Declarant VAT <div class="req"> *</div></label>
<div class="col-sm-4">
<input class="form-control" name="declarantVAT" type="text" id="declarantVAT"
aria-describedby="declarantVATHelp" placeholder="Ex : 174625588-7000 (White spaces not allowed)"
data-error="VAT number is required!" onkeyup="lettersOnly(this)" required value="${app.declarantVAT}">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<button type="submit" id="submit" class="btn btn-success pull-right">SAVE CHANGES</button>
</div>
<div class="col-sm-3" id="msg">
<% if (message.startsWith("Registration")) {
out.print("<script>alert('" + message + "');</script>");
request.getSession().setAttribute("regMessage", "");
}
%>
</div>
</div>
</form:form>
</div>
<jsp:include page="template/footer.jsp"/>
</div>
</body>
</html>
Data retrive succecfully to the edit jsp..but when i hit sava button it will get the error..I want to update application...
Please help me.
error is
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Nov 07 12:32:42 IST 2017
There was an unexpected error (type=Internal Server Error, status=500).
For input string: "updateUserApplication"
in my netbeans console show this error
java.lang.NumberFormatException: For input string: "updateUserApplication"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:1.8.0_121]
at java.lang.Integer.parseInt(Integer.java:580) ~[na:1.8.0_121]
at java.lang.Integer.parseInt(Integer.java:615) ~[na:1.8.0_121]
at lk.slsi.controller.ApplicationUrlMapController.addApplication(ApplicationUrlMapController.java:81) ~[classes/:na]
at sun.reflect.GeneratedMethodAccessor842.invoke(Unknown Source) ~[na:na]
From the controller code, the API endpoint /slsi_mof/EditApplication/{snumber} is getting invoked. It is because you are using relative URL in form action. Update the form action to /slsi_mof/updateUserApplication and it should work

Submit a List from a form generated with JavaScript with a Spring controller [duplicate]

This question already has answers here:
Passing a list generated with Javascript to a Spring controller
(3 answers)
Closed 5 years ago.
I'm building an app with Spring Boot, the MVC pattern, and Thymeleaf as template engine. I have a form that generates a list with JavaScript, and a controller with a #ModelAttribute expecting a list, to be saved into the database.
At the JavaScript side I collect the items with this array:
groupList = [];
groupList.push(inputValue);
function getGroupList(){
return groupList;
}
In the html I'm trying to assign the array value to a hidden input field:
<input type="hidden" class="invisible" id="groupList" th:field="*{groupList}"/>
With this inline function:
<script th:inline="javascript" type="text/javascript">
$(function() {
var groupListCollected = getGroupList();
$("#groupList").val(groupListCollected);
});
</script>
My problem at this point, is that I don't find the way to collect the array, and pass it to the Controller as a list.
This is the value that the console shows, for the input field:
<input type="hidden" class="invisible" id="groupList" name="groupList"
value="[object HTMLInputElement]">
Any advice to face this issue, would be much appreciated. Thanks in advance.
You can proceed like this :
Create a Model, for exemple:
public class User {
private String username;
public User() {
}
public User(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
Create a FormModel:
public class FormUsers {
private List<User> listUsers;
public FormUsers(List<User> listUsers) {
this.listUsers = listUsers;
}
public FormUsers() {
}
public List<User> getListUsers() {
return listUsers;
}
public void setListUsers(List<User> listUsers) {
this.listUsers = listUsers;
}
#Override
public String toString() {
return "FormUsers{" + "listUsers=" + listUsers + '}';
}
}
in your controller (Get and Post) :
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello(ModelMap model) {
FormUsers formUsers = new FormUsers();
List<User> list = new ArrayList<>();
list.add(new User("Wassim"));
formUsers.setListUsers(list);
logger.debug("--> " + formUsers.toString());
model.addAttribute("formUsers", formUsers);
return "hello";
}
#RequestMapping(value = "/hello", method = RequestMethod.POST)
public String helloPost(#ModelAttribute FormUsers formUsers, ModelMap model) {
logger.debug("Get List of new users --> " + formUsers.toString());
return "hello";
}
In my view (hello.html) : for listing all users :
<button id="addAction">ADD</button>
<form action="#" th:action="#{/hello}" th:object="${formUsers}" method="post">
<ul id="myUl">
<input type="text" th:field="*{listUsers[0].username}" />
</ul>
<input type="submit" value="Submit" />
</form>
Now if I want to add another user with javascript when I clic in the button 'ADD, I will append() a new 'li' element containing the new user :
<script type="text/javascript">
$(document).ready(function () {
console.log("ready!");
$("#addAction").click(function () {
console.log("FUNCTION");
$("#myUl").append('<li><input id="listUsers1.username" name="listUsers[1].username" value="Rafik" type="text"/></li>');
});
});
</script>
When I Submit, I will get a list with 2 User : 'Wassim' & 'Rafik'.
You can manage this exemple (also the index of the list must managed properly) to append your list with the needed DATA.

After accepting data with #requestbody, I want to return message or realize webpage-jump

Controller:
#RequestMapping(value="receive", method=RequestMethod.POST, consumes="application/json")
#ResponseBody
public RegInfo receiveData(#RequestBody RegInfo info){
String reg_check = regInfoService.checkRegInfo(info);
......
}
RegInfo:
public class RegInfo {
private String account;
private String passwords;
private String realname;
private String phonenumber;
private String sex;
private String mailname;
.......}
register.jsp:
$("#sub").click(function(){
var m = {
"account": $("#_account").val(),
"passwords": $("#_pass").val(),
"realname": $("#real_name").val(),
"phonenumber": $("#phone_number").val(),
"sex": $("input:checked").val(),
"mailname": $("#mail_name").val()
};
$.ajax({
type:"POST",
async : false,
url:"/demo/user/receive",
dataType:"json",
contentType:"application/json; charset=utf-8",
data:JSON.stringify(m),
success:function(data){
alert("ok");
alert(data.realname);
},
erroe:function(data){
alert("保存失败 ")
}
})
});
Now I want to check RegInfo in the controller. If the result of check is legal, I want to jump to other webpage like login.jsp and if it is illegal, I want to return some message and show the message in register.jsp. How can I realize it?
complete Controller:
#Controller
#RequestMapping("/user")
public class LoginController {
#Autowired
private UserService userService;
#Autowired
private RegInfoService regInfoService;
#RequestMapping("/login")
public String homePage(){
return "user/login";
}
#RequestMapping("/loginin")
public String toLogin(#ModelAttribute("user")User user){
String u = userService.loginCheck(user);
System.out.println(u);
if(u == "success"){
return "user/success";
}
else{
return "user/login";
}
}
#RequestMapping("/register")
public String toRegister(){
return "user/register";
}
#RequestMapping("/success")
public String toSuccess(){
return "user/success";
}
#RequestMapping(value="receive", method=RequestMethod.POST, consumes="application/json")
#ResponseBody
public RegInfo receiveData(#RequestBody RegInfo info){
String reg_check = regInfoService.checkRegInfo(info);
System.out.println(reg_check);
System.out.println(info);
System.out.println(info.getRealname());
return info;
}
}
I want to jump to other webpage like login.jsp and if it is illegal, I
want to return some message and show the message in register.jsp. How
can I realize it?
Simple, in your AJAX success handler redirect with URL parameters like:
$.ajax({
type:"POST",
async : false,
url:"/demo/user/receive",
dataType:"json",
contentType:"application/json; charset=utf-8",
data:JSON.stringify(m),
success:function(data){
alert("ok");
alert(data.realname);
if (data.realname != undefined || data.realname!= null) {
window.location = '/login?realname=' + data.realname;
}
},
erroe:function(data){
alert("保存失败 ")
}
});
EDITS:
based on your comment the controller method will look like:
#Controller
#RequestMapping("/user")
public class LoginController {
#RequestMapping("/login")
public String homePage(Mode model, #RequestParam(value="realname",required=false)String realName){
if(realName!=null && (!realName.trim().isEmpty())){
model.addAttribute("regSuccessUser",realName);
}
return "user/login";
}
}
and redirect statement will look like:
window.location = '/user/login?realname=' + data.realname;
Note: URL start with contextPath to avoid 404 problems
I test as follows:
<input type="button" value="test" onClick="newpage()">
function newpage(){
window.location="/demo/user/login";}
then it jump to login.jsp successfully.In the ajax,it had run to "window.location" but didn't jump.It looks so strange.
Final solution:
error:
<input type="submit" id="sub" value="save" >
true:
<input type="button" id="sub" value="save" >
Form is submitted twice.

Resources