I'm currently learning JSP/Servelets. The following is code containing 2 JSP pages and a servlet, which works as follows:
JSP #1 requests user info, & passes it into a servlet.
The servlet Instantiates a JavaBean class, and passes it to the 2nd JSP, using the Session Object.
The 2nd JSP then displays the info that th user entered in the 1st JSP; the user can then hit the Return button to return to the 1st JSP.
My Question is: I've read in various Tutorials (notably Murach's JSP, which this code is based on) that if the Javabean attributes are passed to the session object rather than the request object, the JavaBean's values should be maintained throughout the session. However when I return to the first page, the JB fields are empty. Am i doing anything wrong? I would appreciate any help!
The following is the code:
1st JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Email Application</title>
</head>
<body>
<h1>Join our Email list</h1>
<p>To join our email list, enter your name and email address below.<br>
Then, click on the Submit button</p>
<form action="addToEmailList" method="post">
<jsp:useBean id="user" scope="session" class="business.User"/>
<table cellspacing="5" border="0">
<tr>
<td align="right">First name:</td>
<td>
<input type="text" name="firstName"
value = "<jsp:getProperty name="user" property="firstName"/>">
</td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><input type="text" name="lastName"
value = "<jsp:getProperty name="user" property="lastName"/>">
</td>
</tr>
<tr>
<td align="right">Email address:</td>
<td><input type="text" name="emailAddress"
value = "<jsp:getProperty name="user" property="emailAddress"/>">
</td>
</tr>
<tr>
<td>I'm interested in these types of music:</td>
<td><select name="music" multiple>
<option value="rock">Rock</option>
<option value="country">Country</option>
<option value="bluegrass">Bluegrass</option>
<option value="folkMusic">Folk Music</option>
</select>
</td>
</tr>
<tr>
<td ></td>
<td><input type="submit" name="Submit"></td>
</tr>
</table>
</form>
</body>
Servlet:
public class AddToEmailListServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
private HttpServletResponse response;
private String firstName;
private String lastName;
private String emailAddress;
private String[] musicTypes;
private Music music;
private User user;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
this.request = request;
this.response = response;
setInstanceVariables();
writeDataToFile();
forwardResponseToJSPpage();
System.err.println("Hello!");
}
private void setInstanceVariables()
{
this.firstName = getFirstName();
this.lastName = getLastName();
this.emailAddress = getEmailAddress();
this.musicTypes = request.getParameterValues("music"); //getMusic();
this.user = new User(firstName,lastName,emailAddress);
}
private String getFirstName()
{
return request.getParameter("firstName");
}
private String getLastName()
{
return request.getParameter("lastName");
}
private String getEmailAddress()
{
return request.getParameter("emailAddress");
}
private void writeDataToFile() throws IOException
{
String path = getRelativeFileName();
UserIO.add(user,path);
}
private String getRelativeFileName()
{
ServletContext sc = getServletContext();
String path = sc.getRealPath("/WEB-INF/EmailList.txt");
return path;
}
private void forwardResponseToJSPpage() throws ServletException, IOException
{
if(this.emailAddress.isEmpty()||this.firstName.isEmpty()||this.lastName.isEmpty())
{
String url = "/validation_error.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request,response);
}
else
{
music = new Music(musicTypes);
HttpSession session = this.request.getSession();
session.setAttribute("music", music);
session.setAttribute("user", user);
String url = "/display_email_entry.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request,response);
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
doPost(request,response);
}
}
2nd JSP:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# include file="/header.html" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Email Application</title>
</head>
<body>
<h1>Thanks for joining our email list</h1>
<p>Here is the information that you entered:</p>
<jsp:useBean id="user" scope="session" class="business.User"/>
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<td align="right">First name:</td>
<td><jsp:getProperty name="user" property="firstName"/></td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><jsp:getProperty name="user" property="lastName"/></td>
</tr>
<tr>
<td align="right">Email Address:</td>
<td><jsp:getProperty name="user" property="emailAddress"/></td>
</tr>
</table>
<p>We'll use the Email to otify you whenever we have new releases of the following types of music:</p>
<c:forEach items="${music.musicTypes}" var="i">
<c:out value="${i}"></c:out><br/>
</c:forEach>
<p>To enter another email address, click on the Back <br>
button in your browser or the Return button shown <br>
below.</p>
<form action="join_email_list.jsp" method="post">
<input type="submit" value="Return">
</form>
</body>
<%# include file="/footer.html" %>
</html>
Related
I have a Person.class with parameters: name, age, email and I have a jsp form for adding new user into ArrayList
#WebServlet(urlPatterns = "/addclientform.jsp")
public class AddClientServlet extends HttpServlet {
private PersonStorage personlist1 = new PersonStorage();
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
int age = Integer.parseInt(req.getParameter("age"));
String email = req.getParameter("email");
Person person = new Person(name, age, email);
personlist1.addPerson(person);
req.setAttribute("list", personlist1);
req.getRequestDispatcher("clientList.jsp").forward(req,resp);
}
}
<html>
<head>
<title>Clien Page</title>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Email</th>
</tr>
<c:forEach items="${list}" var="personlist">
<tr>
<td>${personlist.name}</td>
<td>${personlist.age}</td>
<td>${personlist.email}</td>
</tr>
</c:forEach>
</table>
<form name="home" action="home.jsp" method="post">
<input type="submit" value="back">
</form>
</body>
</html>
but when I want to see all users I cannot do this.
Where I made a mistake?
You need to add the following directive at the top of the page:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
I made a form submit application via Spring MVC. After submitting the form, all values of input fields are visible in url.
let's suppose that after submitting the generated URL is this:
SpringTuto/successA?name=FirstUser&designation=Student&country=XYZ&dob=2018%2F01%2F16&skills=paragliding&address.street_name=avenue+Road&address.city=New+City&address.district=New+District&address.pin_code=322343
From the above url, I want to encode name, designation, country and all other parameters in some encrypted code.
After reading a few articles, i came to an understanding that I will use the URIeditor(org.springframework.beans.propertyeditors.URIEditor) to encode. But I don't know how to use it. If anyone has another way to do this please share it.
Thanks in advance.
Here is my Controller Class.
#Controller
public class SpgController {
#ModelAttribute("header")
public Model addHeader(Model view) {
int a = 10;
return view.addAttribute(a);
}
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/mm/dd");
binder.registerCustomEditor(Date.class, "dob", new CustomDateEditor(dateFormat, false));
binder.registerCustomEditor(String.class, "name" , new NamepropertyEditor());
}
#RequestMapping("/main")
public ModelAndView go() {
ModelAndView view = new ModelAndView("main");
return view;
}
#RequestMapping(value = "/successA", method = RequestMethod.GET)
public ModelAndView method(#Valid #ModelAttribute("bean") Bean bean, BindingResult result ) {
if (result.hasErrors()) {
ModelAndView view = new ModelAndView("main");
return view;
}
ModelAndView view = new ModelAndView("successAnother");
return view;
}
}
Here is the successAnother.jsp page
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form >
Name: ${bean.name}<br/>
Designation: ${bean.designation}<br/>
DoB: ${bean.dob}<br/>
Skills: ${bean.skills}<br/>
Street: ${bean.address.street_name}<br/>
City: ${bean.address.city}<br/>
District: ${bean.address.district}<br/>
PinCode: ${bean.address.pin_code}<br/>
Country: ${bean.country}<br/>
</form>
</body>
</html>
Here is main.jsp(Application form)
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://www.springframework.org/tags" prefix = "spring" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring</title>
</head>
<body>
English|French|Hindi
<h3>${msg}</h3>
<form:errors path = "bean.*"/>
<form action="successA" method="get">
<table>
<tr>
<td><spring:message code = "label.userName"/><input type="text" name="name">
</td>
</tr>
<tr>
<td><spring:message code = "label.userDesignation"/><input type="text" name="designation">
</td>
</tr>
<tr>
<td><spring:message code = "label.userCountry"/><input type="text" name="country">
</td>
</tr>
<tr>
<td>
<spring:message code = "label.userDoB"/><input type= "text" name = "dob" >
</td>
</tr>
<tr>
<td>
<spring:message code = "label.Skils"/><select name = "skills" multiple >
<option value= "driving">Driving</option>
<option value = "diving">Diving</option>
<option value = "swimming">Swimming</option>
<option value = "paragliding">Paragliding</option>
</select>
</td>
</tr>
<tr>
<td>
<h5><spring:message code = "label.userAddress"/></h5>
<spring:message code = "label.userStreetname"/><input type = "text" name = "address.street_name">
<spring:message code = "label.userCity"/> <input type = "text" name = "address.city">
<spring:message code = "label.userDistrict"/><input type = "text" name = "address.district">
<spring:message code = "label.userPin"/><input type = "text" name = "address.pin_code">
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td><input type="submit" value=<spring:message code = "label.userSubmit"/>></td>
</tr>
</table>
</form>
</body>
</html>
If your application supports HTTPS, then it can be achieved easily using spring security by doing some configuration as follows.
<http>
<intercept-url pattern="/**" access="ROLE_USER" requires-channel="https"/>
...
</http>
Integrating spring security with spring mvc is very simple.
I've got problem with my project. (It is my first Spring project, sorry for messy code). I want to insert values from form to DB, (for that moment they are working inputs called "nameHosp", "namePat", "surnamePat","peselPat"). And the problem is passing value from select options form. Result of submiting is "null" in column called "nameHosp"
Form
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
`<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
`
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<sf:form action="${pageContext.request.contextPath}/create"
method="post" modelAttribute="combinedCommand" >
<table style="margin-right: auto; margin-left: auto;" width="100%">
<tr><sf:form modelAttribute="combinedCommand">
<td colspan="5"><strong>Szpital zamawiający</strong><br /> <br />
<sf:select path="${getHospitals}">
<sf:option value="NONE"> --Wybierz Szpital--</sf:option>
<sf:options items="${hospitals}" itemValue="nameHosp" itemLabel="nameHosp"></sf:options>
</sf:select></sf:form>
</tr>
<tr>
<th>Dane pacjenta</th>
<th colspan="4">Zamówienie</th>
</tr>
<tr>
<td>Imię:<br /> <sf:input path="${namePat}" name="namePat"
type="text" />
</td>
<td>KKCz</td>
<td><input name="iloscKKCz" size="1" type="text" /> jednostek.
</td>
<td><input name="ED5" type="checkbox" value="86" />
Ubogoleukocytarny</td>
<td><input name="EC2" type="checkbox" value="26" />
Napromieniowany</td>
</tr>
<tr>
<td>Nazwisko:<br /> <sf:input path="${surnamePat}"
name="surnamePat" type="text" />
</td>
<td>PLT</td>
<td><input name="iloscPLT" size="1" type="text" /> jednostek.
</td>
<td><input name="ED5" type="checkbox" value="86" />
Ubogoleukocytarny</td>
<td><input name="EC2" type="checkbox" value="26" />
Napromieniowany</td>
</tr>
<tr>
<td>PESEL:<br /> <sf:input path="${peselPat}" name="peselPat"
type="text" />
</table>
</sf:form>
Controller
#Controller
public class Controlling {
#Autowired
private Servicu servicu;
#Autowired
public void setServicu(Servicu servicu) {
this.servicu = servicu;
}
#RequestMapping("/")
public String showHome(Model model) {
return "home";
}
#RequestMapping("/orderForm")
public String showForm(Model model){
List<Hospitals> hospital = servicu.getCurrent();
model.addAttribute("combinedCommand", new CombinedCommand());
model.addAttribute("hospitals", hospital);
model.addAttribute("ordersPatient", new OrdersPatient());
return "orderForm";
}
#RequestMapping(value="/create", method=RequestMethod.POST)
public String doCreate( Hospitals hospitals,
Model model,
OrdersPatient ordersPatient,
Orders orders,
BindingResult result) {
if(result.hasErrors()) {
return "error";
}else{
model.addAttribute("nameHosp",hospitals);
// model.addAttribute("combinedCommand", new CombinedCommand());
model.addAttribute("ordersPatient", new OrdersPatient());
servicu.create(ordersPatient);
// servicu.create(orders);
return "success";
}
DAO
#Component("offersDAO")
public class OffersDAO {
private NamedParameterJdbcTemplate jdbc;
#Autowired
public void setDataSource(DataSource jdbc) {
this.jdbc = new NamedParameterJdbcTemplate(jdbc);
}
public List<Hospitals> getHosps() {
return jdbc.query("select nameHosp from hospitals", new RowMapper<Hospitals>() {
public Hospitals mapRow(ResultSet rs, int rowNum) throws SQLException {
Hospitals hospital = new Hospitals("nameHosp");
hospital.setNameHosp(rs.getString("nameHosp"));
return hospital;
}
});
}
public boolean createPatient(OrdersPatient ordersPatient){
BeanPropertySqlParameterSource param = new BeanPropertySqlParameterSource(ordersPatient);
return jdbc.update("insert into patient (idOrd,nameHosp,namePat,surnamePat,peselPat) values (:idOrd,:nameHosp,:namePat,:surnamePat,:peselPat)", param)==1;
}
Try to add name="nameHosp" to the select. Like this.
<sf:select path="${getHospitals}" name="nameHosp">
<sf:option value="NONE"> --Wybierz Szpital--</sf:option>
<sf:options items="${hospitals}" itemValue="nameHosp" itemLabel="nameHosp"></sf:options>
</sf:select></sf:form>
I am getting an error that says:
/WEB-INF/jsps/createoffer.jsp (line: 29, column: 67) quote symbol expected
from what I read in the java spring documentations the below is correct. The app runs until I select the link to the form on the index.jsp page.
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="${pageContext.request.contextPath}/static/css/main.css"
rel="stylesheet" type="text/css" />
<title>My form</title>
</head>
<body>
<sf:form method="post"
action="${pageContext.request.contextPath}/docreate" commandName="offer">
<table class="formtable">
<tr>
<td class="label">Name:</td>
<td><sf:input class="control" path="name" name="name" type="text" /></td>
</tr>
<tr>
<td class="label">email:</td>
<td><sf:input class="control" path="email" name="email" type="text" /></td>
</tr>
<tr>
<td class="label">your offer:</td>
<td><sf:textarea class="control" path="text" name="text" rows=10 cols=10 /></td>
</tr>
<tr>
<td></td>
<td><input name="Create Offer" type="submit" /></td>
</tr>
</table>
</sf:form>
</body>
</html>
from OffersController.java
#RequestMapping("/createoffer")
public String createOffer(Model model) {
model.addAttribute("offer", new Offer());
/*List<Offer> offers = offersService.getCurrent();
model.addAttribute("offers", offers);
*/
return "createoffer";
}
Offer Bean
#Component
public class Offer {
private int id;
#Size(min = 5, max = 25, message = "Name is not vaild")
private String name;
#NotNull
#Email(message = "Is not a vaild email address")
private String email;
private String text;
public Offer() {
}
I don't have enough points to add comment. Can you double check that row=10 is same with row="10" in that jsp file? The error message seems like a syntax problem in the jsp.
Getting error:
java.lang.IllegalStateException: getAttributeNames: Session already invalidated.After logout from parent window.
LogOutUserAction.java
public String execute() throws Exception {
System.out.println("inside :: LogOutUserAction------");
//HttpServletRequest request = null;
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session =request.getSession(true);
session.removeAttribute("loggedInUser");
request.getSession(false).invalidate();
session=null;
return "logout";
}
LoginInterceptor
public String intercept(ActionInvocation invocation) throws Exception {
final ActionContext context = invocation.getInvocationContext();
HttpServletRequest request = (HttpServletRequest) context
.get(HTTP_REQUEST);
HttpServletResponse response = (HttpServletResponse) context
.get(HTTP_RESPONSE);
HttpSession session = request.getSession(true);
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
/*user logged out from the parent window then set the message
for click on the popup window*/
if(session == null){
System.out.println("set the attribute");
request.setAttribute("SessionExpired","Your have already logged out");
}
Object user = session.getAttribute(USER_HANDLE);
String loginOut = request.getParameter(LOGIN_OUT);
System.out.println("loginOut---->"+loginOut);
if (user == null) {
// The user has not logged in yet.
System.out.println(" inside if ");
// Is the user attempting to log in right now?
String loginAttempt = request.getParameter(LOGIN_ATTEMPT);
/* The user is attempting to log in. */
if (!StringUtils.isBlank(loginAttempt)) {
return invocation.invoke();
}
return "login";
} else {
return invocation.invoke();
}
}
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="sx" uri="/struts-dojo-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
if (request.getAttribute("SessionExpired")!= null)
{
System.out.println("After Session invalid");
}
%>
<html>
<head>
<title>Login</title>
<sx:head cache="true"/>
<script type="text/javascript">
</script>
<script type="text/javascript" language="javascript" src="js/login.js"></script>
<style type="text/css">
.style1 {font-family: Verdana, Arial, Helvetica, sans-serif}
.style2 {
color: #000099
}
</style>
</head>
<body bgcolor="#CODFFD" background="<%request.getContextPath();%>images/watermark_new.jpg">
<br>
<br>
<br>
<br>
<br>
<br>
<div align="center"><span class="style1">USER LOGIN</span>
<br>
<br>
<br>
<s:form action="checkUserLogin.action" validate="true" name = "loginForm">
<s:hidden name="loginAttempt" value="%{'1'}" />
<table border="0" cellspacing="1" cellpadding="0" width="350" >
<tr>
<td align="center">
<b>Login ID</b>
</td>
<td>
<table>
<s:textfield id="id" name="loginId" value="" />
</table>
</td>
</tr>
<tr>
<td align="center">
<b>Password</b>
</td>
<td>
<table>
<s:password id="password" name="loginPassword" value="" showPassword="true"/>
</table>
</td>
</tr>
<tr><td colspan="2" align="center">
<table>
<s:submit value="Login" onclick = "return getRoleList()"/>
</table>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<table>
<s:a href="changePasswordScreen.action" >Change Password</s:a>
</table>
</td>
</tr>
</table>
</s:form>
</div>
<br>
<br>
<br>
</body>
</html>
Need to display message on popup window (when i click on any link) as i mentioned on my login jsp after logout from parent window.
Interceptors can execute code before and after an Action is invoked. When is yours being invoked? I would imagine what's happening is this:
In LogOutUserAction.java you invalidate the session
LoginInterceptor.intercept is then executed. This tries to get an attribute from the session object that you invalidated hence the IllegalStateException.
Why are you invalidating the session? Your LoginInterceptor is using the presence of the USER_HANDLE attribute to indicate whether or not the user is logged in. I would remove this attribute in your LogOutUserAction but don't invalidate the session.